Compare commits

..
Author SHA1 Message Date
Eiren Rain 12354f0a95 Implement crude CSV tracker data collection 2026-01-27 10:45:48 +01:00
1013 changed files with 62868 additions and 36494 deletions

No files matched your search

+5 -4
View File
@@ -1,9 +1,10 @@
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 rust-toolchain.toml
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
+7 -5
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,12 @@
/gui/src/components/settings/ @Erimelowo @loucass003
# Electron part of the GUI
/gui/electron/ @loucass003
# Rust part of the GUI
/gui/src-tauri/ @loucass003
/Cargo.lock @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
@@ -27,8 +31,6 @@
/server/src/main/java/dev/slimevr/tracking/processor/ @Erimelowo
/server/src/main/java/dev/slimevr/filtering/ @Erimelowo
/bindings-provider/ @ImSapphire
# Linux files
*.nix @loucass003
/flake.lock @loucass003
+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*"]
+129
View File
@@ -0,0 +1,129 @@
name: Build GUI
on:
push:
branches:
- main
paths:
- .github/workflows/build-gui.yml
- gui/**
- package*.json
pull_request:
paths:
- .github/workflows/build-gui.yml
- gui/**
- package*.json
workflow_dispatch:
create:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
submodules: recursive
- uses: pnpm/action-setup@v4
- name: Use Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Build
run: |
pnpm i
cd gui
pnpm run lint
build:
strategy:
fail-fast: false
matrix:
os:
[
ubuntu-22.04,
windows-latest,
macos-latest,
ubuntu-22.04-arm,
windows-11-arm,
]
runs-on: ${{ matrix.os }}
env:
# Don't mark warnings as errors
CI: false
BUILD_ARCH: ${{ endsWith(matrix.os, 'arm') && 'aarch64' || 'amd64' }}
steps:
- uses: actions/checkout@v6
with:
submodules: recursive
- if: startsWith(matrix.os, 'ubuntu')
name: Set up Linux dependencies
uses: awalsh128/[email protected]
with:
packages: libgtk-3-dev webkit2gtk-4.1 libappindicator3-dev librsvg2-dev patchelf
# Increment to invalidate the cache
version: ${{ format('v1.0-{0}', env.BUILD_ARCH) }}
# Enables a workaround to attempt to run pre and post install scripts
execute_install_scripts: true
# Disables uploading logs as a build artifact
debug: false
- if: matrix.os == 'windows-11-arm'
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
cache: false
- name: Cache cargo dependencies
uses: Swatinem/rust-cache@v2
- uses: pnpm/action-setup@v4
- name: Use Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
shell: bash
run: pnpm i
- name: Build
shell: bash
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
NODE_OPTIONS: ${{ matrix.os == 'macos-latest' && '--max-old-space-size=4096' || '' }}
run: pnpm run skipbundler --config $( ./gui/scripts/gitversion.mjs )
- if: startsWith(matrix.os, 'windows')
name: Upload a Build Artifact (Windows)
uses: actions/upload-artifact@v6
with:
# Artifact name
name: ${{ format('SlimeVR-GUI-Windows-{0}', env.BUILD_ARCH) }}
# A file, directory or wildcard pattern that describes what to upload
path: target/release/slimevr.exe
- if: startsWith(matrix.os, 'ubuntu')
name: Upload a Build Artifact (Linux)
uses: actions/upload-artifact@v6
with:
# Artifact name
name: ${{ format('SlimeVR-GUI-Linux-{0}', env.BUILD_ARCH) }}
# A file, directory or wildcard pattern that describes what to upload
path: target/release/slimevr
- if: matrix.os == 'macos-latest'
name: Upload a Build Artifact (macOS)
uses: actions/upload-artifact@v6
with:
# Artifact name
name: SlimeVR-GUI-macOS
# A file, directory or wildcard pattern that describes what to upload
path: target/release/slimevr
-342
View File
@@ -1,342 +0,0 @@
name: SlimeVR Full Build
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
workflow_dispatch:
jobs:
setup-matrix:
name: Configure Build Matrix
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
matrix-cpp: ${{ steps.set-matrix.outputs.matrix-cpp }}
steps:
- id: set-matrix
shell: bash
run: |
BASE='[{"os":"ubuntu-22.04","platform":"linux"},{"os":"windows-latest","platform":"windows"},{"os":"macos-latest","platform":"macos"}]'
EXTRA='[{"os":"ubuntu-22.04-arm","platform":"linux"},{"os":"windows-11-arm","platform":"windows"}]'
if [[ "${{ github.ref }}" == refs/tags/v* || "${{ github.ref }}" == refs/heads/main || "${{ github.event_name }}" == "workflow_dispatch" ]]; then
RESULT=$(echo "$BASE $EXTRA" | jq -c -s 'add')
else
RESULT=$(echo "$BASE" | jq -c '.')
fi
RESULT_CPP=$(echo "$RESULT" | jq -c '[ .[] | select ( (.platform != "macos") and ( (.platform != "windows") or (.os | endswith("-arm") | not) ) ) ]')
echo "matrix={\"include\":$RESULT}" >> "$GITHUB_OUTPUT"
echo "matrix-cpp={\"include\":$RESULT_CPP}" >> "$GITHUB_OUTPUT"
build-bindings-provider:
name: Build bindings provider for ${{ matrix.os }}
needs: [setup-matrix]
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix-cpp) }}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
submodules: recursive
- if: matrix.platform == 'linux'
name: Install GCC
uses: egor-tensin/setup-gcc@v2
with:
version: 16
- name: Get CMake
uses: lukka/get-cmake@latest
- name: Configure
run: cmake -S bindings-provider/ -B bindings-provider/build -DCMAKE_BUILD_TYPE=Release
- name: Build
run: cmake --build bindings-provider/build --config Release -j6
- name: Upload artifact
uses: actions/upload-artifact@v7
with:
name: bindings-provider-${{ matrix.platform }}-${{ matrix.os }}
path: |
bindings-provider/build/slimevr-bindings-provider
bindings-provider/build/libopenvr_api.so
bindings-provider/build/Release/SlimeVR-Bindings-Provider.exe
bindings-provider/build/openvr_api.dll
gui-checks:
name: Gui Checks
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
with:
submodules: recursive
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Setup PNPM
uses: pnpm/action-setup@v6
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: GUI Lint
run: pnpm i && pnpm run lint
server-checks:
name: Server Checks
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
with:
submodules: recursive
- name: Set up JDK 24
uses: actions/setup-java@v5
with:
java-version: '24'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
- name: Server Spotless Check
run: ./gradlew spotlessCheck --build-cache
- name: Server Detekt Lint
run: ./gradlew :server:detekt --build-cache
build-server-jar:
name: Build Desktop Server
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
with:
submodules: recursive
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Set up JDK 24
uses: actions/setup-java@v5
with:
java-version: '24'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
- name: Build ShadowJar
run: ./gradlew :server:desktop:shadowJar --build-cache
- name: Test with Gradle
run: ./gradlew :server:desktop:test
- name: Upload Server Jar
uses: actions/upload-artifact@v7
with:
name: server-jar
path: |
server/desktop/build/libs/slimevr.jar
server/core/resources
build-gui-frontend:
name: Build GUI Assets
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
with:
submodules: recursive
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Setup PNPM
uses: pnpm/action-setup@v6
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Build JS
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
run: pnpm i && pnpm run build
- name: Tar GUI Dist
run: tar -czf slimevr-gui-dist.tar.gz -C gui/electron/out .
- name: Upload GUI Dist
uses: actions/upload-artifact@v7
with:
name: gui-dist
path: slimevr-gui-dist.tar.gz
package-desktop:
name: Package Desktop (${{ matrix.platform }} - ${{ matrix.os }})
needs: [setup-matrix, build-server-jar, build-gui-frontend, build-bindings-provider]
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix) }}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
submodules: recursive
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Setup PNPM
uses: pnpm/action-setup@v6
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Download Server Jar
uses: actions/download-artifact@v8
with:
name: server-jar
path: server
- if: contains(fromJson(needs.setup-matrix.outputs.matrix-cpp).include.*.os, matrix.os)
name: Download bindings provider artifact
uses: actions/download-artifact@v8
with:
name: bindings-provider-${{ matrix.platform }}-${{ matrix.os }}
path: bindings-provider/build/${{ matrix.platform == 'windows' && 'win' || 'linux' }}-${{ endsWith(matrix.os, '-arm') && 'arm64' || 'x64' }}
- name: Download GUI Dist
uses: actions/download-artifact@v8
with:
name: gui-dist
- name: Extract GUI for Electron
shell: bash
run: mkdir -p gui/electron/out && tar -xzf slimevr-gui-dist.tar.gz -C gui/electron/out
- name: Run Electron Builder
shell: bash
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
run: |
mkdir -p gui/electron/dist/artifacts/linux/ \
gui/electron/dist/artifacts/win \
gui/electron/dist/artifacts/mac
VERSION=$(git --no-pager tag --sort -taggerdate --points-at HEAD | head -1)
[ -z "$VERSION" ] && VERSION="0.0.0"
VERSION="${VERSION#v}"
echo "Building version: $VERSION"
pnpm i
cd gui/electron
pnpm exec electron-builder --${{ matrix.platform }} \
${{ matrix.platform == 'macos' && '--universal' || '' }} \
--config.extraMetadata.version="$VERSION" \
--publish never
- name: Collect and Rename Artifacts
shell: bash
run: |
SRC_DIR="${{ github.workspace }}/gui/electron/dist/artifacts"
DEST_DIR="${{ github.workspace }}/release-out"
mkdir -p "$DEST_DIR"
if [ "${{ matrix.platform }}" == "windows" ]; then
[[ "${{ matrix.os }}" == *"arm"* ]] && SUFFIX="win-aarch64" || SUFFIX="win64"
cp "$SRC_DIR"/win/*.zip "$DEST_DIR/SlimeVR-$SUFFIX.zip"
elif [ "${{ matrix.platform }}" == "linux" ]; then
for f in "$SRC_DIR"/linux/*; do
[ -d "$f" ] && continue
BASE=$(basename "$f")
NEW_NAME=$(echo "$BASE" | sed -e 's/x86_64/amd64/g' -e 's/arm64/aarch64/g')
cp "$f" "$DEST_DIR/$NEW_NAME"
done
elif [ "${{ matrix.platform }}" == "macos" ]; then
cp "$SRC_DIR"/mac/*.dmg "$DEST_DIR/SlimeVR-mac.dmg"
fi
echo "Collected files:"
ls -lh "$DEST_DIR"
- name: Upload For Release
uses: actions/upload-artifact@v7
with:
name: release-${{ matrix.platform }}-${{ matrix.os }}
path: release-out/*
bundle-android:
name: Build Android APK
needs: [build-gui-frontend]
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
with:
submodules: recursive
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Set up JDK 24
uses: actions/setup-java@v5
with:
java-version: '24'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v6
- name: Download GUI Dist
uses: actions/download-artifact@v8
with:
name: gui-dist
- name: Extract GUI for Android
run: mkdir -p gui/electron/out && tar -xzf slimevr-gui-dist.tar.gz -C gui/electron/out
- name: Build APK
run: ./gradlew :server:android:build --build-cache
env:
ANDROID_STORE_FILE: ${{ secrets.ANDROID_STORE_FILE }}
ANDROID_STORE_PASSWD: ${{ secrets.ANDROID_STORE_PASSWD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWD: ${{ secrets.ANDROID_KEY_PASSWD }}
- name: Test with Gradle
run: ./gradlew test
- name: Prepare APK
run: cp server/android/build/outputs/apk/release/*.apk ./SlimeVR-android.apk
- name: Upload APK
uses: actions/upload-artifact@v7
with:
name: release-android
path: SlimeVR-android.apk
- name: Build Google Play release bundle
if: startsWith(github.ref, 'refs/tags/')
run: ./gradlew :server:android:bundleRelease
env:
ANDROID_STORE_FILE: ${{ secrets.ANDROID_GPLAY_STORE_FILE }}
ANDROID_STORE_PASSWD: ${{ secrets.ANDROID_GPLAY_STORE_PASSWD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_GPLAY_KEY_ALIAS }}
ANDROID_KEY_PASSWD: ${{ secrets.ANDROID_GPLAY_KEY_PASSWD }}
- name: Upload the Google Play artifact
uses: actions/upload-artifact@v7
if: startsWith(github.ref, 'refs/tags/')
with:
# Artifact name
name: 'SlimeVR-Android-GPDev' # optional, default is artifact
# A file, directory or wildcard pattern that describes what to upload
path: server/android/build/outputs/bundle/release/*
create-release:
name: Finalize Release Draft
needs: [package-desktop, bundle-android, build-server-jar, build-gui-frontend]
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
steps:
- name: Download All Release Artifacts
uses: actions/download-artifact@v8
with:
pattern: release-*
path: release-out
merge-multiple: true
- name: Download Server Jar
uses: actions/download-artifact@v8
with:
name: server-jar
path: server
- name: Download GUI Dist
uses: actions/download-artifact@v8
with:
name: gui-dist
- name: Create GitHub Release
uses: softprops/action-gh-release@v3
with:
draft: true
generate_release_notes: true
files: |
release-out/*
server/desktop/build/libs/slimevr.jar
slimevr-gui-dist.tar.gz
@@ -20,13 +20,13 @@ jobs:
run: |
npx @slimevr/update-manifest-generator@latest
- uses: actions/upload-artifact@v7
- uses: actions/upload-artifact@v6
with:
name: "update-manifest.json"
path: ./update-manifest.json
- name: Upload update-manifest.json to release
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ secrets.UPDATE_MANIFEST_RELEASE_TAG }}
files: ./update-manifest.json
+413
View File
@@ -0,0 +1,413 @@
# This workflow will build a Java project with Gradle
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: SlimeVR Server
on:
push:
branches:
- main
pull_request:
workflow_dispatch:
create:
jobs:
test:
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v6
with:
submodules: recursive
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Set up JDK 17
uses: actions/setup-java@v5
with:
java-version: '17'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
- run: mkdir ./gui/dist && touch ./gui/dist/somefile
shell: bash
- name: Check code formatting
run: ./gradlew spotlessCheck
- name: Test with Gradle
run: ./gradlew test
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
submodules: recursive
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Set up JDK 17
uses: actions/setup-java@v5
with:
java-version: '17'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
- name: Build with Gradle
run: ./gradlew :server:desktop:shadowJar
- name: Upload the Server JAR as a Build Artifact
uses: actions/upload-artifact@v6
with:
# Artifact name
name: 'SlimeVR-Server' # optional, default is artifact
# A file, directory or wildcard pattern that describes what to upload
path: server/desktop/build/libs/slimevr.jar
- name: Upload to draft release
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
generate_release_notes: true
files: |
server/desktop/build/libs/slimevr.jar
bundle-android:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
submodules: recursive
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Set up JDK 17
uses: actions/setup-java@v5
with:
java-version: '17'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
- uses: pnpm/action-setup@v4
- name: Use Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
run: pnpm i
- name: Build GUI
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
run: cd gui && pnpm run build
- name: Build with Gradle
run: ./gradlew :server:android:build
env:
ANDROID_STORE_FILE: ${{ secrets.ANDROID_STORE_FILE }}
ANDROID_STORE_PASSWD: ${{ secrets.ANDROID_STORE_PASSWD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWD: ${{ secrets.ANDROID_KEY_PASSWD }}
- name: Upload the Android build artifact
uses: actions/upload-artifact@v6
with:
# Artifact name
name: 'SlimeVR-Android' # optional, default is artifact
# A file, directory or wildcard pattern that describes what to upload
path: server/android/build/outputs/apk/*
- name: Prepare for release
if: startsWith(github.ref, 'refs/tags/')
run: |
cp server/android/build/outputs/apk/release/android-release.apk ./SlimeVR-android.apk
- name: Upload to draft release
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
generate_release_notes: true
files: |
./SlimeVR-android.apk
- name: Build Google Play release bundle
if: startsWith(github.ref, 'refs/tags/')
run: ./gradlew :server:android:bundleRelease
env:
ANDROID_STORE_FILE: ${{ secrets.ANDROID_GPLAY_STORE_FILE }}
ANDROID_STORE_PASSWD: ${{ secrets.ANDROID_GPLAY_STORE_PASSWD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_GPLAY_KEY_ALIAS }}
ANDROID_KEY_PASSWD: ${{ secrets.ANDROID_GPLAY_KEY_PASSWD }}
- name: Upload the Google Play artifact
uses: actions/upload-artifact@v6
if: startsWith(github.ref, 'refs/tags/')
with:
# Artifact name
name: 'SlimeVR-Android-GPDev' # optional, default is artifact
# A file, directory or wildcard pattern that describes what to upload
path: server/android/build/outputs/bundle/release/*
bundle-linux:
strategy:
matrix:
os: [ubuntu-latest, ubuntu-24.04-arm]
runs-on: ${{ matrix.os }}
needs: [build, test]
if: contains(fromJSON('["workflow_dispatch", "create"]'), github.event_name)
env:
BUILD_ARCH: ${{ endsWith(matrix.os, 'arm') && 'aarch64' || 'amd64' }}
steps:
- uses: actions/checkout@v6
with:
submodules: recursive
- uses: actions/download-artifact@v7
with:
name: 'SlimeVR-Server'
path: server/desktop/build/libs/
- name: Set up Linux dependencies
uses: awalsh128/[email protected]
with:
packages: |
build-essential curl wget file libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev xdg-utils
# Increment to invalidate the cache
version: ${{ format('v1.0-{0}', env.BUILD_ARCH) }}
# Enables a workaround to attempt to run pre and post install scripts
execute_install_scripts: true
# Disables uploading logs as a build artifact
debug: false
- name: Set up specific Linux versioned dependencies
run: |
sudo apt-get update && sudo apt-get install -y \
libwebkit2gtk-4.1-0=2.44.0-2 \
libwebkit2gtk-4.1-dev=2.44.0-2 \
libjavascriptcoregtk-4.1-0=2.44.0-2 \
libjavascriptcoregtk-4.1-dev=2.44.0-2 \
gir1.2-javascriptcoregtk-4.1=2.44.0-2 \
gir1.2-webkit2-4.1=2.44.0-2;
- name: Cache cargo dependencies
uses: Swatinem/rust-cache@v2
- uses: pnpm/action-setup@v4
- name: Use Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
run: pnpm i
- name: Build
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
run: pnpm run tauri build --config $( ./gui/scripts/gitversion.mjs )
- name: Make GUI tarball
run: |
tar czf slimevr-gui-dist.tar.gz -C gui/dist/ .
- uses: actions/upload-artifact@v6
if: matrix.os == 'ubuntu-latest'
with:
name: SlimeVR-GUI-Dist
path: ./slimevr-gui-dist.tar.gz
- uses: actions/upload-artifact@v6
with:
name: ${{ format('SlimeVR-GUI-Deb-{0}', env.BUILD_ARCH) }}
path: target/release/bundle/deb/slimevr*.deb
- uses: actions/upload-artifact@v6
with:
name: ${{ format('SlimeVR-GUI-AppImage-{0}', env.BUILD_ARCH) }}
path: target/release/bundle/appimage/slimevr*.AppImage
- uses: actions/upload-artifact@v6
with:
name: ${{ format('SlimeVR-GUI-RPM-{0}', env.BUILD_ARCH) }}
path: target/release/bundle/rpm/slimevr*.rpm
- name: Prepare for release
if: startsWith(github.ref, 'refs/tags/')
run: |
cp target/release/bundle/appimage/slimevr*.AppImage "./SlimeVR-$BUILD_ARCH.appimage"
cp target/release/bundle/deb/slimevr*.deb "./SlimeVR-$BUILD_ARCH.deb"
cp target/release/bundle/rpm/slimevr*.rpm "./SlimeVR-$BUILD_ARCH.rpm"
- name: Upload to draft release
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
generate_release_notes: true
files: |
./slimevr-gui-dist.tar.gz
./SlimeVR-*.appimage
./SlimeVR-*.deb
./SlimeVR-*.rpm
bundle-mac:
runs-on: macos-latest
needs: [build, test]
if: contains(fromJSON('["workflow_dispatch", "create"]'), github.event_name)
steps:
- uses: actions/checkout@v6
with:
submodules: recursive
- uses: actions/download-artifact@v7
with:
name: 'SlimeVR-Server'
path: server/desktop/build/libs/
- name: Cache cargo dependencies
uses: Swatinem/rust-cache@v2
- uses: pnpm/action-setup@v4
- name: Use Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
run: |
rustup target add x86_64-apple-darwin
pnpm i
- name: Build
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
NODE_OPTIONS: --max-old-space-size=4096
run: pnpm run tauri build --target universal-apple-darwin --config $( ./gui/scripts/gitversion.mjs )
- name: Modify Application
run: |
cd target/universal-apple-darwin/release/bundle/macos/slimevr.app/Contents/MacOS
cp $( git rev-parse --show-toplevel )/server/desktop/build/libs/slimevr.jar ./
cd ../../../
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName SlimeVR" slimevr.app/Contents/Info.plist
/usr/libexec/PlistBuddy -c "Set :CFBundleName SlimeVR" slimevr.app/Contents/Info.plist
codesign --sign - --deep --force slimevr.app
mv slimevr.app SlimeVR.app
cd ../dmg/
./bundle_dmg.sh --volname SlimeVR --icon slimevr 180 170 --app-drop-link 480 170 \
--window-size 660 400 --hide-extension ../macos/SlimeVR.app \
--volicon ../macos/SlimeVR.app/Contents/Resources/icon.icns --skip-jenkins \
--eula ../../../../../LICENSE-MIT slimevr.dmg ../macos/SlimeVR.app
- uses: actions/upload-artifact@v6
with:
name: SlimeVR-GUI-MacApp
path: target/universal-apple-darwin/release/bundle/macos/SlimeVR*.app
- uses: actions/upload-artifact@v6
with:
name: SlimeVR-GUI-MacDmg
path: target/universal-apple-darwin/release/bundle/dmg/slimevr.dmg
- name: Prepare for release
if: startsWith(github.ref, 'refs/tags/')
run: |
cp target/universal-apple-darwin/release/bundle/dmg/slimevr.dmg ./SlimeVR-mac.dmg
- name: Upload to draft release
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
generate_release_notes: true
files: |
./SlimeVR-mac.dmg
bundle-windows:
strategy:
matrix:
os: [windows-latest, windows-11-arm]
runs-on: ${{ matrix.os }}
needs: [build, test]
if: contains(fromJSON('["workflow_dispatch", "create"]'), github.event_name)
env:
BUILD_ARCH: ${{ endsWith(matrix.os, 'arm') && 'win-aarch64' || 'win64' }}
steps:
- uses: actions/checkout@v6
with:
submodules: recursive
- uses: actions/download-artifact@v7
with:
name: 'SlimeVR-Server'
path: server/desktop/build/libs/
- if: matrix.os == 'windows-11-arm'
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
cache: false
- name: Cache cargo dependencies
uses: Swatinem/rust-cache@v2
- uses: pnpm/action-setup@v4
- name: Use Node.js
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Install dependencies
shell: bash
run: pnpm i
- name: Build
shell: bash
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
run: pnpm run skipbundler --config $( ./gui/scripts/gitversion.mjs )
- name: Bundle to zips
shell: bash
run: |
mkdir SlimeVR
cp gui/src-tauri/icons/icon.ico ./SlimeVR/run.ico
cp server/desktop/build/libs/slimevr.jar ./SlimeVR/slimevr.jar
cp server/core/resources/* ./SlimeVR/
cp target/release/slimevr.exe ./SlimeVR/
7z a -tzip "SlimeVR-$BUILD_ARCH.zip" ./SlimeVR/
- uses: actions/upload-artifact@v6
with:
name: ${{ format('SlimeVR-GUI-Windows-{0}', env.BUILD_ARCH) }}
path: ./SlimeVR*.zip
- name: Upload to draft release
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
generate_release_notes: true
files: ./SlimeVR-*.zip
+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 }}"
+5 -8
View File
@@ -4,10 +4,8 @@
# Syncthing ignore file
.stignore
# Ignore .idea, except shared project inspection profiles
.idea/*
!.idea/inspectionProfiles/
!.idea/inspectionProfiles/*.xml
# Ignore .idea
.idea
# Ignore .fleet
.fleet
@@ -36,6 +34,9 @@
# ignore gradle build folder
build/
# Rust build artifacts
/target
# direnv has been claimed for Nix usage
.direnv/
.devenv
@@ -45,7 +46,3 @@ local.properties
# Ignore temporary config
vrconfig.yml.tmp
# Nixos
.bin/
-3
View File
@@ -1,6 +1,3 @@
[submodule "solarxr-protocol"]
path = solarxr-protocol
url = https://github.com/SlimeVR/SolarXR-Protocol.git
[submodule "svr-bindings-provider/openvr"]
path = bindings-provider/openvr
url = https://github.com/ValveSoftware/openvr.git
-30
View File
@@ -1,30 +0,0 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="27ef4df3-2b89-390d-a9cd-ef29bd86503d" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="8d635bb8-7d4f-3af3-8d31-6f9164877ab2" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="ConvertLongToDuration" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SSBasedInspection" enabled="true" level="ERROR" enabled_by_default="true">
<searchConfiguration name="Use safeLaunch instead of raw launch" uuid="8d635bb8-7d4f-3af3-8d31-6f9164877ab2" description="Use dev.slimevr.util.safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." suppressId="RAW_LAUNCH_USAGE" problemDescriptor="Use safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." text="$scope$.launch { $statements$; }" recursive="true" caseInsensitive="false" type="Kotlin" pattern_context="default">
<constraint name="__context__" within="" contains="" />
<constraint name="scope" within="" contains="" />
<constraint name="statements" minCount="0" maxCount="2147483647" within="" contains="" />
</searchConfiguration>
<searchConfiguration name="Use safeLaunch instead of raw launch" uuid="0e4a6db4-4c7b-3fd4-99ce-2717fa0fd2fb" description="Use dev.slimevr.util.safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." suppressId="RAW_LAUNCH_USAGE" problemDescriptor="Use safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." text="launch { $statements$; }" recursive="true" caseInsensitive="false" type="Kotlin" pattern_context="default">
<constraint name="__context__" within="" contains="" />
<constraint name="statements" minCount="0" maxCount="2147483647" within="" contains="" />
</searchConfiguration>
<searchConfiguration name="Use safeLaunch instead of raw launch" uuid="27ef4df3-2b89-390d-a9cd-ef29bd86503d" description="Use dev.slimevr.util.safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." suppressId="RAW_LAUNCH_USAGE" problemDescriptor="Use safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." text="$scope$.launch($args$) { $statements$; }" recursive="true" caseInsensitive="false" type="Kotlin" pattern_context="default">
<constraint name="__context__" within="" contains="" />
<constraint name="scope" within="" contains="" />
<constraint name="args" maxCount="2147483647" within="" contains="" />
<constraint name="statements" minCount="0" maxCount="2147483647" within="" contains="" />
</searchConfiguration>
<searchConfiguration name="Use safeLaunch instead of raw launch" uuid="ca477c43-2f5b-3907-8b06-02c34dc26930" description="Use dev.slimevr.util.safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." suppressId="RAW_LAUNCH_USAGE" problemDescriptor="Use safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." text="launch($args$) { $statements$; }" recursive="true" caseInsensitive="false" type="Kotlin" pattern_context="default">
<constraint name="__context__" within="" contains="" />
<constraint name="args" maxCount="2147483647" within="" contains="" />
<constraint name="statements" minCount="0" maxCount="2147483647" within="" contains="" />
</searchConfiguration>
</inspection_tool>
</profile>
</component>
-7
View File
@@ -1,7 +0,0 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="PROJECT_PROFILE" value="Project Default" />
<option name="USE_PROJECT_PROFILE" value="true" />
<version value="1.0" />
</settings>
</component>
+1
View File
@@ -7,6 +7,7 @@
"gaborv.flatbuffers",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"rust-lang.rust-analyzer",
"bradlc.vscode-tailwindcss",
"EditorConfig.EditorConfig",
"macabeus.vscode-fluent",
-64
View File
@@ -1,64 +0,0 @@
# OpenCode Agent Instructions
## Environment & Tooling
- **Server (Kotlin/Java)**: Use `gradle` (`./gradlew`).
- Run: `./gradlew run`
- Build: `./gradlew shadowJar`
- Format: `./gradlew spotlessApply`
- **GUI (Electron/TS)**: Use `pnpm`.
- Install: `pnpm i`
- Dev: `pnpm gui`
- Build: `pnpm package:build`
- Format: `pnpm run lint:fix`
- **SolarXR Protocol (Submodule)**: Use `bash` and `pnpm`.
- Edit: Only `schema/` files.
- Generate: `./generate-flatbuffer.sh` (Linux/macOS).
- Sync: Run `pnpm i` in root after generation.
## Architecture: The Reducer/Behaviour Pattern
The server uses a reactive reducer pattern for thread safety and observability.
- **Core Primitives**:
- `Context<S, A>`: Holds `StateFlow<S>`, `CoroutineScope`, and `Behaviour`s.
- `Behaviour<S, A, C>`:
- `reduce(state, action)`: **Pure function**. No side effects.
- `observe(receiver)`: **Side effects**. Launch coroutines using `receiver.context.scope`.
- **Lifecycle**: `Module.create()` (inert construction) $\rightarrow$ `module.startObserving()` (side-effect activation).
- **DI**: Uses `Phase1ContextProvider` $\rightarrow$ `AppContextProvider` hierarchy.
- **Communication**: Modules communicate via `dispatch(action)` or by observing another module's `StateFlow`.
## Design & Coding Preferences
- **Function over Class**: Prefer plain functions or `object` over classes for single-purpose logic.
- **Function over Extension**: Use plain functions instead of extension functions unless the receiver is the primary subject.
- **Action Selection**:
- Use `Update` (with a lambda) for internal state changes that require no external reaction.
- Use **Named Actions** when multiple behaviours must react to a specific event.
- **State Management**: Only include data in `StateFlow` if it is required for observation by other modules.
- **Communication**: Decouple modules by using `dispatch` or observing `StateFlow` rather than direct method calls.
## Agent Workflow
- **Phase 1: Discovery**: Use the `Glob` $\rightarrow$ `Grep` $\rightarrow$ `Read` pattern. Never guess file paths or contents.
- **Phase 2: Planning**: For complex tasks, use `todowrite` to create a checklist. Present the plan to the user before implementation.
- **Phase 3: Implementation**: Use `edit` for existing files; `write` for new files.
- **Phase 4: Verification**: Always run the relevant linting or testing tools before marking a task as complete.
## Common Pitfalls
- **Coroutine Leaks**: Never launch coroutines in `observe` using a global scope; **always** use `receiver.context.scope`.
- **Direct State Mutation**: Never attempt to mutate state properties directly. Always use `dispatch(action)`.
- **Incomplete Cleanup**: Ensure any module owning a `Context` implements a `dispose()` method.
## Conventions
- **Files**: `module.kt` (Class/State/Actions) and `behaviours.kt` (Implementations).
- **Actions**: Use `sealed interface`.
- **State**: Data classes must use `val` only.
- **Cleanup**: We use a direct `dispose()` method on modules instead of a `Disposable` interface.
- **Detailed Conventions**: See `server/README.md` for full coding style and architecture details.
## Testing
- **Reducers**: Test by creating a `Context` with specific `Behaviour`s.
- **Modules**: Use `TestAppContext` and `buildTest...` helpers from `TestServer.kt`.
## Verification Protocol
- **Linting**: Run `./gradlew spotlessApply` (Server) or `pnpm run lint:fix` (GUI).
- **Testing**: Identify and run the relevant test suite (e.g., `./gradlew test` or specific module tests).
- **Final Audit**: Perform a final `git diff` check to ensure no unintended changes were made.
+10 -18
View File
@@ -7,6 +7,8 @@ This document describes essential knowledge required to contribute to the SlimeV
- [Git](https://git-scm.com/downloads)
- [Java v17+](https://adoptium.net/temurin/releases/)
- [Node.js v16.9+](https://nodejs.org) (We recommend the use of `nvm` instead of installing Node.js directly)
- [Microsoft Edge WebView2](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section) or `webkit2gtk` for Linux
- [Rust](https://rustup.rs)
## Cloning the code
First, clone the codebase using git in a terminal in the folder you want.
@@ -22,25 +24,21 @@ Now you can open the codebase in [IDEA](https://www.jetbrains.com/idea/download/
### Java (server)
Before contributing to the server, read [server/README.md](server/README.md) for an overview of its architecture and design guidelines.
The Java code is built with `gradle`, a CLI tool that manages java projects and their
dependencies.
- You can run the server by running `./gradlew :server:desktop:run` in your IDE's terminal.
- You can run the server by running `./gradlew run` in your IDE's terminal.
- To compile the code, run `./gradlew shadowJar`. The result will
be at `server/desktop/build/libs/slimevr.jar` (you can ignore `server.jar`).
be at `server/build/libs/slimevr.jar` (you can ignore `server.jar`).
(Note: Your IDE may be able to do all of the above for you.)
### Electron (gui)
### Tauri (gui)
- Activate corepack (included with Node.js) via `corepack enable`
(might require launching Git Bash as administrator on Windows)
- Make sure you're at the root of the repository.
- Activate corepack (included with Node.JS) via `corepack enable` (might require administrator permissions)
- Run `pnpm i` in your IDE's terminal to download and install dependencies.
- To launch the GUI in dev mode, run `pnpm gui`.
- Finally, to compile for production, run `pnpm package:build` under `gui/electron`.
The result will be in `gui/dist/artifacts/`. Content will change depending on the platform.
- Finally, to compile for production, run `pnpm run tauri build`. The result
will be at `target/release/slimevr.exe`.
## Code style
@@ -86,10 +84,10 @@ Import the formatting settings defined in `spotless.xml`, like this:
Eclipse will only do a subset of the checks in `spotless`, so you may still want to do
`./gradlew spotlessApply` if you ever see an error from spotless.
### Electron (gui)
### Tauri (gui)
We use ESLint and Prettier to format GUI code.
- Make sure you're at the root of the repository.
- First, go into the GUI's directory with your terminal by running `cd gui`.
- To check code formatting, run `pnpm run lint`.
- To fix code formatting, run `pnpm run lint:fix` and `pnpm run format`
@@ -118,9 +116,3 @@ licensed under `GPL-v3`.
## Discord
We use discord *a lot* to coordinate and discuss development. Come join us at
https://discord.gg/SlimeVR!
## Use of AI
We DO NOT accept contributions that are generated with AI (for example, "vibe-coding").
If you do use AI, and you believe your usage of AI is reasonable, you must clearly disclose
how you used AI in your submission.
Generated
+6898
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -0,0 +1,16 @@
[workspace]
# Use 2021 edition resolver, better resolves crate features.
resolver = "2"
# A list of all rust crates in the workspace.
members = ["gui/src-tauri"]
# These settings can be inherited by workspace members
[workspace.package]
edition = "2021"
license = "MIT OR Apache-2.0"
rust-version = "1.82" # Tauri's MSRV
repository = "https://github.com/SlimeVR/SlimeVR-Server"
[profile.release]
lto = "thin"
-2
View File
@@ -22,8 +22,6 @@ Latest setup instructions are [in our docs](https://docs.slimevr.dev/server/inde
## Building & Contributing
For information on building and contributing to the codebase, see [CONTRIBUTING.md](CONTRIBUTING.md).
For an overview of the server architecture and design guidelines, see [server/README.md](server/README.md).
## Translating
Translation is done via Pontoon at [i18n.slimevr.dev](https://i18n.slimevr.dev/). Please join our [Discord translation forum](https://discord.com/channels/817184208525983775/1050413434249949235) to coordinate.
-297
View File
@@ -1,297 +0,0 @@
---
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: true
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseArrows: false
AlignCaseColons: false
AlignConsecutiveTableGenBreakingDAGArgColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenCondOperatorColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenDefinitionColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignEscapedNewlines: Right
AlignOperands: DontAlign
AlignTrailingComments:
Kind: Never
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowBreakBeforeNoexceptSpecifier: Never
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseExpressionOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AllowShortNamespacesOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AttributeMacros:
- __capability
BinPackArguments: true
BinPackLongBracedList: true
BinPackParameters: BinPack
BitFieldColonSpacing: Both
BracedInitializerIndentWidth: -1
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterExternBlock: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAdjacentStringLiterals: true
BreakAfterAttributes: Leave
BreakAfterJavaFieldAnnotations: false
BreakAfterReturnType: None
BreakArrays: true
BreakBeforeBinaryOperators: All
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTemplateCloser: false
BreakBeforeTernaryOperators: true
BreakBinaryOperations: Never
BreakConstructorInitializers: BeforeComma
BreakFunctionDefinitionParameters: false
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
BreakTemplateDeclarations: MultiLine
ColumnLimit: 0
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
EnumTrailingComma: Leave
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: false
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: false
IndentExportBlock: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertBraces: false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLines:
AtEndOfFile: false
AtStartOfBlock: true
AtStartOfFile: true
KeepFormFeed: false
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ''
MacroBlockEnd: ''
MainIncludeChar: Quote
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 4
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
OneLineFormatOffRegex: ''
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakBeforeMemberAccess: 150
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakScopeResolution: 500
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
PPIndentWidth: -1
QualifierAlignment: Leave
ReferenceAlignment: Pointer
ReflowComments: Always
RemoveBracesLLVM: false
RemoveEmptyLinesInUnwrappedLines: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes:
Enabled: true
IgnoreCase: false
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterOperatorKeyword: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterNot: false
AfterOverloadedOperator: false
AfterPlacementOperator: true
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: true
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
ExceptDoubleParentheses: false
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TableGenBreakInsideDAGArg: DontBreak
TabWidth: 8
UseTab: Never
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
WrapNamespaceBodyWithEmptyLines: Leave
...
-12
View File
@@ -1,12 +0,0 @@
# Garbage left behind on Windows
.vs/
out/
CMakeFiles/
vcpkg_installed/
src/resources/resources.hpp
CMakeCache.txt
build.ninja
*.cmake
*.dll
*.log
-78
View File
@@ -1,78 +0,0 @@
cmake_minimum_required(VERSION 3.26)
project(SlimeVR-Bindings-Provider)
set(SOLARXR_PROTOCOL_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../solarxr-protocol")
set(FLATBUFFERS_GENERATED_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../solarxr-protocol/protocol/cpp")
# These are used to determine the OpenVR library path
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(PROCESSOR_ARCH "64")
else()
set(PROCESSOR_ARCH "32")
endif()
if(WIN32)
set(OPENVR_LIBRARY_NAME "openvr_api")
set(OPENVR_LIBRARY_EXT "dll")
set(PLATFORM_NAME "win")
elseif(APPLE)
set(OPENVR_LIBRARY_NAME "libopenvr_api")
set(OPENVR_LIBRARY_EXT "dylib")
set(PLATFORM_NAME "osx")
elseif(LINUX)
set(OPENVR_LIBRARY_NAME "libopenvr_api")
set(OPENVR_LIBRARY_EXT "so")
if (CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
set(PLATFORM_NAME "linuxarm")
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
set(PLATFORM_NAME "linux")
else()
message(FATAL_ERROR "Unknown/unsupported CPU architecture")
endif()
else()
message(FATAL_ERROR "Unknown/unsupported platform")
endif()
set(OPENVR_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/openvr")
message(STATUS "OpenVR library search path: ${OPENVR_ROOT}/lib/${PLATFORM_NAME}${PROCESSOR_ARCH}")
find_library(OPENVR_LIBRARY NAMES openvr_api REQUIRED PATHS "${OPENVR_ROOT}/lib/${PLATFORM_NAME}${PROCESSOR_ARCH}/" NO_DEFAULT_PATH)
message(STATUS "Found OpenVR library at: ${OPENVR_LIBRARY}")
add_executable("${PROJECT_NAME}"
"${CMAKE_CURRENT_SOURCE_DIR}/src/paths.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/logger.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/solarxr.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/vr_utils.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp"
)
set_target_properties("${PROJECT_NAME}" PROPERTIES CXX_STANDARD 23)
target_include_directories("${PROJECT_NAME}" PRIVATE "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/include" "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/" "${FLATBUFFERS_GENERATED_ROOT}/include" "${CMAKE_CURRENT_SOURCE_DIR}/include" "${OPENVR_ROOT}/headers")
target_link_libraries("${PROJECT_NAME}" PRIVATE "${OPENVR_LIBRARY}")
if(LINUX)
set_target_properties("${PROJECT_NAME}" PROPERTIES OUTPUT_NAME slimevr-bindings-provider)
endif()
set(OPENVR_RUNTIME_LIBRARY "${OPENVR_ROOT}/bin/${PLATFORM_NAME}${PROCESSOR_ARCH}/${OPENVR_LIBRARY_NAME}.${OPENVR_LIBRARY_EXT}")
message(STATUS "Found OpenVR runtime library: ${OPENVR_RUNTIME_LIBRARY}")
configure_file("${OPENVR_RUNTIME_LIBRARY}" "${CMAKE_CURRENT_BINARY_DIR}/." COPYONLY)
# Embed the resources into resources.hpp
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
src/resources/manifest.vrmanifest
src/resources/action_manifest.json
src/resources/generic.json
src/resources/knuckles.json
src/resources/oculus_touch.json
src/resources/vive_controller.json
)
file(STRINGS src/resources/manifest.vrmanifest SVR_VRAPP_MANIFEST NEWLINE_CONSUME)
file(STRINGS src/resources/action_manifest.json SVR_VRAPP_ACTION_MANIFEST NEWLINE_CONSUME)
file(STRINGS src/resources/generic.json SVR_VRAPP_GENERIC_BINDS NEWLINE_CONSUME)
file(STRINGS src/resources/knuckles.json SVR_VRAPP_KNUCKLES_BINDS NEWLINE_CONSUME)
file(STRINGS src/resources/oculus_touch.json SVR_VRAPP_OCULUS_BINDS NEWLINE_CONSUME)
file(STRINGS src/resources/vive_controller.json SVR_VRAPP_VIVE_BINDS NEWLINE_CONSUME)
configure_file(src/resources/resources.hpp.in src/resources/resources.hpp @ONLY)
target_include_directories("${PROJECT_NAME}" PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/src")
-21
View File
@@ -1,21 +0,0 @@
#include "logger.hpp"
#include "paths.hpp"
#ifdef _WIN32
#define WIN32_MEAN_AND_LEAN
#include <Windows.h>
#endif
Logger::Logger()
: log_stream(Paths::getLogPath() / "slimevr-bindings-provider.log",
std::ios::out | std::ios::app)
#ifdef _WIN32
, should_log_to_std_streams(GetConsoleWindow() != nullptr)
#endif
{
}
Logger &Logger::get() {
static Logger logger;
return logger;
}
-77
View File
@@ -1,77 +0,0 @@
#pragma once
#include <cassert>
#include <chrono>
#include <format>
#include <fstream>
#include <iomanip>
#include <iostream>
class Logger {
private:
std::ofstream log_stream;
#ifdef _WIN32
bool should_log_to_std_streams;
#endif
template <bool important, typename... Args>
void log(std::string_view suffix, std::format_string<Args...> fmt,
Args &&...args) {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
auto s = std::format(fmt, std::forward<Args>(args)...);
#ifdef _WIN32
if (should_log_to_std_streams) {
#endif
if constexpr (important)
std::cerr << suffix << ' ' << s << '\n';
else
std::cout << suffix << ' ' << s << '\n';
#ifdef _WIN32
}
#endif
log_stream << std::put_time(std::localtime(&time_t), "[%F %T]") //
<< ' ' << suffix << ' ' << s << '\n';
}
public:
Logger();
template <typename... Args>
void debug(std::format_string<Args...> fmt, Args &&...args) {
#ifndef NDEBUG
log<false>("[DEBUG]", fmt, std::forward<Args>(args)...);
#endif
}
template <typename... Args>
void info(std::format_string<Args...> fmt, Args &&...args) {
log<false>("[INFO]", fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void warning(std::format_string<Args...> fmt, Args &&...args) {
log<true>("[WARN]", fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void error(std::format_string<Args...> fmt, Args &&...args) {
log<true>("[ERROR]", fmt, std::forward<Args>(args)...);
}
void flush() {
#ifdef _WIN32
if (should_log_to_std_streams) {
#endif
std::cerr.flush();
std::cout.flush();
#ifdef _WIN32
}
#endif
log_stream.flush();
}
static Logger &get();
};
-315
View File
@@ -1,315 +0,0 @@
#include <cassert>
#include <csignal>
#include <map>
#include <optional>
#include <thread>
#include <tuple>
// These must be included before Windows.h because of some macro collisions.
#include "flatbuffers/flatbuffers.h"
#include "solarxr_protocol/generated/all_generated.h"
#include "logger.hpp"
#include "solarxr.hpp"
#include "vr_utils.hpp"
#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;
static void shutdown_vr(vr::IVRSystem *_sys) { vr::VR_Shutdown(); }
static void onYawReset(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::YAW, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onFullReset(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::FULL, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onMountingCalibration(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::MOUNTING, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onFeetMountingCalibration(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto bodyParts = fbb.CreateVector(
{ datatypes::BodyPart::LEFT_FOOT, datatypes::BodyPart::RIGHT_FOOT });
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::MOUNTING, bodyParts, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onToggleTracking(SolarXRConnection &conn) {
static bool shouldPause = false;
flatbuffers::FlatBufferBuilder fbb;
shouldPause = !shouldPause;
auto toggleReq = rpc::CreateSetPauseTrackingRequest(fbb, shouldPause);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::SetPauseTrackingRequest,
toggleReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
sig_atomic_t should_exit = 0;
static void signal_handler(int signal) {
Logger::get().info("Received signal {}", signal);
should_exit = 1;
}
int main() {
auto &logger = Logger::get();
// Steam and SteamVR sets these environment variables on applications that it
// spawns, but if an app spawned by Steam then spawns a child that initialises
// OpenVR, SteamVR will give the child the appkey of the root application it
// is a descendant of, e.g. if SteamVR launches SlimeVR as an overlay,
// it will set SteamAppId="3245490" and STEAMVR_APPKEY="steam.overlay.3245490"
// which breaks our bindings. We want SteamVR to use a generated appkey if
// possible.
#ifdef _WIN32
SetEnvironmentVariableA("SteamAppId", nullptr);
SetEnvironmentVariableA("STEAMVR_APPKEY", nullptr);
#else
unsetenv("SteamAppId");
unsetenv("STEAMVR_APPKEY");
#endif
try {
SolarXRConnection conn;
std::unique_ptr<vr::IVRSystem, decltype(&shutdown_vr)> sys{ nullptr,
shutdown_vr };
// On vrlink, VR_Init returns
// VRInitError_Driver_WirelessHmdNotConnected while the connection
// is initialising, so keep calling VR_Init until it ends up
// succeeding
vr::EVRInitError err{ vr::VRInitError_Driver_WirelessHmdNotConnected };
while (err == vr::VRInitError_Driver_WirelessHmdNotConnected) {
sys.reset(vr::VR_Init(&err, vr::VRApplication_Background));
if (err == vr::VRInitError_Driver_WirelessHmdNotConnected)
std::this_thread::sleep_for(500ms);
}
if (sys == nullptr or err != vr::VRInitError_None) {
logger.error("Failed to init OpenVR: {} ({})",
vr::VR_GetVRInitErrorAsSymbol(err),
vr::VR_GetVRInitErrorAsEnglishDescription(err));
return 1;
}
logger.info("Initialised OpenVR, HMD model '{}'",
VRUtils::getStringProp(vr::k_unTrackedDeviceIndex_Hmd,
vr::Prop_ModelNumber_String)
.value_or("<unknown>"));
vr::IVRApplications *app = vr::VRApplications();
vr::IVRInput *input = vr::VRInput();
fs::path actionManifestPath;
std::tie(std::ignore, 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
{
vr::EVRInputError err{};
constexpr int max_tries = 5;
int tries = 0;
while ((err = input->SetActionManifestPath(
actionManifestPath.string().data()))
== vr::VRInputError_IPCError
&& tries++ < max_tries) {
logger.debug("IPC error loading action manifest, retrying ({}/{})",
tries, max_tries);
std::this_thread::sleep_for(20ms);
}
if (err != vr::VRInputError_None) {
logger.error("Failed to set action manifest path: {}",
std::to_underlying(err));
return 1;
}
}
vr::VRActionSetHandle_t action_set;
if (auto err = input->GetActionSetHandle("/actions/main", &action_set);
err != vr::VRInputError_None) {
logger.error("Failed to get main action set handle: {}",
std::to_underlying(err));
return 1;
}
std::map<std::string, std::tuple<vr::VRActionHandle_t, std::function<void(SolarXRConnection &)>>>
actions{
{ "/actions/main/in/YawReset",
std::make_tuple(vr::k_ulInvalidActionHandle, onYawReset) },
{ "/actions/main/in/FullReset",
std::make_tuple(vr::k_ulInvalidActionHandle, onFullReset) },
{ "/actions/main/in/MountingCalibration",
std::make_tuple(vr::k_ulInvalidActionHandle,
onMountingCalibration) },
{ "/actions/main/in/FeetMountingCalibration",
std::make_tuple(vr::k_ulInvalidActionHandle,
onFeetMountingCalibration) },
{ "/actions/main/in/ToggleTracking",
std::make_tuple(vr::k_ulInvalidActionHandle, onToggleTracking) },
};
for (auto &[name, tuple] : actions) {
auto &[handle, _] = tuple;
if (auto err = input->GetActionHandle(name.c_str(), &handle);
err != vr::VRInputError_None || handle == vr::k_ulInvalidActionHandle) {
logger.warning("Failed to get action handle for action {}: {}", name,
std::to_underlying(err));
}
}
constexpr auto interval = 1000ms / 30;
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
while (!should_exit) {
vr::VREvent_t event{};
while (sys->PollNextEvent(&event, sizeof(event))) {
switch (event.eventType) {
case vr::VREvent_Quit:
logger.info("OpenVR runtime requested quit");
should_exit = 1;
break;
case vr::VREvent_Input_BindingLoadFailed: {
auto &loadData = event.data.inputBinding;
logger.debug("Binding load failed (ulAppContainer={} "
"pathMessage={} pathUrl={} pathControllerType={})",
loadData.ulAppContainer, loadData.pathMessage,
loadData.pathUrl, loadData.pathControllerType);
break;
}
case vr::VREvent_Input_BindingLoadSuccessful: {
auto &loadData = event.data.inputBinding;
logger.debug("Binding load successful (ulAppContainer={} "
"pathMessage={} pathUrl={} pathControllerType={})",
loadData.ulAppContainer, loadData.pathMessage,
loadData.pathUrl, loadData.pathControllerType);
break;
}
case vr::VREvent_Input_ActionManifestReloaded:
logger.debug("Action manifest reloaded");
break;
case vr::VREvent_Input_ActionManifestLoadFailed: {
auto &manifestData = event.data.actionManifest;
logger.debug(
"Action manifest load failed (pathAppKey={} pathMessage={} "
"pathMessageParam={} pathManifestPath={})",
manifestData.pathAppKey, manifestData.pathMessage,
manifestData.pathMessageParam, manifestData.pathManifestPath);
break;
}
default:
break;
}
}
if (!conn.connected()) {
logger.warning("Connection to SlimeVR lost, exiting");
break;
}
vr::VRActiveActionSet_t set{
.ulActionSet = action_set,
.ulRestrictedToDevice = vr::k_ulInvalidInputValueHandle,
.ulSecondaryActionSet = vr::k_ulInvalidActionSetHandle,
.nPriority = 0,
};
if (auto err = input->UpdateActionState(&set, sizeof(set), 1);
err != vr::VRInputError_None) {
logger.warning("Error when updating action states: {}",
std::to_underlying(err));
}
for (auto &[name, tuple] : actions) {
auto &[handle, callback] = tuple;
vr::InputDigitalActionData_t action_data{};
if (auto err = input->GetDigitalActionData(
handle, &action_data, sizeof(action_data),
vr::k_ulInvalidInputValueHandle);
err != vr::VRInputError_None) {
logger.warning("Failed to get action state for {} ({}): {}", name,
handle, std::to_underlying(err));
continue;
}
if (action_data.bActive && action_data.bChanged && action_data.bState) {
logger.debug("Action {} triggered", name);
callback(conn);
}
}
logger.flush();
std::this_thread::sleep_for(interval);
}
logger.info("Main loop done");
} catch (std::exception &ex) {
logger.error("Exception in main: {}", ex.what());
logger.flush();
return 1;
}
logger.flush();
return 0;
}
-33
View File
@@ -1,33 +0,0 @@
#include "paths.hpp"
namespace fs = std::filesystem;
fs::path Paths::getDataPath() {
fs::path basePath{};
#if defined(__linux__)
if (const char *dataHomeOverride = getenv("XDG_DATA_HOME")) {
basePath = dataHomeOverride;
} else {
const char *homeDir = getenv("HOME");
if (homeDir == nullptr)
throw std::runtime_error("HOME is unset");
basePath = fs::path(homeDir) / ".local" / "share";
}
#elif defined(_WIN32)
{
const char *appData = getenv("APPDATA");
if (appData == nullptr)
throw std::runtime_error("APPDATA is unset");
basePath = appData;
}
#else
#error "Unsupported platform"
#endif
return basePath / "dev.slimevr.SlimeVR";
}
fs::path Paths::getLogPath() { return Paths::getDataPath() / "logs"; }
-11
View File
@@ -1,11 +0,0 @@
#pragma once
#include <filesystem>
namespace Paths {
// Throws when path cannot be found
std::filesystem::path getDataPath() noexcept(false);
// Throws when path cannot be found
std::filesystem::path getLogPath() noexcept(false);
} // namespace Paths
@@ -1,64 +0,0 @@
{
"default_bindings": [
{
"controller_type": "generic",
"binding_url": "generic.json"
},
{
"controller_type": "oculus_touch",
"binding_url": "oculus_touch.json"
},
{
"controller_type": "knuckles",
"binding_url": "knuckles.json"
},
{
"controller_type": "vive_controller",
"binding_url": "vive_controller.json"
}
],
"actions": [
{
"name": "/actions/main/in/YawReset",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/FullReset",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/MountingCalibration",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/FeetMountingCalibration",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/ToggleTracking",
"requirement": "optional",
"type": "boolean"
}
],
"action_sets": [
{
"name": "/actions/main",
"usage": "leftright"
}
],
"localization": [
{
"language_tag": "en_us",
"/actions/main": "Utility Bindings",
"/actions/main/in/YawReset": "Yaw Reset",
"/actions/main/in/FullReset": "Full Reset",
"/actions/main/in/MountingCalibration": "Mounting Calibration",
"/actions/main/in/FeetMountingCalibration": "Feet Mounting Calibration",
"/actions/main/in/ToggleTracking": "Toggle Tracking"
}
]
}
@@ -1,12 +0,0 @@
{
"name": "Default Bindings for Generic",
"controller_type": "generic",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
@@ -1,12 +0,0 @@
{
"name": "Default Bindings for Knuckles",
"controller_type": "knuckles",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
@@ -1,14 +0,0 @@
{
"source": "builtin",
"applications": [{
"app_key": "dev.slimevr.BindingsProvider",
"is_dashboard_overlay": false,
"action_manifest_path": "action_manifest.json",
"strings": {
"en_us": {
"name": "SlimeVR Bindings Provider",
"description": "SlimeVR Bindings Provider"
}
}
}]
}
@@ -1,12 +0,0 @@
{
"name": "Default Bindings for Oculus Touch",
"controller_type": "oculus_touch",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
@@ -1,8 +0,0 @@
#pragma once
#cmakedefine SVR_VRAPP_MANIFEST R"(@SVR_VRAPP_MANIFEST@)"
#cmakedefine SVR_VRAPP_ACTION_MANIFEST R"(@SVR_VRAPP_ACTION_MANIFEST@)"
#cmakedefine SVR_VRAPP_GENERIC_BINDS R"(@SVR_VRAPP_GENERIC_BINDS@)"
#cmakedefine SVR_VRAPP_KNUCKLES_BINDS R"(@SVR_VRAPP_KNUCKLES_BINDS@)"
#cmakedefine SVR_VRAPP_OCULUS_BINDS R"(@SVR_VRAPP_OCULUS_BINDS@)"
#cmakedefine SVR_VRAPP_VIVE_BINDS R"(@SVR_VRAPP_VIVE_BINDS@)"
@@ -1,12 +0,0 @@
{
"name": "Default Bindings for Vive Wands",
"controller_type": "vive_controller",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
-163
View File
@@ -1,163 +0,0 @@
#include "solarxr.hpp"
#include "logger.hpp"
#include <stdexcept>
#if defined(__linux__)
#include <sys/socket.h>
#include <sys/un.h>
#elif defined(_WIN32)
#include <Windows.h>
#else
#error "Unsupported platform"
#endif
namespace fs = std::filesystem;
fs::path SolarXRConnection::getSocketPath() {
using namespace std::string_view_literals;
#if defined(__linux__)
#define MAKE_SOCKET_PATH(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, const char *>, 4> socketPaths{
MAKE_SOCKET_PATH("SLIMEVR_SOCKET_DIR"),
MAKE_SOCKET_PATH("XDG_RUNTIME_DIR"),
MAKE_SOCKET_PATH("TMPDIR"),
{ "/tmp", "/tmp" }
};
#undef MAKE_SOCKET_PATH
for (auto [name, path] : socketPaths) {
if (path == nullptr) {
Logger::get().info(
"Skipping socket directory {} because it doesn't exist", name);
continue;
}
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);
}
#elif defined(_WIN32)
throw std::logic_error(
"SolarXRConnection::getSocketPath should not be called on Windows");
#else
#error "Unsupported platform"
#endif
throw std::runtime_error("Failed to find socket directory");
}
SolarXRConnection::SolarXRConnection() {
#if defined(__linux__)
sockaddr_un addr{};
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, getSocketPath().string().data());
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
throw std::runtime_error(
std::format("Failed to create listen socket: {}", strerror(errno)));
}
if (connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
int e = errno;
close(fd);
throw std::runtime_error(std::format("Failed to connect to socket {}: {}",
addr.sun_path, strerror(e)));
}
#elif defined(_WIN32)
const char *pipeName = R"(\\.\pipe\SlimeVRRpc)";
if (!WaitNamedPipe(pipeName, 5000)) {
throw std::runtime_error("Timed out waiting for pipe");
}
pipe = CreateFile(pipeName, GENERIC_READ | GENERIC_WRITE, 0, nullptr,
OPEN_EXISTING, 0, nullptr);
if (pipe == INVALID_HANDLE_VALUE) {
throw std::runtime_error(
std::format("Unable to open pipe (error={})", GetLastError()));
}
#else
#error "Unsupported platform"
#endif
}
SolarXRConnection::~SolarXRConnection() {
#if defined(__linux__)
if (fd != -1)
close(fd);
#elif defined(_WIN32)
if (pipe != INVALID_HANDLE_VALUE)
CloseHandle(pipe);
#else
#error "Unsupported platform"
#endif
}
bool SolarXRConnection::connected() {
#if defined(__linux__)
if (read(fd, nullptr, 0) == -1) {
return !(errno == EBADF || errno == EINVAL);
}
return true;
#elif defined(_WIN32)
if (!WriteFile(pipe, nullptr, 0, nullptr, nullptr)) {
int err = GetLastError();
// The documentation says it should return ERROR_BROKEN_PIPE
// when the write-end has been closed, but it seems to actually
// return ERROR_NO_DATA...
return !(err == ERROR_NO_DATA || err == ERROR_BROKEN_PIPE);
}
return true;
#else
#error "Unsupported platform"
#endif
}
void SolarXRConnection::sendMsg(flatbuffers::FlatBufferBuilder &fbb) {
// The server expects the total size of the buffer to be written at the
// start of the packet, including the first 4 bytes for the size
int size = fbb.GetSize() + 4;
// This may be wrong on mixed-endianness, but oh well...
if constexpr (std::endian::native != std::endian::little)
size = std::byteswap(size);
#if defined(__linux__)
if (write(fd, &size, sizeof(size)) == -1) {
Logger::get().warning("Failed to write message size to socket: {}",
strerror(errno));
return;
}
if (write(fd, fbb.GetBufferPointer(), fbb.GetSize()) == -1) {
Logger::get().warning("Failed to write message to socket: {}",
strerror(errno));
return;
}
#elif defined(_WIN32)
uint8_t tempBuf[2048];
if (fbb.GetSize() > 2048 - 4) {
Logger::get().warning("Message is too big for temporary buffer");
return;
}
*reinterpret_cast<int *>(&tempBuf[0]) = size;
memcpy(&tempBuf[4], fbb.GetBufferPointer(), fbb.GetSize());
if (!WriteFile(pipe, tempBuf, fbb.GetSize() + 4, nullptr, nullptr)) {
Logger::get().warning("Failed to write message to pipe (error={})",
GetLastError());
return;
}
#else
#error "Unsupported platform"
#endif
}
-31
View File
@@ -1,31 +0,0 @@
#pragma once
#include <filesystem>
#if defined(_WIN32)
#define WIN32_MEAN_AND_LEAN
#include <Windows.h>
#endif
#include "flatbuffers/flatbuffer_builder.h"
class SolarXRConnection {
private:
#if defined(__linux__)
int fd{ -1 };
#elif defined(_WIN32)
HANDLE pipe{ INVALID_HANDLE_VALUE };
#else
#error "Unsupported platform"
#endif
static std::filesystem::path getSocketPath();
public:
SolarXRConnection() noexcept(false);
~SolarXRConnection();
bool connected();
void sendMsg(flatbuffers::FlatBufferBuilder &fbb);
};
-72
View File
@@ -1,72 +0,0 @@
#include "vr_utils.hpp"
#include "logger.hpp"
#include "paths.hpp"
#include "resources/resources.hpp"
#include <array>
#include <fstream>
#include <string_view>
#include <utility>
namespace fs = std::filesystem;
std::optional<std::string>
VRUtils::getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
vr::ETrackedDeviceProperty prop) {
vr::IVRSystem *sys = vr::VRSystem();
vr::ETrackedPropertyError err{ vr::TrackedProp_Success };
uint32_t required_len = sys->GetStringTrackedDeviceProperty(deviceIndex, prop, nullptr, 0, &err);
if (err != vr::TrackedProp_BufferTooSmall) {
Logger::get().info(
"Failed to get size of string property {} for device {}: {}",
std::to_underlying(prop), deviceIndex,
sys->GetPropErrorNameFromEnum(err));
return std::nullopt;
}
std::string s(required_len - 1, '\0');
sys->GetStringTrackedDeviceProperty(deviceIndex, prop, s.data(), required_len,
&err);
if (err != vr::TrackedProp_Success) {
Logger::get().info("Failed to get string property {} for device {}: {}",
std::to_underlying(prop), deviceIndex,
sys->GetPropErrorNameFromEnum(err));
return std::nullopt;
}
return s;
}
std::tuple<fs::path, fs::path> VRUtils::initialiseManifest() {
fs::path manifestDir = Paths::getDataPath() / "bindings-provider";
std::error_code ec;
fs::create_directories(manifestDir, ec);
if (ec) {
throw std::runtime_error(
std::format("Failed to create manifest folder: {}", ec.message()));
}
using namespace std::string_view_literals;
// Make sure the vrmanifest and action manifest are 1st and 2nd respectively
// in the array
std::array requiredFiles{
std::make_pair("manifest.vrmanifest"sv, SVR_VRAPP_MANIFEST),
std::make_pair("action_manifest.json"sv, SVR_VRAPP_ACTION_MANIFEST),
std::make_pair("generic.json"sv, SVR_VRAPP_GENERIC_BINDS),
std::make_pair("knuckles.json"sv, SVR_VRAPP_KNUCKLES_BINDS),
std::make_pair("oculus_touch.json"sv, SVR_VRAPP_OCULUS_BINDS),
std::make_pair("vive_controller.json"sv, SVR_VRAPP_VIVE_BINDS),
};
for (auto &[name, contents] : requiredFiles) {
fs::path path = manifestDir / name;
if (!fs::exists(path)) {
std::ofstream stream(path);
stream << contents;
}
}
return { manifestDir / requiredFiles.at(0).first,
manifestDir / requiredFiles.at(1).first };
}
-16
View File
@@ -1,16 +0,0 @@
#pragma once
#include <filesystem>
#include <optional>
#include <string>
#include <tuple>
#include "openvr.h"
namespace VRUtils {
std::optional<std::string> getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
vr::ETrackedDeviceProperty prop);
// Returns <app vrmanifest path, action manifest json path>
std::tuple<std::filesystem::path, std::filesystem::path> initialiseManifest();
} // namespace VRUtils
+3
View File
@@ -0,0 +1,3 @@
plugins {
id("org.ajoberstar.grgit")
}
+242
View File
@@ -0,0 +1,242 @@
# This template contains all of the possible sections and their default values
# Note that all fields that take a lint level have these possible values:
# * deny - An error will be produced and the check will fail
# * warn - A warning will be produced, but the check will not fail
# * allow - No warning or error will be produced, though in some cases a note
# will be
# The values provided in this template are the default values that will be used
# when any section or field is not specified in your own configuration
# Root options
# The graph table configures how the dependency graph is constructed and thus
# which crates the checks are performed against
[graph]
# If 1 or more target triples (and optionally, target_features) are specified,
# only the specified targets will be checked when running `cargo deny check`.
# This means, if a particular package is only ever used as a target specific
# dependency, such as, for example, the `nix` crate only being used via the
# `target_family = "unix"` configuration, that only having windows targets in
# this list would mean the nix crate, as well as any of its exclusive
# dependencies not shared by any other crates, would be ignored, as the target
# list here is effectively saying which targets you are building for.
targets = [
# The triple can be any string, but only the target triples built in to
# rustc (as of 1.40) can be checked against actual config expressions
#"x86_64-unknown-linux-musl",
# You can also specify which target_features you promise are enabled for a
# particular target. target_features are currently not validated against
# the actual valid features supported by the target architecture.
#{ triple = "wasm32-unknown-unknown", features = ["atomics"] },
]
# When creating the dependency graph used as the source of truth when checks are
# executed, this field can be used to prune crates from the graph, removing them
# from the view of cargo-deny. This is an extremely heavy hammer, as if a crate
# is pruned from the graph, all of its dependencies will also be pruned unless
# they are connected to another crate in the graph that hasn't been pruned,
# so it should be used with care. The identifiers are [Package ID Specifications]
# (https://doc.rust-lang.org/cargo/reference/pkgid-spec.html)
#exclude = []
# If true, metadata will be collected with `--all-features`. Note that this can't
# be toggled off if true, if you want to conditionally enable `--all-features` it
# is recommended to pass `--all-features` on the cmd line instead
all-features = false
# If true, metadata will be collected with `--no-default-features`. The same
# caveat with `all-features` applies
no-default-features = false
# If set, these feature will be enabled when collecting metadata. If `--features`
# is specified on the cmd line they will take precedence over this option.
#features = []
# The output table provides options for how/if diagnostics are outputted
[output]
# When outputting inclusion graphs in diagnostics that include features, this
# option can be used to specify the depth at which feature edges will be added.
# This option is included since the graphs can be quite large and the addition
# of features from the crate(s) to all of the graph roots can be far too verbose.
# This option can be overridden via `--feature-depth` on the cmd line
feature-depth = 1
# This section is considered when running `cargo deny check advisories`
# More documentation for the advisories section can be found here:
# https://embarkstudios.github.io/cargo-deny/checks/advisories/cfg.html
[advisories]
# The path where the advisory databases are cloned/fetched into
#db-path = "$CARGO_HOME/advisory-dbs"
# The url(s) of the advisory databases to use
#db-urls = ["https://github.com/rustsec/advisory-db"]
# A list of advisory IDs to ignore. Note that ignored advisories will still
# output a note when they are encountered.
ignore = [
#"RUSTSEC-0000-0000",
#{ id = "RUSTSEC-0000-0000", reason = "you can specify a reason the advisory is ignored" },
#"[email protected]", # you can also ignore yanked crate versions if you wish
#{ crate = "[email protected]", reason = "you can specify why you are ignoring the yanked crate" },
]
# If this is true, then cargo deny will use the git executable to fetch advisory database.
# If this is false, then it uses a built-in git library.
# Setting this to true can be helpful if you have special authentication requirements that cargo-deny does not support.
# See Git Authentication for more information about setting up git authentication.
#git-fetch-with-cli = true
# This section is considered when running `cargo deny check licenses`
# More documentation for the licenses section can be found here:
# https://embarkstudios.github.io/cargo-deny/checks/licenses/cfg.html
[licenses]
# List of explicitly allowed licenses
# See https://spdx.org/licenses/ for list of possible licenses
# [possible values: any SPDX 3.11 short identifier (+ optional exception)].
allow = [
"MIT",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"Unicode-3.0",
"Unicode-DFS-2016",
"MIT-0",
"ISC",
"BSD-3-Clause",
"Zlib",
"MPL-2.0",
]
# The confidence threshold for detecting a license from license text.
# The higher the value, the more closely the license text must be to the
# canonical license text of a valid SPDX license file.
# [possible values: any between 0.0 and 1.0].
confidence-threshold = 0.8
# Allow 1 or more licenses on a per-crate basis, so that particular licenses
# aren't accepted for every possible crate as with the normal allow list
exceptions = [
# Each entry is the crate and version constraint, and its specific allow
# list
#{ allow = ["Zlib"], crate = "adler32" },
]
# Some crates don't have (easily) machine readable licensing information,
# adding a clarification entry for it allows you to manually specify the
# licensing information
#[[licenses.clarify]]
# The package spec the clarification applies to
#crate = "ring"
# The SPDX expression for the license requirements of the crate
#expression = "MIT AND ISC AND OpenSSL"
# One or more files in the crate's source used as the "source of truth" for
# the license expression. If the contents match, the clarification will be used
# when running the license check, otherwise the clarification will be ignored
# and the crate will be checked normally, which may produce warnings or errors
# depending on the rest of your configuration
#license-files = [
# Each entry is a crate relative path, and the (opaque) hash of its contents
#{ path = "LICENSE", hash = 0xbd0eed23 }
#]
[licenses.private]
# If true, ignores workspace crates that aren't published, or are only
# published to private registries.
# To see how to mark a crate as unpublished (to the official registry),
# visit https://doc.rust-lang.org/cargo/reference/manifest.html#the-publish-field.
ignore = false
# One or more private registries that you might publish crates to, if a crate
# is only published to private registries, and ignore is true, the crate will
# not have its license(s) checked
registries = [
#"https://sekretz.com/registry
]
# This section is considered when running `cargo deny check bans`.
# More documentation about the 'bans' section can be found here:
# https://embarkstudios.github.io/cargo-deny/checks/bans/cfg.html
[bans]
# Lint level for when multiple versions of the same crate are detected
multiple-versions = "warn"
# Lint level for when a crate version requirement is `*`
wildcards = "allow"
# The graph highlighting used when creating dotgraphs for crates
# with multiple versions
# * lowest-version - The path to the lowest versioned duplicate is highlighted
# * simplest-path - The path to the version with the fewest edges is highlighted
# * all - Both lowest-version and simplest-path are used
highlight = "all"
# The default lint level for `default` features for crates that are members of
# the workspace that is being checked. This can be overridden by allowing/denying
# `default` on a crate-by-crate basis if desired.
workspace-default-features = "allow"
# The default lint level for `default` features for external crates that are not
# members of the workspace. This can be overridden by allowing/denying `default`
# on a crate-by-crate basis if desired.
external-default-features = "allow"
# List of crates that are allowed. Use with care!
allow = [
#"[email protected]",
#{ crate = "[email protected]", reason = "you can specify a reason it is allowed" },
]
# List of crates to deny
deny = [
#"[email protected]",
#{ crate = "[email protected]", reason = "you can specify a reason it is banned" },
# Wrapper crates can optionally be specified to allow the crate when it
# is a direct dependency of the otherwise banned crate
#{ crate = "[email protected]", wrappers = ["this-crate-directly-depends-on-ansi_term"] },
]
# List of features to allow/deny
# Each entry the name of a crate and a version range. If version is
# not specified, all versions will be matched.
#[[bans.features]]
#crate = "reqwest"
# Features to not allow
#deny = ["json"]
# Features to allow
#allow = [
# "rustls",
# "__rustls",
# "__tls",
# "hyper-rustls",
# "rustls",
# "rustls-pemfile",
# "rustls-tls-webpki-roots",
# "tokio-rustls",
# "webpki-roots",
#]
# If true, the allowed features must exactly match the enabled feature set. If
# this is set there is no point setting `deny`
#exact = true
# Certain crates/versions that will be skipped when doing duplicate detection.
skip = [
#"[email protected]",
#{ crate = "[email protected]", reason = "you can specify a reason why it can't be updated/removed" },
]
# Similarly to `skip` allows you to skip certain crates during duplicate
# detection. Unlike skip, it also includes the entire tree of transitive
# dependencies starting at the specified crate, up to a certain depth, which is
# by default infinite.
skip-tree = [
#"[email protected]", # will be skipped along with _all_ of its direct and transitive dependencies
#{ crate = "[email protected]", depth = 20 },
]
# This section is considered when running `cargo deny check sources`.
# More documentation about the 'sources' section can be found here:
# https://embarkstudios.github.io/cargo-deny/checks/sources/cfg.html
[sources]
# Lint level for what to happen when a crate from a crate registry that is not
# in the allow list is encountered
unknown-registry = "warn"
# Lint level for what to happen when a crate from a git repository that is not
# in the allow list is encountered
unknown-git = "warn"
# List of URLs for allowed crate registries. Defaults to the crates.io index
# if not specified. If it is specified but empty, no registries are allowed.
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
# List of URLs for allowed Git repositories
allow-git = []
[sources.allow-org]
# 1 or more github.com organizations to allow git sources for
github = [""]
# 1 or more gitlab.com organizations to allow git sources for
gitlab = [""]
# 1 or more bitbucket.org organizations to allow git sources for
bitbucket = [""]
Generated
+47 -25
View File
@@ -1,15 +1,36 @@
{
"nodes": {
"fenix": {
"inputs": {
"nixpkgs": [
"nixpkgs"
],
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1756795219,
"narHash": "sha256-tKBQtz1JLKWrCJUxVkHKR+YKmVpm0KZdJdPWmR2slQ8=",
"owner": "nix-community",
"repo": "fenix",
"rev": "80dbdab137f2809e3c823ed027e1665ce2502d74",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "fenix",
"type": "github"
}
},
"flake-parts": {
"inputs": {
"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": {
@@ -19,22 +40,6 @@
}
},
"nixpkgs": {
"locked": {
"lastModified": 1781577229,
"narHash": "sha256-lrp67w8AulE9Ks53n27I45ADSzbOCn4H+CNW1Ck8B+8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "567a49d1913ce81ac6e9582e3553dd90a955875f",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-jdk24": {
"locked": {
"lastModified": 1756787288,
"narHash": "sha256-rw/PHa1cqiePdBxhF66V7R+WAP8WekQ0mCDG4CFqT8Y=",
@@ -45,18 +50,18 @@
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"rev": "d0fc30899600b9b3466ddb260fd83deb486c32f1",
"type": "github"
}
},
"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": {
@@ -67,9 +72,26 @@
},
"root": {
"inputs": {
"fenix": "fenix",
"flake-parts": "flake-parts",
"nixpkgs": "nixpkgs",
"nixpkgs-jdk24": "nixpkgs-jdk24"
"nixpkgs": "nixpkgs"
}
},
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1756597274,
"narHash": "sha256-wfaKRKsEVQDB7pQtAt04vRgFphkVscGRpSx3wG1l50E=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "21614ed2d3279a9aa1f15c88d293e65a98991b30",
"type": "github"
},
"original": {
"owner": "rust-lang",
"ref": "nightly",
"repo": "rust-analyzer",
"type": "github"
}
}
},
+56 -202
View File
@@ -1,219 +1,73 @@
{
description = "SlimeVR Server & GUI";
description = "Affordable full-body tracking for VR!";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
# Pinned to a revision that still ships temurin jdk-24
nixpkgs-jdk24.url = "github:NixOS/nixpkgs/d0fc30899600b9b3466ddb260fd83deb486c32f1";
flake-parts.url = "github:hercules-ci/flake-parts";
fenix = {
url = "github:nix-community/fenix";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs =
inputs@{
self,
nixpkgs,
nixpkgs-jdk24,
flake-parts,
...
}:
outputs = inputs@{ self, nixpkgs, flake-parts, fenix, ... }:
flake-parts.lib.mkFlake { inherit inputs; } {
systems = [
"aarch64-linux"
"x86_64-linux"
];
systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ];
perSystem =
{
system,
lib,
pkgs,
...
}:
perSystem = { system, lib, ... }:
let
java = (import nixpkgs-jdk24 { inherit system; }).jdk24;
pkgs = import nixpkgs { inherit system; };
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
];
rust_toolchain = lib.importTOML ./rust-toolchain.toml;
fenixPkgs = fenix.packages.${system};
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";
rustToolchainSet = fenixPkgs.fromToolchainName {
name = rust_toolchain.toolchain.channel;
sha256 = "sha256-+9FmLhAOezBZCOziO0Qct1NOrfpjNsXxc/8I0c7BdKE=";
};
in {
# 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
devShells.default = pkgs.mkShell {
name = "slimevr";
buildInputs =
(with pkgs; [
cacert
]) ++ lib.optionals pkgs.stdenv.isLinux (with pkgs; [
atk cairo dbus dbus.lib dprint gdk-pixbuf glib.out glib-networking
gobject-introspection gtk3 harfbuzz libffi libsoup_3 openssl.dev pango
pkg-config treefmt webkitgtk_4_1 zlib
gst_all_1.gstreamer gst_all_1.gst-plugins-base
gst_all_1.gst-plugins-good gst_all_1.gst-plugins-bad
librsvg freetype expat libayatana-appindicator udev libusb1
]) ++ lib.optionals pkgs.stdenv.isDarwin [
pkgs.darwin.apple_sdk.frameworks.Security
] ++ [
pkgs.jdk17
pkgs.kotlin
rustToolchainSet.rustc
rustToolchainSet.cargo
rustToolchainSet.rustfmt
];
nativeBuildInputs = with pkgs; [ pnpm nodejs_22 gradle ];
RUST_BACKTRACE = 1;
GIO_EXTRA_MODULES = "${pkgs.glib-networking}/lib/gio/modules:${pkgs.dconf.lib}/lib/gio/modules";
shellHook = ''
export SLIMEVR_RUST_LD_LIBRARY_PATH="$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="${pkgs.udev}/lib:${pkgs.libayatana-appindicator}/lib:$LD_LIBRARY_PATH"
export GST_PLUGIN_SYSTEM_PATH_1_0="${pkgs.gst_all_1.gstreamer.out}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-base}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-good}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-bad}/lib/gstreamer-1.0"
# Force linker and pkg-config to use udev from nixpkgs so libgudev/hidapi
# resolve against the correct libudev implementation at link time.
export PKG_CONFIG_PATH="${pkgs.udev}/lib/pkgconfig:${pkgs.glib}/lib/pkgconfig:$PKG_CONFIG_PATH"
export LIBRARY_PATH="${pkgs.udev}/lib:$LIBRARY_PATH"
export LD_RUN_PATH="${pkgs.udev}/lib:$LD_RUN_PATH"
export NIX_LDFLAGS="-L${pkgs.udev}/lib -ludev $NIX_LDFLAGS"
export LDFLAGS="-L${pkgs.udev}/lib -Wl,-rpath,${pkgs.udev}/lib -ludev $LDFLAGS"
'';
installPhase = ''
mkdir $out
cp -r -t $out/ \
lib/ \
runtime-*
'';
};
appImageTools = pkgs.stdenvNoCC.mkDerivation {
name = "electron-builder-appimage-tools";
dontUnpack = true;
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
'';
};
# Toolchain shared by the dev shell and the packaging FHS env.
commonPackages = [
# for running the jar
java
# 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
];
buildEnv = {
JAVA_HOME = "${java}/lib/openjdk";
USE_SYSTEM_FPM = "true";
ELECTRON_BUILDER_7ZIP_PATH = "${pkgs.p7zip}/bin/7za";
APPIMAGE_TOOLS_PATH = "${appImageTools}";
# for electron-vite, so `pnpm gui` works
ELECTRON_EXEC_PATH = "${pkgs.electron}/bin/electron";
};
# electron-builder produces generic dynamically-linked binaries that
# NixOS can't run (no /lib64 loader). Building and running the packaged
# app inside an FHS sandbox provides that standard loader, so the final
# electron build works. `nix run .#package` runs `pnpm package:build`.
packageBuildScript = pkgs.writeShellScript "slimevr-package-build" ''
set -eu
cd "$(${pkgs.git}/bin/git rev-parse --show-toplevel)"
${lib.concatStringsSep "\n" (
lib.mapAttrsToList (name: value: "export ${name}=${lib.escapeShellArg value}") buildEnv
)}
export LD_LIBRARY_PATH="${lib.makeLibraryPath (runtimeLibs ++ [ pkgs.hidapi ])}:''${LD_LIBRARY_PATH:-}"
pnpm install
pnpm --filter @slimevr/gui-electron run package:build
'';
packageBuildFhs = pkgs.buildFHSEnv {
name = "slimevr-package-build";
targetPkgs = _: commonPackages ++ runtimeLibs;
runScript = "${packageBuildScript}";
};
in
{
devShells.default = pkgs.mkShell (
buildEnv
// {
packages = commonPackages;
buildInputs = runtimeLibs;
shellHook = ''
export LD_LIBRARY_PATH="${
lib.makeLibraryPath [
pkgs.systemd
pkgs.hidapi
]
}:$LD_LIBRARY_PATH"
'';
}
);
# Build the desktop package inside an FHS sandbox:
# nix run .#package
apps.package = {
type = "app";
program = "${packageBuildFhs}/bin/slimevr-package-build";
};
# Interactive FHS shell for manual packaging / running the built app:
# nix run .#package-shell
apps.package-shell = {
type = "app";
program = "${
pkgs.buildFHSEnv {
name = "slimevr-fhs";
targetPkgs = _: commonPackages ++ runtimeLibs;
runScript = "bash";
}
}/bin/slimevr-fhs";
};
};
};
+5 -5
View File
@@ -13,8 +13,8 @@ android.useAndroidX=true
android.nonTransitiveRClass=true
org.gradle.unsafe.configuration-cache=false
kotlinVersion=2.3.10
spotlessVersion=8.2.1
shadowJarVersion=9.3.1
buildconfigVersion=6.0.7
wireVersion=5.3.1
kotlinVersion=2.0.20
spotlessVersion=8.0.0
shadowJarVersion=8.3.2
buildconfigVersion=5.5.0
grgitVersion=5.2.2
Binary file not shown.
+2 -2
View File
@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=bbaeb2fef8710818cf0e261201dab964c572f92b942812df0c3620d62a529a01
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Vendored
+5 -4
View File
@@ -86,7 +86,8 @@ done
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -114,7 +115,7 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -205,7 +206,7 @@ fi
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
@@ -213,7 +214,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
Vendored
+2 -2
View File
@@ -70,11 +70,11 @@ goto fail
:execute
@rem Setup the command line
set CLASSPATH=
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
View File
File renamed without changes.
+7 -11
View File
@@ -1,16 +1,16 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# JS/TS dependencies
node_modules/
.pnp
/node_modules
/.pnp
.pnp.js
# testing
coverage/
/coverage
# Build artifacts
build/
target/
/build
/target
# misc
.DS_Store
@@ -26,16 +26,12 @@ yarn-error.log*
*.log
# vite
dist/
stats.html
/dist
/stats.html
vite.config.ts.timestamp*
electron.vite.config.*.mjs
# eslint
.eslintcache
# Sentry Config File
.env.sentry-build-plugin
# electron
out/
+2 -2
View File
@@ -1,5 +1,5 @@
export default {
'app/**/*.{js,jsx,ts,tsx}':
'pnpm --filter @slimevr/gui-app exec eslint --no-warn-ignored --cache --fix',
'**/*.{ts,tsx}': () => 'tsc -p tsconfig.json --noEmit',
'src/**/*.{js,jsx,ts,tsx}': 'eslint --max-warnings=0 --no-warn-ignored --cache --fix',
'**/*.{js,jsx,ts,tsx,css,scss,md,json}': 'prettier --write',
};
-520
View File
@@ -1,520 +0,0 @@
# Please developers (not translators) don't reuse a key inside another key
# or concat text with a translation string in the code, use the appropriate
# features like variables and selectors in each appropriate case!
# And also comment the string if it's something not easy to translate, so you help
# translators on what it means
## Websocket (server) status
websocket-connecting = Sunucuya bağlanılıyor...
websocket-connection_lost = Sunucuyla bağlantı kesildi. Tekrar bağlanılmaya çalışılıyor...
websocket-connection_lost-desc = SlimeVR sunucusu çöktü. Kayıtları kontrol edip programı yeniden başlat.
websocket-timedout = Sunucuya bağlanılamadı
websocket-timedout-desc = SlimeVR sunucusu çöktü veya zaman aşımına uğradı. Kayıtları kontrol et ve programı yeniden başlat.
websocket-error-close = SlimeVR'ı kapat
websocket-error-logs = Kayıtlar klasörünü aç
## Update notification
version_update-title = Yeni sürüm mevcut: { $version }
version_update-description = "{ version_update-update }" seçeneğine tıklamak SlimeVR kurulum uygulamasını indirir.
version_update-update = Güncelle
version_update-close = Kapat
## Tips
tips-find_tracker = Hangi takipçi hangisi emin değil misin? Takipçilerden birini hareket ettirerek belirleyebilirsin.
tips-do_not_move_heels = Kayıt sırasında ayaklarının hareket etmediğinden emin ol!
tips-file_select = Dosyaları sürükleyip bırak veya dosyalarından <u>seç</u>.
tips-tap_setup = Menüden seçmek yerine takipçine 2 kez yavaşça dokunarak da seçebilirsin.
tips-turn_on_tracker = Resmi SlimeVR takipçisi mi kullanıyorsun? Takipçilerini bilgisayara bağladıktan sonra onları <b><em>açmayı</em></b> unutma!
tips-failed_webgl = WebGL başlatılamadı.
## Units
unit-meter = Metre
unit-foot = Ayak
unit-inch = Inç
unit-cm = cm
## Body parts
body_part-NONE = Atanmamış
body_part-HEAD = Kafa
body_part-NECK = Boyun
body_part-RIGHT_SHOULDER = Sağ Omuz
body_part-RIGHT_UPPER_ARM = Sağ Üst Kol
body_part-RIGHT_LOWER_ARM = Sağ Alt Kol
body_part-RIGHT_HAND = Sağ El
body_part-RIGHT_UPPER_LEG = Sağ Uyluk
body_part-RIGHT_LOWER_LEG = Sağ Ayak Bileği
body_part-RIGHT_FOOT = Sağ Ayak
body_part-UPPER_CHEST = Üst Göğüs
body_part-CHEST = Göğüs
body_part-WAIST = Bel
body_part-HIP = Kalça
body_part-LEFT_SHOULDER = Sol Omuz
body_part-LEFT_UPPER_ARM = Sol Üst Kol
body_part-LEFT_LOWER_ARM = Sol Alt Kol
body_part-LEFT_HAND = Sol El
body_part-LEFT_UPPER_LEG = Sol Uyluk
body_part-LEFT_LOWER_LEG = Sol Ayak Bileği
body_part-LEFT_FOOT = Sol Ayak
body_part-LEFT_THUMB_METACARPAL = Sol başparmak metakarpal kemiği
body_part-LEFT_THUMB_PROXIMAL = Sol başparmak proksimal kemiği
body_part-LEFT_THUMB_DISTAL = Sol başparmak distal falanks kemiği
body_part-LEFT_INDEX_PROXIMAL = Sol işaret parmağının proksimal falanks kemiği
body_part-LEFT_INDEX_INTERMEDIATE = Sol işaret parmağının orta falanks kemiği
body_part-LEFT_INDEX_DISTAL = Sol işaret parmağının distal falanks kemiği
body_part-LEFT_MIDDLE_PROXIMAL = Sol orta parmağın proksimal falanks kemiği
body_part-LEFT_MIDDLE_INTERMEDIATE = Sol orta parmağın orta falanks kemiği
body_part-LEFT_MIDDLE_DISTAL = Sol orta parmağın distal falanks kemiği
body_part-LEFT_RING_PROXIMAL = Sol yüzük parmağının proksimal falanks kemiği
body_part-LEFT_RING_INTERMEDIATE = Sol yüzük parmağının orta falanks kemiği
body_part-LEFT_RING_DISTAL = Sol yüzük parmağının distal falanks kemiği
body_part-LEFT_LITTLE_PROXIMAL = Sol küçük parmağın proksimal falanks kemiği
body_part-LEFT_LITTLE_INTERMEDIATE = Sol küçük parmağın orta falanks kemiği
body_part-LEFT_LITTLE_DISTAL = Sol küçük parmağın distal falanks kemiği
body_part-RIGHT_THUMB_METACARPAL = Sağ başparmak metakarpal kemiği
body_part-RIGHT_THUMB_PROXIMAL = Sağ başparmağın proksimal falanks kemiği
body_part-RIGHT_THUMB_DISTAL = Sağ başparmağın distal falanks kemiği
body_part-RIGHT_INDEX_PROXIMAL = Sağ işaret parmağının proksimal falanks kemiği
body_part-RIGHT_INDEX_INTERMEDIATE = Sağ işaret parmağının orta falanks kemiği
body_part-RIGHT_INDEX_DISTAL = Sağ işaret parmağının distal falanks kemiği
body_part-RIGHT_MIDDLE_PROXIMAL = Sağ orta parmağın proksimal falanks kemiği
body_part-RIGHT_MIDDLE_INTERMEDIATE = Sağ orta parmağın orta falanks kemiği
body_part-RIGHT_MIDDLE_DISTAL = Sağ orta parmağın distal falanks kemiği
body_part-RIGHT_RING_PROXIMAL = Sağ yüzük parmağının proksimal falanks kemiği
body_part-RIGHT_RING_INTERMEDIATE = Sağ yüzük parmağının orta falanks kemiği
body_part-RIGHT_RING_DISTAL = Sağ yüzük parmağının distal falanks kemiği
body_part-RIGHT_LITTLE_PROXIMAL = Sağ küçük parmağın proksimal falanks kemiği
body_part-RIGHT_LITTLE_INTERMEDIATE = Sağ küçük parmağın orta falanks kemiği
body_part-RIGHT_LITTLE_DISTAL = Sağ küçük parmağın distal falanks kemiği
## BoardType
board_type-UNKNOWN = Bilinmeyen
board_type-NODEMCU = NodeMCU
board_type-WROOM32 = WROOM32
board_type-WEMOSD1MINI = Wemos D1 Mini
board_type-TTGO_TBASE = TTGO T-Base
board_type-ESP01 = ESP-01
board_type-SLIMEVR = SlimeVR
board_type-SLIMEVR_DEV = SlimeVR Dev Board
board_type-SLIMEVR_V1_2 = SlimeVR v1.2
board_type-LOLIN_C3_MINI = Lolin C3 Mini
board_type-BEETLE32C3 = Beetle ESP32-C3
board_type-ESP32C3DEVKITM1 = Espressif ESP32-C3 DevKitM-1
board_type-OWOTRACK = owoTrack
board_type-WRANGLER = Wrangler Joycons
board_type-MOCOPI = Sony Mocopi
board_type-WEMOSWROOM02 = Wemos Wroom-02 D1 Mini
board_type-XIAO_ESP32C3 = Seeed Studio XIAO ESP32C3
board_type-HARITORA = Haritora
board_type-ESP32C6DEVKITC1 = Espressif ESP32-C6 DevKitC-1
board_type-GLOVE_IMU_SLIMEVR_DEV = SlimeVR Dev IMU Eldiveni
board_type-GESTURES = Hareketler
board_type-ESP32S3_SUPERMINI = ESP32-S3 Supermini
board_type-GENERIC_NRF = Jenerik nRF
board_type-SLIMEVR_BUTTERFLY_DEV = SlimeVR Dev Butterfly
board_type-SLIMEVR_BUTTERFLY = SlimeVR Butterfly
## Proportions
skeleton_bone-NONE = Yok
skeleton_bone-HEAD = Kafa Hizası
skeleton_bone-HEAD-desc =
Bu, kulaklığın ile başının ortası arasındaki mesafedir.
Ayarlamak için, 'hayır' der gibi başını soldan sağa ve sağdan sola salla,
diğer takipçiler yerinden oynamayana kadar bunu tekrarlayıp ayarla.
skeleton_bone-NECK = Boyun Uzunluğu
skeleton_bone-NECK-desc =
Bu, başının ortasından boynunun başlangıcına kadar olan mesafedir.
Ayarlamak için başını 'evet' der gibi yukarı-aşağı hareket ettir veya başını hafifçe öne eğip, başını sola ve sağa kaydır,
diğer takipçiler yerinden oynamayana kadar bunu tekrarlayıp ayarla.
skeleton_bone-torso_group = Gövde Uzunluğu
skeleton_bone-torso_group-desc =
Bu, boynunun başlangıcından kalçalarına kadar olan mesafedir.
Ayarlamak için dik dur ve sanal kalçaların, gerçek kalçalarınla hizalanana kadar değeri değiştir.
skeleton_bone-UPPER_CHEST = Üst Göğüs Uzunluğu
skeleton_bone-UPPER_CHEST-desc =
Bu, boynunun başlangıcından göğsünün ortasına kadar olan mesafedir.
Gövde uzunluğunu doğru şekilde ayarlayıp (otururken, eğilirken, uzanırken vb. duruşlarda) sanal omurgan,
gerçek omurganla eşleşene kadar bu değeri değiştir.
skeleton_bone-CHEST_OFFSET = Göğüs Hizası
skeleton_bone-CHEST_OFFSET-desc =
Bu, bazı oyun veya uygulamalarda kalibrasyona yardımcı olmak için,
sanal göğüs takipçisini yukarı ya da aşağı hareket ettirmene izin verir.
skeleton_bone-CHEST = Göğüs Uzunluğu
skeleton_bone-CHEST-desc =
Bu, göğsünün ortasından omurganın ortasına kadar olan mesafedir.
Gövde uzunluğunu doğru şekilde ayarlayıp (otururken, eğilirken, uzanırken vb. duruşlarda) sanal omurgan,
gerçek omurganla eşleşene kadar bu değeri değiştir.
skeleton_bone-WAIST = Bel Uzunluğu
skeleton_bone-WAIST-desc =
Bu, omurganın ortasından göbek deliğine kadar olan mesafedir.
Gövde uzunluğunu doğru şekilde ayarlayıp (otururken, eğilirken, uzanırken vb. duruşlarda) sanal omurgan,
gerçek omurganla eşleşene kadar bu değeri değiştir.
skeleton_bone-HIP = Kalça Uzunluğu
skeleton_bone-HIP-desc =
Bu, göbek deliğinden kalçalarına kadar olan mesafedir.
Gövde uzunluğunu doğru şekilde ayarlayıp (otururken, eğilirken, uzanırken vb. duruşlarda) sanal omurgan,
gerçek omurganla eşleşene kadar bu değeri değiştir.
skeleton_bone-HIP_OFFSET = Kalça Hizası
skeleton_bone-HIP_OFFSET-desc =
Bu, bazı oyun veya uygulamalarda kalibrasyona yardımcı olmak için,
sanal kalça takipçisini yukarı ya da aşağı hareket ettirmene izin verir.
skeleton_bone-HIPS_WIDTH = Kalça Genişliği
skeleton_bone-HIPS_WIDTH-desc =
Bu, bacaklarının başladığı noktalar arasındaki mesafedir.
Ayarlamak için bacaklarını düz tutarak tam bir sıfırlama yap ve,
sanal bacaklarının aralığı, gerçek bacaklarının aralığıyla hizalanana kadar bu değeri değiştir.
skeleton_bone-leg_group = Bacak uzunluğu
skeleton_bone-leg_group-desc =
Bu, kalçandan ayaklarına olan mesafedir.
Ayarlamak için Gövde uzunluğunu doğru şekilde ayarla ve,
sanal ayakların gerçek ayaklarınla aynı seviyeye gelene kadar bu değeri değiştir.
skeleton_bone-UPPER_LEG = Üst Bacak Uzunluğu
skeleton_bone-UPPER_LEG-desc =
Bu, kalçandan dizlerine olan mesafedir.
Ayarlamak için Bacak uzunluğunu doğru şekilde ayarla ve,
sanal dizlerin gerçek dizlerinle aynı seviyeye gelene kadar bu değeri değiştir.
skeleton_bone-LOWER_LEG = Alt Bacak Uzunluğu
skeleton_bone-LOWER_LEG-desc =
Bu, dizlerinden ayak bileklerine olan mesafedir.
Ayarlamak için Bacak uzunluğunu doğru şekilde ayarla ve,
sanal dizlerin gerçek dizlerinle aynı seviyeye gelene kadar bu değeri değiştir.
skeleton_bone-FOOT_LENGTH = Ayak Uzunluğu
skeleton_bone-FOOT_LENGTH-desc =
Bu, ayak bileklerinden ayak parmaklarına olan mesafedir.
Ayarlamak için parmak uçlarına çık ve sanal ayakların sabit kalana kadar bu değeri değiştir.
skeleton_bone-FOOT_SHIFT = Ayak hizası
skeleton_bone-FOOT_SHIFT-desc =
Bu değer, dizinden ayak bileğine olan yatay mesafedir.
Bu, dik dururken alt bacaklarının geriye doğru konumlanmasını telafi eder.
Ayarlamak için Ayak uzunluğunu 0 olarak ayarla, tam sıfırlama yap ve,
sanal ayakların ayak bileklerinin ortasıyla hizalanana kadar bu değeri değiştir.
skeleton_bone-SKELETON_OFFSET = İskelet hizası
skeleton_bone-SHOULDERS_DISTANCE = Omuz Mesafesi
skeleton_bone-SHOULDERS_WIDTH = Omuz Genişliği
skeleton_bone-arm_group = Kol uzunluğu
skeleton_bone-UPPER_ARM = Üst Kol Uzunluğu
skeleton_bone-LOWER_ARM = Alt Kol Uzunluğu
skeleton_bone-ELBOW_OFFSET = Dirsek hizası
## Tracker reset buttons
reset-reset_all = Tüm oranları sıfırla
reset-reset_all_warning-cancel = İptal et
reset-full = Sıfırlama
reset-mounting-feet = Ayak Kalibrasyonu
reset-mounting-fingers = Parmak Kalibrasyonu
## Serial detection stuff
serial_detection-new_device-p0 = Yeni seri cihaz algılandı!
serial_detection-new_device-p1 = Wi-Fi bilgilerinizi girin!
serial_detection-new_device-p2 = Lütfen onunla ne yapmak istediğinizi seçin
serial_detection-open_wifi = Wi-Fi'ye bağlan
serial_detection-open_serial = Seri Konsolu Aç
serial_detection-submit = Gönder!
serial_detection-close = Kapat
## Navigation bar
navbar-home = Ana Menü
navbar-body_proportions = Vücut Oranları
navbar-onboarding = Kurulum Sihirbazı
navbar-settings = Ayarlar
## Biovision hierarchy recording
bvh-start_recording = BVH Kaydet
bvh-recording = Kaydediliyor
## Tracking pause
tracking-unpaused = Takibi duraklat
## Widget: Overlay settings
## Widget: Drift compensation
## Widget: Clear Mounting calibration
## Widget: Developer settings
widget-developer_mode = Geliştirici Modu
widget-developer_mode-high_contrast = Yüksek kontrast
widget-developer_mode-precise_rotation = Hassas dönüş
widget-developer_mode-sort_by_name = Ada göre sırala
widget-developer_mode-more_info = Daha fazla bilgi
## Widget: IMU Visualizer
widget-imu_visualizer = Rotasyon
widget-imu_visualizer-preview = Önizle
widget-imu_visualizer-hide = Gizle
widget-imu_visualizer-rotation_preview = Önizle
## Widget: Skeleton Visualizer
widget-skeleton_visualizer-hide = Gizle
## Tracker status
tracker-status-none = Durum Yok
tracker-status-busy = Meşgul
tracker-status-error = Hata
tracker-status-disconnected = Bağlantı kesildi
tracker-status-ok = İYİ
tracker-status-timed_out = Zaman aşımı
## Tracker status columns
tracker-table-column-name = İsim
tracker-table-column-type = Tür
tracker-table-column-battery = Pil
tracker-table-column-tps = TPS
tracker-table-column-temperature = Sıcaklık °C
tracker-table-column-rotation = Rotasyon X/Y/Z
tracker-table-column-position = Pozisyon X/Y/Z
tracker-table-column-url = URL
## Tracker rotation
tracker-rotation-front = Ön
tracker-rotation-left = Sol
tracker-rotation-right = Sağ
tracker-rotation-back = Arka
## Tracker information
tracker-infos-manufacturer = Üretici
tracker-infos-display_name = Görünen Ad
tracker-infos-custom_name = Özel Ad
tracker-infos-url = Takipçi URL'si
tracker-infos-version = Yazılım Sürümü
tracker-infos-hardware_rev = Donanım Revizyonu
tracker-infos-hardware_identifier = Donanım Kimliği
tracker-infos-imu = IMU Sensör
tracker-infos-board_type = Ana kart
## Tracker settings
tracker-settings-back = Takipçi listesine geri dön
tracker-settings-title = Takipçi ayarları
tracker-settings-assignment_section-description = Tracker'in vücudun hangi kısmına atandığı.
# 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 = Takipçi adı
tracker-settings-name_section-placeholder = NightyBeast'in sol bacağı
## Tracker part card info
tracker-part_card-no_name = İsimsiz
tracker-part_card-unassigned = Atanmamış
## Body assignment menu
body_assignment_menu = Bu takipçinin nerede olmasını istiyorsunuz?
body_assignment_menu-manage_trackers = Tüm takipçileri yönet
## Tracker assignment menu
# A -translation_key (with a dash in the front) means that it's a label.
# It can only be used in the translation file, it's nice for reusing names and that kind of stuff.
#
# We are using it here because english doesn't require changing the text in each case but
# maybe your language does.
-tracker_selection-part = hangi takipçiyi atayacaksınız?
tracker_selection_menu-HEAD = Başınıza { -tracker_selection-part }
tracker_selection_menu-RIGHT_SHOULDER = Sağ omuzunuza { -tracker_selection-part }
tracker_selection_menu-RIGHT_UPPER_ARM = Sağ üst kolunuza { -tracker_selection-part }
tracker_selection_menu-RIGHT_LOWER_ARM = Sağ alt kolunuza { -tracker_selection-part }
tracker_selection_menu-RIGHT_HAND = Sağ elinize { -tracker_selection-part }
tracker_selection_menu-RIGHT_UPPER_LEG = Say kalçanıza { -tracker_selection-part }
tracker_selection_menu-RIGHT_LOWER_LEG = Sağ ayak bileğinize { -tracker_selection-part }
tracker_selection_menu-RIGHT_FOOT = Sağ ayağınıza { -tracker_selection-part }
tracker_selection_menu-UPPER_CHEST = Üst göğüsünüze { -tracker_selection-part }
tracker_selection_menu-unassigned = Atanmamış takipçiler
tracker_selection_menu-assigned = Atanan takipçiler
tracker_selection_menu-neck_warning-done = Riskleri anlıyorum
tracker_selection_menu-neck_warning-cancel = İptal
## Mounting menu
mounting_selection_menu = Bu takipçinin nerede olmasını istiyorsunuz?
mounting_selection_menu-close = Kapat
## Sidebar settings
settings-sidebar-title = Ayarlar
settings-sidebar-general = Genel
settings-sidebar-interface = Arayüz
settings-sidebar-osc_router = OSC yönlendirici
settings-sidebar-osc_trackers = VRChat OSC Takipçileri
settings-sidebar-serial = Seri konsol
## SteamVR settings
settings-general-steamvr = SteamVR
settings-general-steamvr-subtitle = SteamVR takipçileri
settings-general-steamvr-trackers-waist = Bel
settings-general-steamvr-trackers-chest = Göğüs
## Tracker mechanics
settings-general-tracker_mechanics-filtering-amount = Miktar
## FK/Tracking settings
settings-general-fk_settings-leg_fk = Bacak takibi
settings-general-fk_settings-arm_fk = Kol takibi
settings-general-fk_settings-skeleton_settings-description = İskelet ayarlarını açın veya kapatın. Bunları açık bırakmanız önerilir.
## Gesture control settings (tracker tapping)
## Appearance settings
## Notification settings
## Behavior settings
## Serial settings
settings-serial-reboot = Yeniden Başlat
settings-serial-factory_reset-warning-ok = Ben ne yaptığımı biliyorum
settings-serial-factory_reset-warning-cancel = İptal et
settings-serial-auto_dropdown_item = Otomatik
## OSC router settings
settings-osc-router-enable = Etkinleştir
settings-osc-router-enable-label = Etkinleştir
settings-osc-router-network-address = Ağ adresi
## OSC VRChat settings
settings-osc-vrchat-enable = Etkinleştir
settings-osc-vrchat-enable-label = Etkinleştir
settings-osc-vrchat-network-address = Ağ adresi
## VMC OSC settings
## Common OSC settings
## Advanced settings
## Home Screen
## Tracking Checlist
## Setup/onboarding menu
## Quiz
## Wi-Fi setup
## Mounting setup
## Install info
## Setup start
## Setup done
## Tracker connection setup
## Tracker calibration tutorial
## Tracker assignment tutorial
## Tracker assignment setup
## Tracker assignment warnings
## Tracker mounting method choose
## Tracker manual mounting setup
## Tracker automatic mounting setup
## Tracker manual proportions setupa
## Tracker automatic proportions setup
## User height calibration
## Stay Aligned setup
## Home
## Trackers Still On notification
## Status system
## Firmware tool globals
## Firmware tool Steps
## firmware tool build status
## Firmware update status
## Dedicated Firmware Update Page
## Tray Menu
## First exit modal
## Unknown device modal
## Error collection consent modal
## Tracking checklist section
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

@@ -1,60 +0,0 @@
import { useState } from 'react';
import { BaseModal } from './BaseModal';
import { Button, ButtonProps } from './Button';
export type ButtonConfirmModal = Omit<ButtonProps, 'onClick' | 'to'> & {
onConfirm: () => void;
onCancel: (reason: 'cancel' | 'backdrop') => void;
confirmLabel: string;
cancelLabel: string;
};
export function ButtonConfirmModal(props: ButtonConfirmModal) {
const {
onConfirm,
onCancel,
cancelLabel,
confirmLabel,
children,
...buttonProps
} = props;
const [isOpen, setOpen] = useState(false);
return (
<>
<BaseModal
isOpen={isOpen}
onRequestClose={() => {
setOpen(false);
onCancel('backdrop');
}}
appendClasses="w-full max-w-2xl"
>
<div className="flex flex-col justify-between gap-4">
{children}
<div className="flex w-full justify-between gap-2 xs:flex-row flex-col">
<Button
id={cancelLabel}
variant="tertiary"
onClick={() => {
setOpen(false);
onCancel('cancel');
}}
/>
<Button
id={confirmLabel}
variant="primary"
onClick={() => {
setOpen(false);
onConfirm();
}}
/>
</div>
</div>
</BaseModal>
<Button {...buttonProps} onClick={() => setOpen(true)} />
</>
);
}
@@ -1,130 +0,0 @@
import { useState, forwardRef, useRef } from 'react';
import { Typography } from './Typography';
import classNames from 'classnames';
import { useFormContext } from 'react-hook-form';
const excludedKeys = [' ', 'SPACE'];
const maxKeybindLength = 4;
// KeyboardEvent.key spells some keys differently from the combinations the server stores.
// The super/windows key comes through as Meta, or as OS on older Firefox.
const keyAliases: Record<string, string> = {
CONTROL: 'CTRL',
META: 'SUPER',
OS: 'SUPER',
};
export const KeybindRecorder = forwardRef<
HTMLInputElement,
{
keys: string[];
onKeysChange: (v: string[]) => void;
error?: string;
}
>(function KeybindRecorder({ keys, onKeysChange, error }) {
const [localKeys, setLocalKeys] = useState<string[]>(keys);
const [isRecording, setIsRecording] = useState(false);
const [oldKeys, setOldKeys] = useState<string[]>([]);
const [invalidSlot, setInvalidSlot] = useState<number | null>(null);
const [errorText, setErrorText] = useState<string>('');
const inputRef = useRef<HTMLInputElement>(null);
const displayKeys = isRecording ? localKeys : keys;
const activeIndex = isRecording ? displayKeys.length : -1;
const displayError = errorText || error;
const { clearErrors } = useFormContext();
const handleKeyDown = (e: React.KeyboardEvent) => {
e.preventDefault();
const rawKey = e.key.toUpperCase();
const key = keyAliases[rawKey] ?? rawKey;
const errorMsg = excludedKeys.includes(key)
? `Cannot use ${key}!`
: displayKeys.includes(key)
? `${key} is a Duplicate Key!`
: null;
if (errorMsg) {
setErrorText(errorMsg);
setInvalidSlot(activeIndex);
setTimeout(() => {
setInvalidSlot(null);
}, 350);
return;
}
setErrorText('');
if (displayKeys.length < maxKeybindLength) {
const updatedKeys = [...displayKeys, key];
setLocalKeys(updatedKeys);
onKeysChange(updatedKeys);
if (updatedKeys.length == maxKeybindLength) {
inputRef.current?.blur();
}
}
};
const handleOnBlur = () => {
setIsRecording(false);
if (displayKeys.length < maxKeybindLength - 2 || error) {
onKeysChange(oldKeys);
setLocalKeys(oldKeys);
}
};
const handleOnFocus = () => {
clearErrors('keybinds');
const initialKeys: string[] = [];
setOldKeys(keys);
setLocalKeys(initialKeys);
onKeysChange(initialKeys);
setIsRecording(true);
};
return (
<div className="w-full justify-center items-center flex flex-col gap-2">
<div className="flex gap-2 p-2 items-center rounded-lg relative">
<input
autoFocus
ref={inputRef}
className="opacity-0 absolute cursor-pointer w-full"
onFocus={handleOnFocus}
onBlur={handleOnBlur}
onKeyDown={handleKeyDown}
/>
<div className="flex flex-grow gap-2 justify-center h-full">
{Array.from({ length: maxKeybindLength }).map((_, i) => {
const key = displayKeys[i];
const isActive = isRecording && i === activeIndex;
const isInvalid = invalidSlot === i;
return (
<div key={i} className="flex flex-row">
<div
className={classNames(
'flex p-2 rounded-lg min-w-[50px] min-h-[50px] text-main-title justify-center items-center bg-background-80 mobile:text-sm',
{
'keyslot-invalid ring-2 ring-status-critical': isInvalid,
'keyslot-animate ring-2 ring-accent':
isActive && !isInvalid,
'ring-accent': !isInvalid && !isInvalid,
}
)}
>
{key ?? ''}
</div>
<div className="flex pl-2 text-main-title justify-center items-center mobile:text-sm">
{i < maxKeybindLength - 1 ? '+' : ''}
</div>
</div>
);
})}
</div>
</div>
{displayError && (
<div className="isInvalid keyslot-invalid">
<Typography color="text-status-critical">{displayError}</Typography>
</div>
)}
</div>
);
});
@@ -1,93 +0,0 @@
import { BaseModal } from './BaseModal';
import {
Controller,
Control,
useFormContext,
FieldValues,
FieldPath,
} from 'react-hook-form';
import { KeybindRecorder } from './KeybindRecorder';
import { Typography } from './Typography';
import { Button } from './Button';
import './KeybindRow.scss';
import { useLocalization } from '@fluent/react';
export function KeybindRecorderModal<T extends FieldValues = FieldValues>({
id,
control,
name,
isVisisble,
onClose,
onUnbind,
onSubmit,
}: {
id?: string;
control: Control<T>;
name: FieldPath<T>;
isVisisble: boolean;
onClose: () => void;
onUnbind: () => void;
onSubmit: () => void;
}) {
const { l10n } = useLocalization();
const keybindlocalization = 'settings-keybinds_' + id;
const {
formState: { errors },
resetField,
handleSubmit,
} = useFormContext();
return (
<BaseModal
isOpen={isVisisble}
onRequestClose={onClose}
appendClasses="w-full max-w-xl"
>
<div className="flex flex-col gap-3 w-full justify-between h-full">
<Typography variant="section-title">
{l10n.getString('settings-keybinds-recorder-modal-title')}{' '}
{l10n.getString(keybindlocalization)}
</Typography>
<Controller
control={control}
name={name}
render={({ field }) => (
<KeybindRecorder
keys={field.value ?? []}
onKeysChange={field.onChange}
ref={field.ref}
error={errors.keybinds?.message as string}
/>
)}
/>
<div className="flex flex-row justify-between w-full">
<div className="flex flex-row justify-start gap-4">
<Button
id="settings-keybinds-recorder-modal-reset-button"
variant="tertiary"
onClick={() => {
resetField(name);
handleSubmit(onSubmit)();
}}
/>
<Button
id="settings-keybinds-recorder-modal-unbind-button"
variant="tertiary"
onClick={() => {
onUnbind();
handleSubmit(onSubmit)();
}}
/>
</div>
<div className="flex flex-row justify-end">
<Button
id="settings-keybinds-recorder-modal-done-button"
variant="primary"
onClick={handleSubmit(onSubmit)}
/>
</div>
</div>
</div>
</BaseModal>
);
}
@@ -1,65 +0,0 @@
.keybind-row {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
height: auto;
align-items: center;
gap: 10px;
}
@keyframes keyslot {
0%,
100% {
transform: scale(1);
opacity: 0.6;
}
50% {
transform: scale(1.08);
opacity: 1;
}
}
@keyframes shake {
0% {
transform: translate(1px, 1px) rotate(0deg);
}
10% {
transform: translate(-1px, -2px) rotate(-1deg);
}
20% {
transform: translate(-3px, 0px) rotate(1deg);
}
30% {
transform: translate(3px, 2px) rotate(0deg);
}
40% {
transform: translate(1px, -1px) rotate(1deg);
}
50% {
transform: translate(-1px, 2px) rotate(-1deg);
}
60% {
transform: translate(-3px, 1px) rotate(0deg);
}
70% {
transform: translate(3px, 1px) rotate(-1deg);
}
80% {
transform: translate(-1px, -1px) rotate(1deg);
}
90% {
transform: translate(1px, 2px) rotate(0deg);
}
100% {
transform: translate(1px, -2px) rotate(-1deg);
}
}
.keyslot-animate {
animation: keyslot 1s ease-in-out infinite;
}
.keyslot-invalid {
animation: shake 0.35s ease;
}
@@ -1,79 +0,0 @@
import { Typography } from './Typography';
import './KeybindRow.scss';
import { Control, FieldPath, FieldValues, useWatch } from 'react-hook-form';
import { NumberSelector } from './NumberSelector';
import { useLocaleConfig } from '@/i18n/config';
function KeyBindKeyList({ keybind }: { keybind: string[] }) {
if (keybind.length <= 1) {
return (
<div className="flex h-full text-section-title items-center justifiy-center">
Click to edit keybind
</div>
);
}
return keybind.map((key, i) => {
return (
<div key={i} className="flex flex-row">
<div className="flex flex-wrap p-2 rounded-lg min-w-[50px] text-standard-bold justify-center items-center bg-background-80 mobile:text-sm">
{key ?? ''}
</div>
<div className="flex justify-center items-center text-section-title mobile:text-sm gap-2 pl-3">
{i < keybind.length - 1 ? '+' : ''}
</div>
</div>
);
});
}
export function KeybindsRow<T extends FieldValues = FieldValues>({
id,
control,
index,
openKeybindRecorderModal,
}: {
id?: string;
control: Control<T>;
index: number;
openKeybindRecorderModal: (index: number) => void;
}) {
const binding = useWatch({
control,
name: `keybinds.${index}.binding` as FieldPath<T>,
}) as string[] | undefined;
const { currentLocales } = useLocaleConfig();
const secondsFormat = new Intl.NumberFormat(currentLocales, {
style: 'unit',
unit: 'second',
unitDisplay: 'narrow',
maximumFractionDigits: 2,
});
const handleOpenModal = () => {
openKeybindRecorderModal(index);
};
return (
<div className="keybind-row bg-background-60 rounded-xl h-full keybinds-small:flex keybinds-small:flex-col keybinds-small:justify-center keybinds-small:items-center p-2">
<label className="text-sm font-medium text-background-10 keybinds-small:flex keybinds-small:py-2 keybinds-small:justify-center keybinds-small:align-middle">
<Typography id={`settings-keybinds_${id}`} />
</label>
<div
className="flex gap-2 h-full items-center rounded-lg bg-background-70 hover:bg-background-50 w-full"
onClick={handleOpenModal}
>
<div className="flex flex-grow gap-2 justify-center p-2 h-[50px]">
{binding != null && <KeyBindKeyList keybind={binding} />}
</div>
</div>
<NumberSelector
control={control}
name={`keybinds.${index}.delay` as FieldPath<T>}
valueLabelFormat={(value) => secondsFormat.format(value)}
min={0}
max={10}
step={0.2}
/>
</div>
);
}
@@ -1,118 +0,0 @@
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
import { Button } from './Button';
import { Typography } from './Typography';
import { useCallback, useMemo } from 'react';
import { useLocaleConfig } from '@/i18n/config';
export function NumberSelector<T extends FieldValues = FieldValues>({
label,
valueLabelFormat,
control,
name,
min,
max,
step,
doubleStep,
disabled = false,
showButtonWithNumber = false,
}: {
label?: string;
valueLabelFormat?: (value: number) => string;
control: Control<T>;
name: FieldPath<T>;
min: number;
max: number;
step: number | ((value: number, add: boolean) => number);
doubleStep?: number;
disabled?: boolean;
showButtonWithNumber?: boolean;
}) {
const { currentLocales } = useLocaleConfig();
const stepFn =
typeof step === 'function'
? step
: (value: number, add: boolean) =>
+(add ? value + step : value - step).toFixed(2);
const doubleStepFn = useCallback(
(value: number, add: boolean) =>
doubleStep === undefined
? 0
: +(add ? value + doubleStep : value - doubleStep).toFixed(2),
[doubleStep]
);
const decimalFormat = useMemo(
() =>
new Intl.NumberFormat(currentLocales, {
style: 'decimal',
maximumFractionDigits: 2,
signDisplay: 'exceptZero',
}),
[currentLocales]
);
return (
<Controller
control={control}
name={name}
render={({ field: { onChange, value } }) => {
return (
<div className="flex flex-col gap-1 w-full">
{label?.length != 0 ? <Typography bold>{label}</Typography> : <></>}
<div className="flex gap-5 bg-background-60 p-2 rounded-lg">
<div className="flex gap-1">
{doubleStep !== undefined && (
<Button
variant="tertiary"
rounded
onClick={() => onChange(doubleStepFn(value, false))}
disabled={doubleStepFn(value, false) < min || disabled}
>
{showButtonWithNumber
? decimalFormat.format(-doubleStep)
: '--'}
</Button>
)}
<Button
variant="tertiary"
rounded
onClick={() => onChange(stepFn(value, false))}
disabled={stepFn(value, false) < min || disabled}
>
-
</Button>
</div>
<div className="flex flex-grow justify-center text-center items-center w-10 text-standard">
{valueLabelFormat ? valueLabelFormat(value) : value}
</div>
<div className="flex gap-1">
<Button
variant="tertiary"
rounded
onClick={() => onChange(stepFn(value, true))}
disabled={stepFn(value, true) > max || disabled}
>
+
</Button>
{doubleStep !== undefined && (
<Button
variant="tertiary"
rounded
onClick={() => onChange(doubleStepFn(value, true))}
disabled={doubleStepFn(value, true) > max || disabled}
>
{showButtonWithNumber
? decimalFormat.format(doubleStep)
: '++'}
</Button>
)}
</div>
</div>
</div>
);
}}
/>
);
}
@@ -1,13 +0,0 @@
export function HorizontalAlignIcon({ size = 22 }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={size}
viewBox="0 -960 960 960"
width={size}
fill="#e3e3e3"
>
<path d="M733.15-312.35 565.5-480l167.65-167.65L796.8-584l-57.73 58.5h160.06v91H739.07L796.8-376l-63.65 63.65ZM434.5-151.87v-656.26h91v656.26h-91ZM226.85-312.35 163.2-376l57.73-58.5H60.87v-91h160.06L163.2-584l63.65-63.65L394.5-480 226.85-312.35Z" />
</svg>
);
}
@@ -1,13 +0,0 @@
export function MartialArtsIcon({ size = 23 }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={size}
viewBox="0 -960 960 960"
width={size}
fill="#e3e3e3"
>
<path d="m404.07-69-20-364.54-128.68-73.96-12.56 46.02 82.19 142.68-75.22 43.82-101.87-174.54 48.96-174.87 227.13-130.33L314.98-864 376-925.02l189.98 188.74-143.76 82.76 49.43 41.04 328.48-268.48 52.31 61.26-341.2 345.68L491-69h-86.93Zm-212.2-609.09q-34.44 0-59.13-24.69-24.7-24.7-24.7-59.13 0-34.44 24.7-59.01 24.69-24.58 59.13-24.58 34.43 0 59.01 24.58 24.58 24.57 24.58 59.01 0 34.43-24.58 59.13-24.58 24.69-59.01 24.69Z" />
</svg>
);
}
@@ -1,13 +0,0 @@
export function OutputIcon({ size = 22 }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={size}
viewBox="0 -960 960 960"
width={size}
fill="#e3e3e3"
>
<path d="M202.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h554.5q37.78 0 64.39 26.61t26.61 64.39v76.41h-91v-76.41h-554.5v554.26h554.5v-76.41h91v76.41q0 37.78-26.61 64.39t-64.39 26.61h-554.5Zm481.2-164.06-63.66-63.66 93.92-94.91H353.78v-91h360.55l-93.92-94.91 63.66-63.66L888.13-480 684.07-275.93Z" />
</svg>
);
}
@@ -1,12 +0,0 @@
export function SittingIcon({ size = 24 }: { size?: number }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={size}
viewBox="0 -960 960 960"
width={size}
>
<path d="M600-160H320q-33 0-56.5-23.5T240-240v-440h80v440h280v80ZM460-720q-33 0-56.5-23.5T380-800q0-33 23.5-56.5T460-880q33 0 56.5 23.5T540-800q0 33-23.5 56.5T460-720ZM640-80v-200H440q-33 0-56.5-23.5T360-360v-220q0-42 29-71t71-29q42 0 71 29t29 71v180h80q33 0 56.5 23.5T720-320v240h-80Z" />
</svg>
);
}
@@ -1,113 +0,0 @@
import { useState, useEffect } from 'react';
import { Button } from '@/components/commons/Button';
import { BaseModal } from '@/components/commons/BaseModal';
import { CheckboxInternal } from '@/components/commons/Checkbox';
import { Typography } from '@/components/commons/Typography';
import { useElectron } from '@/hooks/electron';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { RpcMessage, InstalledInfoResponseT } from 'solarxr-protocol';
import { useConfig } from '@/hooks/config';
import { useLocalization } from '@fluent/react';
export function UdevRulesModal() {
const { config, setConfig } = useConfig();
const { useRPCPacket, sendRPCPacket } = useWebsocketAPI();
const electron = useElectron();
const [udevContent, setUdevContent] = useState('');
const [isUdevInstalledResponse, setIsUdevInstalledResponse] = useState(true);
const [showUdevWarning, setShowUdevWarning] = useState(false);
const [dontShowThisSession, setDontShowThisSession] = useState(false);
const [dontShowAgain, setDontShowAgain] = useState(false);
const { l10n } = useLocalization();
const handleUdevContent = async () => {
if (electron.isElectron) {
const dir = await electron.api.getInstallDir();
const rulesPath = `${dir}/69-slimevr-devices.rules`;
setUdevContent(
`cat ${rulesPath} | sudo sh -c 'tee /etc/udev/rules.d/69-slimevr-devices.rules >/dev/null && udevadm control --reload-rules && udevadm trigger'`
);
}
};
useEffect(() => {
handleUdevContent();
}, []);
useEffect(() => {
if (!config) throw 'Invalid state!';
if (electron.isElectron) {
const isLinux = electron.data().os.type === 'linux';
const udevMissing = !isUdevInstalledResponse;
const notHiddenGlobally = !config.dontShowUdevModal;
const notHiddenThisSession = !dontShowThisSession;
const shouldShow =
isLinux && udevMissing && notHiddenGlobally && notHiddenThisSession;
setShowUdevWarning(shouldShow);
}
}, [config, isUdevInstalledResponse, dontShowThisSession]);
useEffect(() => {
sendRPCPacket(
RpcMessage.InstalledInfoRequest,
new InstalledInfoResponseT()
);
}, []);
useRPCPacket(
RpcMessage.InstalledInfoResponse,
({ isUdevInstalled }: InstalledInfoResponseT) => {
setIsUdevInstalledResponse(isUdevInstalled);
}
);
const handleModalClose = () => {
if (!config) throw 'Invalid State!';
setConfig({ dontShowUdevModal: dontShowAgain });
setDontShowThisSession(true);
};
const copyToClipboard = () => {
navigator.clipboard.writeText(udevContent);
};
return (
<BaseModal isOpen={showUdevWarning} appendClasses={'w-full max-w-2xl'}>
<div className="flex w-full h-full flex-col gap-4">
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-2">
<Typography
variant="main-title"
id="install-info_udev-rules_modal_title"
/>
<Typography id="install-info_udev-rules_warning" />
</div>
<div className="relative w-full max-w-2xl">
<div className="absolute right-2 top-2">
<Button variant="secondary" onClick={copyToClipboard}>
Copy
</Button>
</div>
<div className="bg-background-80 rounded-lg overflow-auto p-2 w-full h-[300px]">
<pre className="text-wrap">{udevContent}</pre>
</div>
</div>
</div>
<div className="flex justify-between gap-2">
<CheckboxInternal
label={l10n.getString(
'install-info_udev-rules_modal-dont-show-again_checkbox'
)}
name="dismiss-udev-rules-checkbox"
onChange={(e) => setDontShowAgain(e.currentTarget.checked)}
/>
<Button
variant="primary"
onClick={handleModalClose}
id="install-info_udev-rules_modal_button"
/>
</div>
</div>
</BaseModal>
);
}
@@ -1,57 +0,0 @@
import { Localized } from '@fluent/react';
import { useOnboarding } from '@/hooks/onboarding';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { WarningBox } from '@/components/commons/TipBox';
import { MoreSetsConfirm } from './quiz/MoreSetsConfirm';
export function DongleSectionContent() {
const { state } = useOnboarding();
return (
<div className="flex flex-col gap-2">
<div className="flex gap-2 items-center">
<div className="bg-accent-background-30 rounded-full p-2 fill-background-10">
<USBIcon size={24} />
</div>
<Typography
variant="main-title"
id="onboarding-wifi_creds-dongle-title"
/>
</div>
<div className={classNames('flex flex-col gap-2 flex-grow p-2')}>
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-wifi_creds-dongle-description"
/>
<Localized id="onboarding-wifi_creds-dongle-wip">
<WarningBox whitespace>WARNING</WarningBox>
</Localized>
</div>
<div className="flex px-2 p-6">
{state.alonePage && (
<Button
variant="primary"
to={'/'}
id="onboarding-wifi_creds-dongle-continue"
/>
)}
{!state.alonePage && <MoreSetsConfirm />}
</div>
</div>
);
}
export function DonglePage() {
const { applyProgress } = useOnboarding();
applyProgress(0.5);
return (
<div className="flex flex-col w-full h-full xs:justify-center items-center">
<DongleSectionContent />
</div>
);
}
@@ -1,49 +0,0 @@
import { Localized } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import { useConfig } from '@/hooks/config';
export function ErrorCollectingConsentPage() {
const { setConfig } = useConfig();
const accept = () => {
setConfig({ errorTracking: true });
};
const cancel = () => {
setConfig({ errorTracking: false });
};
return (
<div className="flex items-center justify-center h-full flex-col gap-3 p-4">
<div className="max-w-2xl flex flex-col gap-4">
<div className="flex flex-col w-full gap-4">
<Typography variant="main-title" id="error_collection_modal-title" />
<Localized
id="error_collection_modal-description_v2"
elems={{
b: <b />,
h1: <span className="text-md font-bold" />,
}}
>
<Typography variant="standard" whitespace="whitespace-pre-line" />
</Localized>
</div>
<div className="flex flex-row gap-2 justify-between">
<Button
variant="tertiary"
to="/onboarding/wifi-creds"
onClick={cancel}
id="error_collection_modal-cancel"
/>
<Button
variant="primary"
to="/onboarding/wifi-creds"
onClick={accept}
id="error_collection_modal-confirm"
/>
</div>
</div>
</div>
);
}
@@ -1,168 +0,0 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import { HumanIcon } from '@/components/commons/icon/HumanIcon';
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { useState } from 'react';
import { SittingIcon } from '@/components/commons/icon/SittingIcon';
import { VRMFileUpload } from '@/components/settings/pages/VMCSettings';
import { QuizButton } from './SlimeSetQuestion';
import { useNavigate } from 'react-router-dom';
export function QuizMocapPosQuestion() {
const nav = useNavigate();
const {
applyProgress,
setMocapPos,
mocapPos,
playspace,
setPlayspace,
onboardingEnded,
} = useOnboarding();
const [headTracker, setHeadTracker] = useState(true);
applyProgress(0.9);
const canContinue = (!headTracker || mocapPos) && playspace;
const end = () => {
onboardingEnded();
nav('/');
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography
variant="main-title"
id="onboarding-quiz-mocap_preferences-title"
/>
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-quiz-mocap_preferences-desc"
/>
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-head_tracker-title"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={headTracker}
onClick={() => setHeadTracker(true)}
icon={<HeadsetIcon width={50} />}
name="onboarding-quiz-mocap_preferences-head_tracker-yes"
/>
<QuizButton
active={!headTracker}
onClick={() => {
setHeadTracker(false);
setMocapPos(undefined);
}}
icon={<HeadsetIcon width={50} disabled />}
name="onboarding-quiz-mocap_preferences-head_tracker-no"
/>
</div>
</div>
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-vrm_model-title"
/>
<Typography id="onboarding-quiz-mocap_preferences-vrm_model-desc" />
</div>
<VRMFileUpload />
</div>
</div>
{headTracker && (
<>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-playspace-title"
/>
<Typography id="onboarding-quiz-mocap_preferences-playspace-desc" />
</div>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={playspace === 'sitting'}
onClick={() => setPlayspace('sitting')}
icon={<SittingIcon size={50} />}
name="onboarding-quiz-mocap_preferences-playspace-sitting"
/>
<QuizButton
active={playspace === 'standing'}
onClick={() => setPlayspace('standing')}
icon={<HumanIcon width={50} />}
name="onboarding-quiz-mocap_preferences-playspace-standing"
/>
</div>
</div>
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-head_tracker_location-title"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={mocapPos === 'forehead'}
onClick={() => setMocapPos('forehead')}
icon={
<img
src="/images/quiz/quiz_mocap-pos_forehead.webp"
className="w-44"
/>
}
name="onboarding-quiz-mocap_preferences-head_tracker_location-forehead"
/>
<QuizButton
active={mocapPos === 'face'}
onClick={() => setMocapPos('face')}
icon={
<img
src="/images/quiz/quiz_mocap-pos_face.webp"
className="w-44"
/>
}
name="onboarding-quiz-mocap_preferences-head_tracker_location-face"
/>
</div>
</div>
</div>
</>
)}
<div className="flex justify-between pb-4">
<Button
variant="secondary"
id="onboarding-quiz_back"
to="/onboarding/quiz/usage"
/>
<Button
variant="primary"
id="onboarding-quiz_continue"
disabled={!canContinue}
onClick={end}
/>
</div>
</div>
</div>
);
}
@@ -1,30 +0,0 @@
import { ButtonConfirmModal } from '@/components/commons/ButtonConfirmModal';
import { Typography } from '@/components/commons/Typography';
import { useNavigate } from 'react-router-dom';
export function MoreSetsConfirm() {
const navigate = useNavigate();
return (
<ButtonConfirmModal
variant="primary"
className="ml-auto"
id="onboarding-connect_tracker-next"
cancelLabel="onboarding-quiz-more_sets_modal-cancel"
confirmLabel="onboarding-quiz-more_sets_modal-confirm"
onConfirm={() => navigate('/onboarding/trackers-assign')}
onCancel={(reason) => {
if (reason === 'cancel') navigate('/onboarding/quiz/slime-set');
}}
>
<Typography
variant="main-title"
id="onboarding-quiz-more_sets_modal-title"
/>
<Typography
variant="vr-accessible"
id="onboarding-quiz-more_sets_modal-desc"
/>
</ButtonConfirmModal>
);
}
@@ -1,56 +0,0 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { QuizButton } from './SlimeSetQuestion';
import { SteamIcon } from '@/components/commons/icon/SteamIcon';
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/commons/Button';
export function QuizRuntimeQuestion() {
const { applyProgress, setVrcOSC, vrcOsc, onboardingEnded } = useOnboarding();
const nav = useNavigate();
applyProgress(0.9);
const next = (type: typeof vrcOsc) => {
setVrcOSC(type);
onboardingEnded();
nav('/');
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography variant="main-title" id="onboarding-quiz-runtime-title" />
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={!vrcOsc}
onClick={() => next(false)}
icon={<SteamIcon size={50} />}
name="onboarding-quiz-runtime-answer-steamvr"
/>
<QuizButton
active={vrcOsc}
onClick={() => next(true)}
icon={<HeadsetIcon width={80} />}
name="onboarding-quiz-runtime-answer-standalone"
/>
</div>
</div>
</div>
<div className="flex">
<Button
to={'/onboarding/quiz/usage'}
variant="secondary"
id="onboarding-quiz_back"
/>
</div>
</div>
</div>
);
}
@@ -1,136 +0,0 @@
import { useOnboarding } from '@/hooks/onboarding';
import { ReactNode } from 'react';
import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { useNavigate } from 'react-router-dom';
export function QuizButton({
name,
active,
icon,
onClick,
}: {
active?: boolean;
name: string;
icon: ReactNode;
onClick: () => void;
}) {
return (
<div
onClick={onClick}
className={classNames(
'flex rounded-lg bg-background-60 hover:bg-background-50 cursor-pointer',
'p-4 outline outline-2 flex-col gap-4 items-center justify-between fill-background-20',
{
'outline-accent-background-30': active,
'outline-transparent': !active,
}
)}
>
{icon}
<Typography id={name} variant="section-title" />
</div>
);
}
export function QuizSlimeSetQuestion() {
const { applyProgress, setSlimeSet, slimeSet } = useOnboarding();
const nav = useNavigate();
applyProgress(0.2);
const next = (type: typeof slimeSet) => {
setSlimeSet(type);
switch (type) {
case 'butterfly':
case 'dongle-slime':
nav('/onboarding/dongle');
break;
case 'slime-v1':
case 'wifi-slime':
nav('/onboarding/wifi-creds');
break;
}
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography
variant="main-title"
id="onboarding-quiz-slimeset-title"
/>
<Typography id="onboarding-quiz-slimeset-description" />
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<Typography
variant="section-title"
id="onboarding-quiz-slimeset-official-sets"
/>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={slimeSet === 'slime-v1'}
onClick={() => next('slime-v1')}
icon={
<img
src="/images/trackers/v1_2_slime.webp"
className="w-60"
/>
}
name="onboarding-quiz-slimeset-answer-regular"
/>
<QuizButton
active={slimeSet === 'butterfly'}
onClick={() => next('butterfly')}
icon={
<img
src="/images/trackers/butterfly_slime.webp"
className="w-60"
/>
}
name="onboarding-quiz-slimeset-answer-butterfly"
/>
</div>
</div>
<div className="flex gap-2 flex-col">
<Typography
variant="section-title"
id="onboarding-quiz-slimeset-thirdparty-sets"
/>
<div className="grid grid-cols-2 gap-4">
<QuizButton
onClick={() => next('wifi-slime')}
icon={
<svg
xmlns="http://www.w3.org/2000/svg"
height="50"
viewBox="0 0 24 24"
width="50"
className="fill-background-20"
>
<path d="M0 0h24v24H0z" fill="none" />
<path d="M1 9l2 2c4.97-4.97 13.03-4.97 18 0l2-2C16.93 2.93 7.08 2.93 1 9zm8 8l3 3 3-3c-1.65-1.66-4.34-1.66-6 0zm-4-4l2 2c2.76-2.76 7.24-2.76 10 0l2-2C15.14 9.14 8.87 9.14 5 13z" />
</svg>
}
name="onboarding-quiz-slimeset-answer-wifi"
/>
<QuizButton
onClick={() => next('dongle-slime')}
icon={
<div className="fill-background-20">
<USBIcon size={50} />
</div>
}
name="onboarding-quiz-slimeset-answer-dongle"
/>
</div>
</div>
</div>
</div>
</div>
);
}
@@ -1,62 +0,0 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import { QuizButton } from './SlimeSetQuestion';
import { useNavigate } from 'react-router-dom';
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { HumanIcon } from '@/components/commons/icon/HumanIcon';
export function QuizUsageQuestion() {
const { applyProgress, setUsage, usage } = useOnboarding();
const nav = useNavigate();
applyProgress(0.8);
const next = (type: typeof usage) => {
setUsage(type);
if (type === 'vr-gaming') {
if (window.__ANDROID__) {
nav('/');
} else {
nav('/onboarding/quiz/runtime');
}
} else nav('/onboarding/quiz/mocap-pos');
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography variant="main-title" id="onboarding-quiz-usage-title" />
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-quiz-usage-description"
/>
</div>
<div className="flex flex-col gap-6">
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={usage === 'vr-gaming'}
icon={<HeadsetIcon width={50} />}
name="onboarding-quiz-usage-answer-VRC"
onClick={() => next('vr-gaming')}
/>
<QuizButton
active={usage === 'mocap'}
icon={<HumanIcon width={50} />}
name="onboarding-quiz-usage-answer-mocap_vtubing"
onClick={() => next('mocap')}
/>
</div>
</div>
<div className="flex">
<Button
to={'/onboarding/quiz/slime-set'}
variant="secondary"
id="onboarding-quiz_back"
/>
</div>
</div>
</div>
);
}
@@ -1,70 +0,0 @@
import {
SettingsPageLayout,
SettingsPagePaneLayout,
} from '@/components/settings/SettingsPageLayout';
import { OutputTrackersSettings } from './components/OutputSettings';
import { StayAlignedSettings } from './components/StayAlignedSettings';
import { ResetsSettings } from './components/ResetsSettings';
import { HIDSettings } from './components/HIDSettings';
import { TrackingSettings } from './components/TrackingSettings';
import { TapDetectionSettings } from './components/TapDetectionSettings';
import { WrenchIcon } from '@/components/commons/icon/WrenchIcon';
import { MagnetometerToggleSetting } from './components/MagnetometerToggleSetting';
import { Typography } from '@/components/commons/Typography';
import { useLocalization } from '@fluent/react';
import { FullResetIcon } from '@/components/commons/icon/ResetIcon';
export function GroupedResetsSettings() {
const { l10n } = useLocalization();
return (
<SettingsPagePaneLayout icon={<FullResetIcon width={20} />} id="resets">
<>
<div className="flex flex-col pb-3">
<Typography variant="main-title">
{l10n.getString('settings-general-fk_settings-resets_settings')}
</Typography>
</div>
<TapDetectionSettings />
<ResetsSettings />
</>
</SettingsPagePaneLayout>
);
}
export function GroupedTrackersSettings() {
const { l10n } = useLocalization();
return (
<SettingsPagePaneLayout icon={<WrenchIcon />} id="trackers">
<>
<div className="flex flex-col pb-3">
<Typography variant="main-title">
{l10n.getString('settings-general-trackers_settings')}
</Typography>
</div>
<HIDSettings />
<MagnetometerToggleSetting
settingType="general"
id="mechanics-magnetometer"
/>
</>
</SettingsPagePaneLayout>
);
}
export function GeneralSettings() {
return (
<SettingsPageLayout>
<div className="flex flex-col gap-2 w-full">
<OutputTrackersSettings />
<StayAlignedSettings />
<TrackingSettings />
<GroupedResetsSettings />
<GroupedTrackersSettings />
</div>
</SettingsPageLayout>
);
}
@@ -1,15 +0,0 @@
.keybind-settings {
display: grid;
grid-template:
'n v d ' auto
'k k k ' auto
'b . . ' auto
/ 1fr 1fr 90px;
grid-template-columns: subgrid;
grid-template-rows: subgrid;
align-items: left;
gap: 10px;
}
@@ -1,265 +0,0 @@
import { KeybindRecorderModal } from '@/components/commons/KeybindRecorderModal';
import {
SettingsPageLayout,
SettingsPagePaneLayout,
} from '@/components/settings/SettingsPageLayout';
import { WrenchIcon } from '@/components/commons/icon/WrenchIcon';
import { Typography } from '@/components/commons/Typography';
import { useLocalization } from '@fluent/react';
import './KeybindSettings.scss';
import { Button } from '@/components/commons/Button';
import { KeybindsRow } from '@/components/commons/KeybindsRow';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { ReactNode, useEffect, useRef, useState } from 'react';
import {
ChangeKeybindRequestT,
KeybindRequestT,
KeybindResponseT,
KeybindSupport,
KeybindT,
OpenKeybindSettingsRequestT,
RpcMessage,
} from 'solarxr-protocol';
import { FormProvider, useFieldArray, useForm } from 'react-hook-form';
export type KeybindForm = {
keybinds: {
id: number;
name: string;
binding: string[];
delay: number;
}[];
};
export function KeybindSettings() {
const { l10n } = useLocalization();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [isOpen, setIsOpen] = useState<boolean>(false);
const [defaultKeybindsState, setDefaultKeybindsState] = useState<KeybindForm>(
{
keybinds: [],
}
);
const currentIndex = useRef<number | null>(null);
const [support, setSupport] = useState<KeybindSupport>(
KeybindSupport.UNSUPPORTED
);
const methods = useForm<KeybindForm>({
defaultValues: defaultKeybindsState,
});
const {
control,
handleSubmit,
reset,
setValue,
getValues,
setError,
clearErrors,
resetField,
watch,
} = methods;
const { fields } = useFieldArray({
control,
name: 'keybinds',
});
const onSubmit = () => {
const value = getValues();
if (checkDuplicates(value)) {
return;
}
clearErrors('keybinds');
value.keybinds.forEach((kb) => {
const changeKeybindRequest = new ChangeKeybindRequestT();
const keybind = new KeybindT();
keybind.keybindId = kb.id;
keybind.keybindValue = kb.binding.join('+');
keybind.keybindDelay = kb.delay;
changeKeybindRequest.keybind = keybind;
sendRPCPacket(RpcMessage.ChangeKeybindRequest, changeKeybindRequest);
setIsOpen(false);
});
};
const checkDuplicates = (value: KeybindForm) => {
const normalized = value.keybinds
.filter((kb) => kb.binding.length > 0)
.map((kb) => JSON.stringify([...kb.binding].sort()));
const unique = new Set(normalized);
if (unique.size !== normalized.length) {
setError('keybinds', {
type: 'manual',
message: 'Duplicate keybind combinations are not allowed',
});
return true;
}
return false;
};
const handleOpenSystemSettingsButton = () => {
sendRPCPacket(
RpcMessage.OpenKeybindSettingsRequest,
new OpenKeybindSettingsRequestT()
);
};
useRPCPacket(
RpcMessage.KeybindResponse,
({ keybind, defaultKeybinds, support }: KeybindResponseT) => {
setSupport(support);
if (!keybind) return;
const mappedDefaults = defaultKeybinds.map((kb) => ({
id: kb.keybindId,
name: kb.keybindNameId?.toString() ?? '',
binding: kb.keybindValue?.toString().split('+') ?? [],
delay: kb.keybindDelay,
}));
setDefaultKeybindsState({ keybinds: mappedDefaults });
reset({ keybinds: mappedDefaults });
const mapped = keybind.map((kb) => ({
id: kb.keybindId,
name: kb.keybindNameId?.toString() ?? '',
binding: kb.keybindValue?.toString().split('+') ?? [],
delay: kb.keybindDelay,
}));
mapped.forEach((keybind, index) => {
setValue(`keybinds.${index}.binding`, keybind.binding);
setValue(`keybinds.${index}.delay`, keybind.delay);
});
}
);
const handleOpenRecorderModal = (index: number) => {
currentIndex.current = index;
setIsOpen(true);
};
const onClose = () => {
if (currentIndex.current != null) {
resetField(`keybinds.${currentIndex.current}.binding`);
}
setIsOpen(false);
};
// Captured so the modal's callbacks keep the index they were opened with
const editedIndex = currentIndex.current;
const createKeybindRows = (): ReactNode => {
return fields.map((field, index) => {
return (
<div className="keybind-row" key={index}>
<KeybindsRow
id={field.name}
control={control}
index={index}
openKeybindRecorderModal={handleOpenRecorderModal}
/>
</div>
);
});
};
useEffect(() => {
sendRPCPacket(RpcMessage.KeybindRequest, new KeybindRequestT());
}, []);
// Only the recorder modal submits, so a delay change would otherwise never reach the server
useEffect(() => {
const subscription = watch((_, { name, type }) => {
if (type === 'change' && name?.endsWith('.delay')) onSubmit();
});
return () => subscription.unsubscribe();
}, [watch]);
return (
<SettingsPageLayout>
<SettingsPagePaneLayout icon={<WrenchIcon />} id="keybinds">
<div className="flex flex-col gap-2">
<Typography variant="main-title" id="settings-keybinds" />
<div className="flex flex-col pt-2 pb-4">
{l10n
.getString('settings-keybinds-description')
.split('\n')
.map((line, i) => (
<Typography key={i}>{line}</Typography>
))}
</div>
{support === KeybindSupport.UNSUPPORTED && (
<Typography id="settings-keybinds-unsupported-description" />
)}
{support === KeybindSupport.SYSTEM_MANAGED && (
<div className="flex flex-col gap-4">
<Typography id="settings-keybinds-system-managed-description" />
<div>
<Button
id="settings-keybinds-open-system-settings-button"
className="flex flex-col"
onClick={handleOpenSystemSettingsButton}
variant="primary"
/>
</div>
</div>
)}
{support === KeybindSupport.APP_MANAGED && (
<>
<FormProvider {...methods}>
<div className="keybind-settings">
<Typography
id="keybind_config-keybind_name"
variant="section-title"
/>
<Typography
id="keybind_config-keybind_value"
variant="section-title"
/>
<Typography
id="keybind_config-keybind_delay"
variant="section-title"
/>
{createKeybindRows()}
</div>
<div className="flex justify-end">
<Button
id="settings-keybinds_reset-all-button"
onClick={() => {
reset(defaultKeybindsState);
handleSubmit(onSubmit)();
}}
variant="primary"
/>
</div>
{editedIndex != null && (
<KeybindRecorderModal
id={fields[editedIndex].name}
control={control}
name={`keybinds.${editedIndex}.binding`}
isVisisble={isOpen}
onClose={onClose}
onUnbind={() =>
setValue(`keybinds.${editedIndex}.binding`, [])
}
onSubmit={onSubmit}
/>
)}
</FormProvider>
</>
)}
</div>
</SettingsPagePaneLayout>
</SettingsPageLayout>
);
}
@@ -1,580 +0,0 @@
import { Localized, useLocalization } from '@fluent/react';
import { yupResolver } from '@hookform/resolvers/yup';
import classNames from 'classnames';
import { ReactNode, useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { boolean, object } from 'yup';
import {
ChangeVRCOSCSettingsRequestT,
RpcMessage,
VRCOSCInputState,
VRCOSCOscQueryState,
VRCOSCOutputState,
VRCOSCSettingsRequestT,
VRCOSCSettingsResponseT,
VRCOSCStatusChangeResponseT,
VRCOSCStatusRequestT,
VRCOSCTargetSource,
type VRCOSCDiscoveredTargetT,
} from 'solarxr-protocol';
import { Button } from '@/components/commons/Button';
import { CheckBox } from '@/components/commons/Checkbox';
import { Input } from '@/components/commons/Input';
import { Typography } from '@/components/commons/Typography';
import { VRCIcon } from '@/components/commons/icon/VRCIcon';
import {
SettingsPageLayout,
SettingsPagePaneLayout,
} from '@/components/settings/SettingsPageLayout';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import {
OSCPortsAddress,
useOscPortsAddressValidator,
} from '@/hooks/osc-setting-validator';
interface VRCOSCSettingsForm {
enabled: boolean;
useManualNetwork: boolean;
portsAddress: OSCPortsAddress;
}
const defaultVRCOSCSettings: VRCOSCSettingsForm = {
enabled: false,
useManualNetwork: false,
portsAddress: {
portIn: 9001,
portOut: 9000,
address: '127.0.0.1',
},
};
function asString(value: string | Uint8Array | null | undefined): string {
return typeof value === 'string' ? value : '';
}
function formatElapsedTime(timestamp: bigint | null | undefined, now: number) {
if (!timestamp) return null;
const elapsedSeconds = Math.max(
0,
Math.floor((now - Number(timestamp)) / 1000)
);
if (elapsedSeconds < 5) return 'just now';
if (elapsedSeconds < 60) return `${elapsedSeconds}s ago`;
const elapsedMinutes = Math.floor(elapsedSeconds / 60);
if (elapsedMinutes < 60) return `${elapsedMinutes}m ago`;
const elapsedHours = Math.floor(elapsedMinutes / 60);
return `${elapsedHours}h ago`;
}
type BadgeKind =
| 'idle'
| 'listening'
| 'ready'
| 'found'
| 'searching'
| 'disabled'
| 'error';
const BADGE_LABEL_KEY: Record<BadgeKind, string> = {
idle: 'settings-osc-vrchat-status-badge-idle',
listening: 'settings-osc-vrchat-status-badge-listening',
ready: 'settings-osc-vrchat-status-badge-ready',
found: 'settings-osc-vrchat-status-badge-found',
searching: 'settings-osc-vrchat-status-badge-searching',
disabled: 'settings-osc-vrchat-status-badge-disabled',
error: 'settings-osc-vrchat-status-badge-error',
};
const BADGE_CLASSES: Record<BadgeKind, string> = {
idle: 'bg-background-50',
listening: 'bg-status-success',
ready: 'bg-status-success',
found: 'bg-status-success',
searching: 'bg-status-special',
disabled: 'bg-background-50',
error: 'bg-status-critical',
};
function StatusBadge({ kind }: { kind: BadgeKind }) {
return (
<span
className={classNames(
'rounded-md px-2 py-1 bg-background-70 flex gap-2 items-center'
)}
>
<div
className={classNames('h-2 w-2 rounded-full', BADGE_CLASSES[kind])}
/>
<Typography id={BADGE_LABEL_KEY[kind]} bold />
</span>
);
}
function StatusRow({
label,
badge,
children,
}: {
label: string;
badge: BadgeKind;
children?: ReactNode;
}) {
return (
<div className="flex flex-col gap-1 py-2">
<div className="flex items-center justify-between gap-2">
<Typography variant="section-title">{label}</Typography>
<StatusBadge kind={badge} />
</div>
{children}
</div>
);
}
function inputBadge(
state: VRCOSCInputState,
lastReceivedMillis: bigint | null | undefined
): BadgeKind {
switch (state) {
case VRCOSCInputState.LISTENING:
return lastReceivedMillis ? 'listening' : 'ready';
case VRCOSCInputState.ERROR:
return 'error';
default:
return 'idle';
}
}
function outputBadge(state: VRCOSCOutputState): BadgeKind {
switch (state) {
case VRCOSCOutputState.READY:
return 'ready';
case VRCOSCOutputState.ERROR:
return 'error';
default:
return 'idle';
}
}
function oscQueryBadge(state: VRCOSCOscQueryState): BadgeKind {
switch (state) {
case VRCOSCOscQueryState.FOUND:
return 'found';
case VRCOSCOscQueryState.SEARCHING:
return 'searching';
case VRCOSCOscQueryState.ERROR:
return 'error';
default:
return 'disabled';
}
}
function StatusCard({
status,
now,
onSwitchToTarget,
}: {
status: VRCOSCStatusChangeResponseT;
now: number;
onSwitchToTarget: (target: VRCOSCDiscoveredTargetT) => void;
}) {
const { l10n } = useLocalization();
const inputState = status.inputState ?? VRCOSCInputState.IDLE;
const outputState = status.outputState ?? VRCOSCOutputState.IDLE;
const oscQueryState = status.oscqueryState ?? VRCOSCOscQueryState.DISABLED;
const targetSource = status.targetSource ?? VRCOSCTargetSource.NONE;
const sourceLabel =
targetSource === VRCOSCTargetSource.MANUAL
? l10n.getString('settings-osc-vrchat-status-source-manual')
: targetSource === VRCOSCTargetSource.DISCOVERED
? l10n.getString('settings-osc-vrchat-status-source-auto')
: '';
const lastInputElapsed = formatElapsedTime(
status.lastReceivedInputMillis,
now
);
const lastFrameElapsed = formatElapsedTime(status.lastFrameSentMillis, now);
return (
<div className="flex flex-col bg-background-80 px-4 py-2 mb-5 rounded-md divide-y divide-background-60">
<StatusRow
label={l10n.getString('settings-osc-vrchat-status-input')}
badge={inputBadge(inputState, status.lastReceivedInputMillis)}
>
{inputState === VRCOSCInputState.IDLE ? (
<Typography color="secondary">
{l10n.getString('settings-osc-vrchat-status-input-idle')}
</Typography>
) : (
<>
<Typography color="secondary">
{l10n.getString('settings-osc-vrchat-status-input-listening', {
port: `${status.inputPort ?? 0}`,
})}
</Typography>
{inputState === VRCOSCInputState.ERROR && status.inputError ? (
<Typography color="secondary">
{asString(status.inputError)}
</Typography>
) : lastInputElapsed ? (
<Typography color="secondary">
{l10n.getString('settings-osc-vrchat-status-input-last-data', {
elapsed: lastInputElapsed,
})}
</Typography>
) : (
<Typography color="secondary">
{l10n.getString('settings-osc-vrchat-status-input-no-data')}
</Typography>
)}
</>
)}
</StatusRow>
<StatusRow
label={l10n.getString('settings-osc-vrchat-status-output')}
badge={outputBadge(outputState)}
>
{outputState === VRCOSCOutputState.IDLE ? (
<Typography color="secondary">
{l10n.getString('settings-osc-vrchat-status-output-idle')}
</Typography>
) : (
<>
<Typography color="secondary">
{l10n.getString(
outputState === VRCOSCOutputState.READY
? 'settings-osc-vrchat-status-output-sending'
: 'settings-osc-vrchat-status-output-target',
{
address: asString(status.targetAddress),
port: `${status.targetPort ?? 0}`,
source: sourceLabel,
}
)}
</Typography>
{outputState === VRCOSCOutputState.ERROR && status.outputError ? (
<Typography color="secondary">
{asString(status.outputError)}
</Typography>
) : lastFrameElapsed ? (
<Typography color="secondary">
{l10n.getString(
'settings-osc-vrchat-status-output-last-frame',
{ elapsed: lastFrameElapsed }
)}
</Typography>
) : (
<Typography color="secondary">
{l10n.getString('settings-osc-vrchat-status-output-no-frame')}
</Typography>
)}
</>
)}
</StatusRow>
<StatusRow
label={l10n.getString('settings-osc-vrchat-status-oscquery')}
badge={oscQueryBadge(oscQueryState)}
>
{oscQueryState === VRCOSCOscQueryState.DISABLED ? (
<Typography color="secondary">
{l10n.getString('settings-osc-vrchat-status-oscquery-disabled')}
</Typography>
) : oscQueryState === VRCOSCOscQueryState.ERROR ? (
<Typography color="secondary">
{asString(status.oscqueryError)}
</Typography>
) : (
<>
<Typography color="secondary">
{l10n.getString(
'settings-osc-vrchat-status-oscquery-advertising',
{ port: `${status.oscqueryAdvertisedPort ?? 0}` }
)}
</Typography>
{oscQueryState === VRCOSCOscQueryState.FOUND &&
status.discoveredTargets.length > 0 ? (
<>
<Typography color="secondary">
{l10n.getString(
'settings-osc-vrchat-status-oscquery-discovered-title'
)}
</Typography>
<ul className="flex flex-col gap-1">
{status.discoveredTargets.map((target, index) => (
<li
key={index}
className="flex items-center justify-between gap-2"
>
<Typography color="secondary">
{asString(target.name)} ({asString(target.address)}:
{target.portOut})
</Typography>
{status.discoveredTargets.length > 1 && (
<Button
variant="tertiary"
onClick={() => onSwitchToTarget(target)}
>
{l10n.getString(
'settings-osc-vrchat-status-oscquery-switch'
)}
</Button>
)}
</li>
))}
</ul>
</>
) : (
<Typography color="secondary">
{l10n.getString(
'settings-osc-vrchat-status-oscquery-searching'
)}
</Typography>
)}
</>
)}
</StatusRow>
</div>
);
}
export function VRCOSCSettings() {
const { l10n } = useLocalization();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [status, setStatus] = useState<VRCOSCStatusChangeResponseT | null>(
null
);
const [now, setNow] = useState(() => Date.now());
const { oscValidator } = useOscPortsAddressValidator();
const { reset, control, watch, handleSubmit, setValue } =
useForm<VRCOSCSettingsForm>({
defaultValues: defaultVRCOSCSettings,
reValidateMode: 'onChange',
mode: 'onChange',
resolver: yupResolver(
object({
enabled: boolean().required(),
useManualNetwork: boolean().required(),
portsAddress: oscValidator,
})
),
});
const enabled = watch('enabled');
const useManualNetwork = watch('useManualNetwork');
useEffect(() => {
const interval = window.setInterval(() => setNow(Date.now()), 1_000);
return () => window.clearInterval(interval);
}, []);
const onSubmit = (values: VRCOSCSettingsForm) => {
const req = new ChangeVRCOSCSettingsRequestT();
req.enabled = values.enabled;
req.useManualNetwork = values.useManualNetwork;
req.portIn = values.portsAddress.portIn;
req.portOut = values.portsAddress.portOut;
req.address = values.portsAddress.address;
sendRPCPacket(RpcMessage.ChangeVRCOSCSettingsRequest, req);
};
useEffect(() => {
const subscription = watch((_value, { type }) => {
if (type === 'change') {
handleSubmit(onSubmit)();
}
});
return () => subscription.unsubscribe();
}, []);
useEffect(() => {
sendRPCPacket(
RpcMessage.VRCOSCSettingsRequest,
new VRCOSCSettingsRequestT()
);
sendRPCPacket(RpcMessage.VRCOSCStatusRequest, new VRCOSCStatusRequestT());
}, []);
useRPCPacket(
RpcMessage.VRCOSCSettingsResponse,
(response: VRCOSCSettingsResponseT) => {
const formData: VRCOSCSettingsForm = {
...defaultVRCOSCSettings,
portsAddress: { ...defaultVRCOSCSettings.portsAddress },
};
formData.enabled = response.enabled;
formData.useManualNetwork = response.useManualNetwork;
formData.portsAddress.portIn = response.portIn;
formData.portsAddress.portOut = response.portOut;
formData.portsAddress.address = asString(response.address);
reset(formData);
}
);
useRPCPacket(
RpcMessage.VRCOSCStatusChangeResponse,
(response: VRCOSCStatusChangeResponseT) => {
setStatus(response);
}
);
return (
<SettingsPageLayout>
<form className="flex flex-col gap-2 w-full">
<SettingsPagePaneLayout icon={<VRCIcon />} id="vrchat">
<>
<Typography variant="main-title">
{l10n.getString('settings-osc-vrchat')}
</Typography>
<div className="flex flex-col pt-2 pb-4">
<>
{l10n
.getString('settings-osc-vrchat-description-v1')
.split('\n')
.map((line, i) => (
<Typography key={i}>{line}</Typography>
))}
</>
</div>
<Typography variant="section-title">
{l10n.getString('settings-osc-vrchat-enable')}
</Typography>
<div className="flex flex-col pb-2">
<Typography>
{l10n.getString('settings-osc-vrchat-enable-description')}
</Typography>
</div>
<div className="grid grid-cols-2 gap-3 pb-5">
<CheckBox
variant="toggle"
outlined
control={control}
name="enabled"
label={l10n.getString('settings-osc-vrchat-enable-label')}
/>
</div>
{enabled && status && (
<>
<Typography variant="section-title">
{l10n.getString('settings-osc-vrchat-status-title')}
</Typography>
<StatusCard
status={status}
now={now}
onSwitchToTarget={(target) => {
setValue('useManualNetwork', true, {
shouldDirty: true,
});
setValue('portsAddress.address', asString(target.address), {
shouldDirty: true,
});
setValue('portsAddress.portOut', target.portOut, {
shouldDirty: true,
});
}}
/>
</>
)}
<Typography variant="section-title">
{l10n.getString('settings-osc-vrchat-status-network-mode')}
</Typography>
<div className="flex flex-col pb-2">
<Typography>
{l10n.getString(
'settings-osc-vrchat-status-network-mode-description'
)}
</Typography>
</div>
<div className="grid grid-cols-2 gap-3 pb-5">
<CheckBox
variant="toggle"
outlined
control={control}
name="useManualNetwork"
label={l10n.getString(
'settings-osc-vrchat-status-network-mode-toggle'
)}
/>
</div>
{useManualNetwork && (
<>
<Typography variant="section-title">
{l10n.getString('settings-osc-vrchat-network')}
</Typography>
<div className="flex flex-col pb-2">
<Typography>
{l10n.getString(
'settings-osc-vrchat-status-network-manual-description'
)}
</Typography>
</div>
<div className="grid grid-cols-2 gap-3 pb-5">
<Localized
id="settings-osc-vrchat-network-port_in"
attrs={{ placeholder: true, label: true }}
>
<Input
type="number"
control={control}
name="portsAddress.portIn"
placeholder="9001"
label=""
/>
</Localized>
<Localized
id="settings-osc-vrchat-network-port_out"
attrs={{ placeholder: true, label: true }}
>
<Input
type="number"
control={control}
name="portsAddress.portOut"
placeholder="9000"
label=""
/>
</Localized>
</div>
<Typography variant="section-title">
{l10n.getString('settings-osc-vrchat-network-address')}
</Typography>
<div className="flex flex-col pb-2">
<Typography>
{l10n.getString(
'settings-osc-vrchat-network-address-description-v1'
)}
</Typography>
</div>
<div className="grid gap-3 pb-5">
<Input
type="text"
control={control}
name="portsAddress.address"
placeholder={l10n.getString(
'settings-osc-vrchat-network-address-placeholder'
)}
label=""
/>
</div>
</>
)}
</>
</SettingsPagePaneLayout>
</form>
</SettingsPageLayout>
);
}
@@ -1,101 +0,0 @@
import { useLocalization, Localized } from '@fluent/react';
import { useEffect } from 'react';
import { DefaultValues, useForm } from 'react-hook-form';
import {
ChangeHIDSettingsRequestT,
HIDSettingsRequestT,
HIDSettingsResponseT,
RpcMessage,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { CheckBox } from '@/components/commons/Checkbox';
import { Typography } from '@/components/commons/Typography';
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { isEqual } from '@react-hookz/deep-equal';
import { selectAtom } from 'jotai/utils';
type HIDForm = {
trackersOverHID: boolean;
};
const defaultValues: HIDForm = {
trackersOverHID: false,
};
const hidSettingsAtom = atom(new HIDSettingsResponseT());
const hidSettingsValueAtom = selectAtom(
hidSettingsAtom,
(settings) => settings,
isEqual
);
export function HIDSettings() {
const setSettings = useSetAtom(hidSettingsAtom);
const settings = useAtomValue(hidSettingsValueAtom);
const { l10n } = useLocalization();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const { control, watch, handleSubmit, getValues, reset } = useForm<HIDForm>({
defaultValues,
mode: 'onChange',
reValidateMode: 'onChange',
});
const onSubmit = (values: HIDForm) => {
const settingsReq = new ChangeHIDSettingsRequestT();
settingsReq.trackersOverHid = values.trackersOverHID;
sendRPCPacket(RpcMessage.ChangeHIDSettingsRequest, settingsReq);
};
useEffect(() => {
const subscription = watch((_, { type }) => {
if (type === 'change') handleSubmit(onSubmit)();
});
return () => subscription.unsubscribe();
}, []);
useEffect(() => {
sendRPCPacket(RpcMessage.HIDSettingsRequest, new HIDSettingsRequestT());
}, []);
useEffect(() => {
const formData: DefaultValues<HIDForm> = {
trackersOverHID: settings.trackersOverHid,
};
reset({ ...getValues(), ...formData });
}, [settings]);
useRPCPacket(
RpcMessage.HIDSettingsResponse,
(settings: HIDSettingsResponseT) => {
setSettings(settings);
}
);
return (
<>
<div className="flex flex-col pb-2">
<Typography variant="section-title">
{l10n.getString(
'settings-general-tracker_mechanics-trackers_over_usb'
)}
</Typography>
<Localized
id="settings-general-tracker_mechanics-trackers_over_usb-description"
elems={{ b: <b /> }}
>
<Typography />
</Localized>
</div>
<CheckBox
variant="toggle"
outlined
control={control}
name="trackersOverHID"
label={l10n.getString(
'settings-general-tracker_mechanics-trackers_over_usb-enabled-label'
)}
/>
</>
);
}
@@ -1,387 +0,0 @@
import { useLocalization } from '@fluent/react';
import { useEffect, useRef, useState } from 'react';
import { DefaultValues, useForm } from 'react-hook-form';
import {
BodyPart,
ChangeOutputTrackersSettingsRequestT,
OutputTrackersSettingsRequestT,
OutputTrackersSettingsResponseT,
RpcMessage,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { CheckBox } from '@/components/commons/Checkbox';
import { Typography } from '@/components/commons/Typography';
import { SettingsPagePaneLayout } from '@/components/settings/SettingsPageLayout';
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { isEqual } from '@react-hookz/deep-equal';
import { selectAtom } from 'jotai/utils';
import { HandsWarningModal } from './HandsWarningModal';
import { OutputIcon } from '@/components/commons/icon/OutputIcon';
type OutputTrackersForm = {
automaticTrackerToggle: boolean;
trackers: {
waist: boolean;
chest: boolean;
leftFoot: boolean;
rightFoot: boolean;
leftKnee: boolean;
rightKnee: boolean;
leftElbow: boolean;
rightElbow: boolean;
leftHand: boolean;
rightHand: boolean;
};
sendDerivedVelocity: boolean;
};
const defaultValues: OutputTrackersForm = {
automaticTrackerToggle: true,
trackers: {
waist: false,
chest: false,
leftFoot: false,
rightFoot: false,
leftElbow: false,
rightElbow: false,
leftHand: false,
rightHand: false,
leftKnee: false,
rightKnee: false,
},
sendDerivedVelocity: false,
};
// The tracker is at the tail of the bone.
// Example, the waist tracker is at the tail of the hip bone so we use the hip BodyPart
function togglesToBodyParts(
trackers: OutputTrackersForm['trackers']
): BodyPart[] {
const toggleToBodyPart: [boolean, BodyPart][] = [
[trackers.waist, BodyPart.HIP],
[trackers.chest, BodyPart.UPPER_CHEST],
[trackers.leftFoot, BodyPart.LEFT_FOOT],
[trackers.rightFoot, BodyPart.RIGHT_FOOT],
[trackers.leftKnee, BodyPart.LEFT_UPPER_LEG],
[trackers.rightKnee, BodyPart.RIGHT_UPPER_LEG],
[trackers.leftElbow, BodyPart.LEFT_UPPER_ARM],
[trackers.rightElbow, BodyPart.RIGHT_UPPER_ARM],
[trackers.leftHand, BodyPart.LEFT_HAND],
[trackers.rightHand, BodyPart.RIGHT_HAND],
];
return toggleToBodyPart
.filter(([enabled]) => enabled)
.map(([, part]) => part);
}
function bodyPartsToTrackers(
bodyParts: BodyPart[]
): OutputTrackersForm['trackers'] {
const set = new Set(bodyParts);
return {
waist: set.has(BodyPart.HIP),
chest: set.has(BodyPart.UPPER_CHEST),
leftFoot: set.has(BodyPart.LEFT_FOOT),
rightFoot: set.has(BodyPart.RIGHT_FOOT),
leftKnee: set.has(BodyPart.LEFT_UPPER_LEG),
rightKnee: set.has(BodyPart.RIGHT_UPPER_LEG),
leftElbow: set.has(BodyPart.LEFT_UPPER_ARM),
rightElbow: set.has(BodyPart.RIGHT_UPPER_ARM),
leftHand: set.has(BodyPart.LEFT_HAND),
rightHand: set.has(BodyPart.RIGHT_HAND),
};
}
const outputTrackersSettingsAtom = atom(new OutputTrackersSettingsResponseT());
const outputTrackersSettingsValueAtom = selectAtom(
outputTrackersSettingsAtom,
(settings) => settings,
isEqual
);
export function OutputTrackersSettings() {
const setSettings = useSetAtom(outputTrackersSettingsAtom);
const settings = useAtomValue(outputTrackersSettingsValueAtom);
const { l10n } = useLocalization();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const blockHandsWarning = useRef(false);
// If not null, warning will be shown, and showHandsWarning will
// hold which hands should be toggled ([leftHand, rightHand])
const [showHandsWarning, setShowHandsWarning] = useState<
[boolean, boolean] | null
>(null);
const { control, watch, handleSubmit, getValues, setValue, reset } =
useForm<OutputTrackersForm>({
defaultValues,
mode: 'onChange',
reValidateMode: 'onChange',
});
const { automaticTrackerToggle } = watch();
const onSubmit = (values: OutputTrackersForm) => {
const settingsReq = new ChangeOutputTrackersSettingsRequestT();
let leftHand = values.trackers.leftHand;
let rightHand = values.trackers.rightHand;
const hadHandTracker =
settings.trackers?.includes(BodyPart.LEFT_HAND) ||
settings.trackers?.includes(BodyPart.RIGHT_HAND);
if (
!blockHandsWarning.current &&
!showHandsWarning &&
!hadHandTracker &&
(leftHand || rightHand)
) {
setShowHandsWarning([leftHand, rightHand]);
leftHand = false;
rightHand = false;
} else if (blockHandsWarning.current && !leftHand && !rightHand) {
blockHandsWarning.current = false;
}
settingsReq.trackers = togglesToBodyParts({
...values.trackers,
leftHand,
rightHand,
});
settingsReq.automaticTrackerToggle = values.automaticTrackerToggle;
settingsReq.sendDerivedVelocity = values.sendDerivedVelocity;
sendRPCPacket(RpcMessage.ChangeOutputTrackersSettingsRequest, settingsReq);
};
useEffect(() => {
const subscription = watch((_, { type }) => {
if (type === 'change') handleSubmit(onSubmit)();
});
return () => subscription.unsubscribe();
}, []);
useEffect(() => {
sendRPCPacket(
RpcMessage.OutputTrackersSettingsRequest,
new OutputTrackersSettingsRequestT()
);
}, []);
useEffect(() => {
let formData: DefaultValues<OutputTrackersForm> = {};
if (settings.trackers) {
formData = {
trackers: bodyPartsToTrackers(settings.trackers),
automaticTrackerToggle: settings.automaticTrackerToggle,
sendDerivedVelocity: settings.sendDerivedVelocity,
};
if (
!blockHandsWarning.current &&
(settings.trackers.includes(BodyPart.LEFT_HAND) ||
settings.trackers.includes(BodyPart.RIGHT_HAND))
) {
blockHandsWarning.current = true;
}
}
reset({ ...getValues(), ...formData });
}, [settings]);
useRPCPacket(
RpcMessage.OutputTrackersSettingsResponse,
(settings: OutputTrackersSettingsResponseT) => {
setSettings(settings);
}
);
return (
<>
<HandsWarningModal
isOpen={!!showHandsWarning}
onClose={() => {
setValue('trackers.leftHand', false);
setValue('trackers.rightHand', false);
setShowHandsWarning(null);
}}
accept={() => {
const [leftHand, rightHand] = showHandsWarning!;
blockHandsWarning.current = true;
setValue('trackers.leftHand', leftHand);
setValue('trackers.rightHand', rightHand);
setShowHandsWarning(null);
}}
/>
<SettingsPagePaneLayout icon={<OutputIcon />} id="output">
<>
<Typography variant="main-title">
{l10n.getString('settings-general-output')}
</Typography>
<div className="flex flex-col pb-3" />
<Typography variant="section-title">
{l10n.getString(
'settings-general-steamvr-trackers-tracker_toggling'
)}
</Typography>
<div className="flex flex-col pt-1 pb-2">
{l10n
.getString(
'settings-general-output-trackers-tracker_toggling-description'
)
.split('\n')
.map((line, i) => (
<Typography key={i}>{line}</Typography>
))}
</div>
<CheckBox
variant="toggle"
outlined
control={control}
name="automaticTrackerToggle"
label={l10n.getString(
'settings-general-steamvr-trackers-tracker_toggling-label'
)}
/>
<div className="flex flex-col pt-6" />
<Typography variant="section-title">
{l10n.getString('settings-general-output_trackers')}
</Typography>
<div className="flex flex-col pt-1 pb-2">
{l10n
.getString('settings-general-output_trackers-description')
.split('\n')
.map((line, i) => (
<Typography key={i}>{line}</Typography>
))}
</div>
<div className="grid grid-cols-2 gap-3">
<CheckBox
variant="toggle"
outlined
disabled={automaticTrackerToggle}
control={control}
name="trackers.chest"
label={l10n.getString('settings-general-steamvr-trackers-chest')}
/>
<CheckBox
variant="toggle"
outlined
disabled={automaticTrackerToggle}
control={control}
name="trackers.waist"
label={l10n.getString('settings-general-steamvr-trackers-waist')}
/>
<CheckBox
variant="toggle"
outlined
disabled={automaticTrackerToggle}
control={control}
name="trackers.leftKnee"
label={l10n.getString(
'settings-general-steamvr-trackers-left_knee'
)}
/>
<CheckBox
variant="toggle"
outlined
disabled={automaticTrackerToggle}
control={control}
name="trackers.rightKnee"
label={l10n.getString(
'settings-general-steamvr-trackers-right_knee'
)}
/>
<CheckBox
variant="toggle"
outlined
disabled={automaticTrackerToggle}
control={control}
name="trackers.leftFoot"
label={l10n.getString(
'settings-general-steamvr-trackers-left_foot'
)}
/>
<CheckBox
variant="toggle"
outlined
disabled={automaticTrackerToggle}
control={control}
name="trackers.rightFoot"
label={l10n.getString(
'settings-general-steamvr-trackers-right_foot'
)}
/>
<CheckBox
variant="toggle"
outlined
disabled={automaticTrackerToggle}
control={control}
name="trackers.leftElbow"
label={l10n.getString(
'settings-general-steamvr-trackers-left_elbow'
)}
/>
<CheckBox
variant="toggle"
outlined
disabled={automaticTrackerToggle}
control={control}
name="trackers.rightElbow"
label={l10n.getString(
'settings-general-steamvr-trackers-right_elbow'
)}
/>
<CheckBox
variant="toggle"
outlined
control={control}
name="trackers.leftHand"
label={l10n.getString(
'settings-general-steamvr-trackers-left_hand'
)}
/>
<CheckBox
variant="toggle"
outlined
control={control}
name="trackers.rightHand"
label={l10n.getString(
'settings-general-steamvr-trackers-right_hand'
)}
/>
</div>
<div className="flex flex-col pt-6" />
<Typography variant="section-title">
{l10n.getString('settings-general-fk_settings-velocity_settings')}
</Typography>
<div className="pt-1">
<Typography>
{l10n.getString(
'settings-general-fk_settings-velocity_settings-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 pt-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="sendDerivedVelocity"
label={l10n.getString(
'settings-general-fk_settings-velocity_settings-send_derived_velocity'
)}
/>
</div>
</>
</SettingsPagePaneLayout>
</>
);
}
@@ -1,231 +0,0 @@
import { useLocalization, Localized } from '@fluent/react';
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import {
ResetsSettingsRequestT,
ResetsSettingsResponseT,
RpcMessage,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useLocaleConfig } from '@/i18n/config';
import { CheckBox } from '@/components/commons/Checkbox';
import { NumberSelector } from '@/components/commons/NumberSelector';
import { Radio } from '@/components/commons/Radio';
import { Typography } from '@/components/commons/Typography';
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { isEqual } from '@react-hookz/deep-equal';
import { selectAtom } from 'jotai/utils';
type ResetsSettingsForm = {
resetMountingFeet: boolean;
armsResetMode: number;
yawResetSmoothTime: number;
saveMountingReset: boolean;
resetHmdPitch: boolean;
};
const defaultValues: ResetsSettingsForm = {
resetMountingFeet: false,
armsResetMode: 0,
yawResetSmoothTime: 0.0,
saveMountingReset: false,
resetHmdPitch: false,
};
const resetsSettingsAtom = atom(new ResetsSettingsResponseT());
const resetsSettingsValueAtom = selectAtom(
resetsSettingsAtom,
(settings) => settings,
isEqual
);
export function ResetsSettings() {
const setSettings = useSetAtom(resetsSettingsAtom);
const settings = useAtomValue(resetsSettingsValueAtom);
const { l10n } = useLocalization();
const { currentLocales } = useLocaleConfig();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const secondsFormat = new Intl.NumberFormat(currentLocales, {
style: 'unit',
unit: 'second',
unitDisplay: 'narrow',
maximumFractionDigits: 2,
});
const { control, watch, handleSubmit, getValues, reset } =
useForm<ResetsSettingsForm>({
defaultValues,
mode: 'onChange',
reValidateMode: 'onChange',
});
const onSubmit = (values: ResetsSettingsForm) => {
const resetsSettings = new ResetsSettingsResponseT();
resetsSettings.resetMountingFeet = values.resetMountingFeet;
resetsSettings.armsResetMode = values.armsResetMode;
resetsSettings.yawResetSmoothTime = values.yawResetSmoothTime;
resetsSettings.saveMountingReset = values.saveMountingReset;
resetsSettings.resetHmdPitch = values.resetHmdPitch;
sendRPCPacket(RpcMessage.ChangeResetsSettingsRequest, resetsSettings);
};
useEffect(() => {
const subscription = watch((_, { type }) => {
if (type === 'change') handleSubmit(onSubmit)();
});
return () => subscription.unsubscribe();
}, []);
useEffect(() => {
sendRPCPacket(
RpcMessage.ResetsSettingsRequest,
new ResetsSettingsRequestT()
);
}, []);
useEffect(() => {
reset({ ...getValues(), ...settings });
}, [settings]);
useRPCPacket(
RpcMessage.ResetsSettingsResponse,
(settings: ResetsSettingsResponseT) => {
setSettings(settings);
}
);
return (
<>
<div className="flex md:flex-row flex-col pt-5 pb-1">
<Typography variant="section-title">
{l10n.getString(
'settings-general-tracker_mechanics-yaw-reset-smooth-time'
)}
</Typography>
</div>
<NumberSelector
control={control}
name="yawResetSmoothTime"
valueLabelFormat={(value) => secondsFormat.format(value)}
min={0.0}
max={0.5}
step={0.05}
/>
<div className="flex flex-col pt-5 pb-2">
<Typography variant="section-title">
{l10n.getString(
'settings-general-tracker_mechanics-save_mounting_reset'
)}
</Typography>
<Localized
id="settings-general-tracker_mechanics-save_mounting_reset-description"
elems={{ b: <b /> }}
>
<Typography />
</Localized>
</div>
<CheckBox
variant="toggle"
outlined
control={control}
name="saveMountingReset"
label={l10n.getString(
'settings-general-tracker_mechanics-save_mounting_reset-enabled-label'
)}
/>
<div className="flex flex-col pt-5">
<div className="grid grid-cols-2 gap-2">
<div className="flex flex-col gap-2">
<Typography>
{l10n.getString(
'settings-general-fk_settings-reset_settings-reset_hmd_pitch-description'
)}
</Typography>
<CheckBox
variant="toggle"
outlined
control={control}
name="resetHmdPitch"
label={l10n.getString(
'settings-general-fk_settings-reset_settings-reset_hmd_pitch'
)}
/>
</div>
<div className="flex flex-col gap-2 justify-end">
<Typography>
{l10n.getString(
'settings-general-fk_settings-leg_fk-reset_mounting_feet-description-v1'
)}
</Typography>
<CheckBox
variant="toggle"
outlined
control={control}
name="resetMountingFeet"
label={l10n.getString(
'settings-general-fk_settings-leg_fk-reset_mounting_feet-v1'
)}
/>
</div>
</div>
</div>
<div className="flex flex-col pt-5">
<Typography>
{l10n.getString(
'settings-general-fk_settings-arm_fk-reset_mode-description'
)}
</Typography>
<div className="grid md:grid-cols-2 flex-col gap-3 pt-2 pb-3">
<Radio
control={control}
name="armsResetMode"
label={l10n.getString('settings-general-fk_settings-arm_fk-back')}
description={l10n.getString(
'settings-general-fk_settings-arm_fk-back-description'
)}
value={'0'}
/>
<Radio
control={control}
name="armsResetMode"
label={l10n.getString(
'settings-general-fk_settings-arm_fk-forward'
)}
description={l10n.getString(
'settings-general-fk_settings-arm_fk-forward-description'
)}
value={'1'}
/>
<Radio
control={control}
name="armsResetMode"
label={l10n.getString(
'settings-general-fk_settings-arm_fk-tpose_up'
)}
description={l10n.getString(
'settings-general-fk_settings-arm_fk-tpose_up-description'
)}
value={'2'}
/>
<Radio
control={control}
name="armsResetMode"
label={l10n.getString(
'settings-general-fk_settings-arm_fk-tpose_down'
)}
description={l10n.getString(
'settings-general-fk_settings-arm_fk-tpose_down-description'
)}
value={'3'}
/>
</div>
</div>
</>
);
}
@@ -1,365 +0,0 @@
import { Localized, useLocalization } from '@fluent/react';
import { useEffect, useState } from 'react';
import { DefaultValues, useForm } from 'react-hook-form';
import {
ChangeStayAlignedSettingsRequestT,
RpcMessage,
StayAlignedSettingsRequestT,
StayAlignedSettingsResponseT,
} from 'solarxr-protocol';
import { Button } from '@/components/commons/Button';
import { CheckBox } from '@/components/commons/Checkbox';
import { Typography } from '@/components/commons/Typography';
import { SettingsPagePaneLayout } from '@/components/settings/SettingsPageLayout';
import { HorizontalAlignIcon } from '@/components/commons/icon/HorizontalAlignIcon';
import { useAtomValue, atom, useSetAtom } from 'jotai';
import { selectAtom } from 'jotai/utils';
import { isEqual } from '@react-hookz/deep-equal';
import { connectedIMUTrackersAtom } from '@/store/app-store';
import { bodypartToString } from '@/utils/formatting';
import { useLocaleConfig } from '@/i18n/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import {
FlatRelaxedPoseModal,
SittingRelaxedPoseModal,
StandingRelaxedPoseModal,
} from './StayAlignedPoseModal';
// TODO hide_yaw_correction + setup_complete are now in their own requests
export type StayAlignedSettingsForm = {
enabled: boolean;
hideYawCorrection: boolean;
standingEnabled: boolean;
standingUpperLegAngle: number;
standingLowerLegAngle: number;
standingFootAngle: number;
sittingEnabled: boolean;
sittingUpperLegAngle: number;
sittingLowerLegAngle: number;
sittingFootAngle: number;
flatEnabled: boolean;
flatUpperLegAngle: number;
flatLowerLegAngle: number;
flatFootAngle: number;
setupComplete: boolean;
};
export const defaultStayAlignedSettings: StayAlignedSettingsForm = {
enabled: false,
hideYawCorrection: false,
standingEnabled: false,
standingUpperLegAngle: 0.0,
standingLowerLegAngle: 0.0,
standingFootAngle: 0.0,
sittingEnabled: false,
sittingUpperLegAngle: 0.0,
sittingLowerLegAngle: 0.0,
sittingFootAngle: 0.0,
flatEnabled: false,
flatUpperLegAngle: 0.0,
flatLowerLegAngle: 0.0,
flatFootAngle: 0.0,
setupComplete: false,
};
const stayAlignedSettingsAtom = atom(new StayAlignedSettingsResponseT());
const stayAlignedSettingsValueAtom = selectAtom(
stayAlignedSettingsAtom,
(settings) => settings,
isEqual
);
function CopySettingsButton({ values }: { values: StayAlignedSettingsForm }) {
const { l10n } = useLocalization();
const { currentLocales } = useLocaleConfig();
const numberFormat = new Intl.NumberFormat(currentLocales, {
minimumFractionDigits: 1,
maximumFractionDigits: 1,
});
const trackers = useAtomValue(connectedIMUTrackersAtom);
function boolify(value: boolean) {
return value ? 'true' : 'false';
}
const copySettings = () => {
const config = values;
const debug = `
Stay Aligned
GENERAL
=======
Enabled: ${config.enabled ? 'true' : 'false'}
Setup complete: ${boolify(config.setupComplete)}
RELAXED POSES
=============
Standing: ${config.standingEnabled ? `Enabled (upper_leg=${numberFormat.format(config.standingUpperLegAngle)}, lower_leg=${numberFormat.format(config.standingLowerLegAngle)}, foot=${numberFormat.format(config.standingFootAngle)})` : 'Not enabled'}
Sitting: ${config.sittingEnabled ? `Enabled (upper_leg=${numberFormat.format(config.sittingUpperLegAngle)}, lower_leg=${numberFormat.format(config.sittingLowerLegAngle)}, foot=${numberFormat.format(config.sittingFootAngle)})` : 'Not enabled'}
Flat: ${config.flatEnabled ? `Enabled (upper_leg=${numberFormat.format(config.flatUpperLegAngle)}, lower_leg=${numberFormat.format(config.flatLowerLegAngle)}, foot=${numberFormat.format(config.flatFootAngle)})` : 'Not enabled'}
TRACKERS
========
${trackers
.map((t) => {
const info = t.tracker.info;
const stayAligned = t.tracker.stayAligned;
if (info && stayAligned) {
return `${bodypartToString(info.bodyPart)}: correction=${numberFormat.format(stayAligned.yawCorrectionInDeg)} locked=${stayAligned.locked ? `true locked_error=${numberFormat.format(stayAligned.lockedErrorInDeg)}` : 'false'} center_error=${numberFormat.format(stayAligned.centerErrorInDeg)} neighbor_error=${numberFormat.format(stayAligned.neighborErrorInDeg)}`;
}
})
.join('\n')}
`;
navigator.clipboard.writeText(debug);
};
return (
<Button variant="primary" onClick={copySettings}>
{l10n.getString('settings-stay_aligned-debug-copy-label')}
</Button>
);
}
export function StayAlignedSettings() {
const setSettings = useSetAtom(stayAlignedSettingsAtom);
const settings = useAtomValue(stayAlignedSettingsValueAtom);
const { l10n } = useLocalization();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const { control, watch, handleSubmit, getValues, reset } =
useForm<StayAlignedSettingsForm>({
defaultValues: defaultStayAlignedSettings,
mode: 'onChange',
reValidateMode: 'onChange',
});
const values = watch();
const onSubmit = (values: StayAlignedSettingsForm) => {
const settingsReq = new ChangeStayAlignedSettingsRequestT();
settingsReq.enabled = values.enabled;
settingsReq.standingEnabled = values.standingEnabled;
settingsReq.standingUpperLegAngle = values.standingUpperLegAngle;
settingsReq.standingLowerLegAngle = values.standingLowerLegAngle;
settingsReq.standingFootAngle = values.standingFootAngle;
settingsReq.sittingEnabled = values.sittingEnabled;
settingsReq.sittingUpperLegAngle = values.sittingUpperLegAngle;
settingsReq.sittingLowerLegAngle = values.sittingLowerLegAngle;
settingsReq.sittingFootAngle = values.sittingFootAngle;
settingsReq.flatEnabled = values.flatEnabled;
settingsReq.flatUpperLegAngle = values.flatUpperLegAngle;
settingsReq.flatLowerLegAngle = values.flatLowerLegAngle;
settingsReq.flatFootAngle = values.flatFootAngle;
sendRPCPacket(RpcMessage.ChangeStayAlignedSettingsRequest, settingsReq);
};
useEffect(() => {
const subscription = watch((_, { type }) => {
if (type === 'change') handleSubmit(onSubmit)();
});
return () => subscription.unsubscribe();
}, []);
useEffect(() => {
sendRPCPacket(
RpcMessage.StayAlignedSettingsRequest,
new StayAlignedSettingsRequestT()
);
}, []);
useEffect(() => {
const formData: DefaultValues<StayAlignedSettingsForm> = {};
if (settings.enabled !== undefined) formData.enabled = settings.enabled;
formData.standingEnabled = settings.standingEnabled ?? false;
formData.standingUpperLegAngle = settings.standingUpperLegAngle ?? 0.0;
formData.standingLowerLegAngle = settings.standingLowerLegAngle ?? 0.0;
formData.standingFootAngle = settings.standingFootAngle ?? 0.0;
formData.sittingEnabled = settings.sittingEnabled ?? false;
formData.sittingUpperLegAngle = settings.sittingUpperLegAngle ?? 0.0;
formData.sittingLowerLegAngle = settings.sittingLowerLegAngle ?? 0.0;
formData.sittingFootAngle = settings.sittingFootAngle ?? 0.0;
formData.flatEnabled = settings.flatEnabled ?? false;
formData.flatUpperLegAngle = settings.flatUpperLegAngle ?? 0.0;
formData.flatLowerLegAngle = settings.flatLowerLegAngle ?? 0.0;
formData.flatFootAngle = settings.flatFootAngle ?? 0.0;
formData.setupComplete =
(formData.standingUpperLegAngle ?? 0) !== 0 ||
(formData.sittingUpperLegAngle ?? 0) !== 0 ||
(formData.flatUpperLegAngle ?? 0) !== 0;
reset({ ...getValues(), ...formData });
}, [settings]);
useRPCPacket(
RpcMessage.StayAlignedSettingsResponse,
(settings: StayAlignedSettingsResponseT) => {
setSettings(settings);
}
);
const config = values;
const hasStandingPose =
config.standingEnabled ||
config.standingUpperLegAngle !== 0.0 ||
config.standingLowerLegAngle !== 0.0 ||
config.standingFootAngle !== 0.0;
const hasSittingPose =
config.sittingEnabled ||
config.sittingUpperLegAngle !== 0.0 ||
config.sittingLowerLegAngle !== 0.0 ||
config.sittingFootAngle !== 0.0;
const hasFlatPose =
config.flatEnabled ||
config.flatUpperLegAngle !== 0.0 ||
config.flatLowerLegAngle !== 0.0 ||
config.flatFootAngle !== 0.0;
const openStanding = useState(false);
const openSitting = useState(false);
const openFlat = useState(false);
return (
<SettingsPagePaneLayout icon={<HorizontalAlignIcon />} id="stayAligned">
<Typography variant="main-title">
{l10n.getString('settings-stay_aligned')}
</Typography>
<div className="pt-3">
<Typography>
{l10n.getString('settings-stay_aligned-description')}
</Typography>
<Typography>
{l10n.getString('settings-stay_aligned-setup-description')}
</Typography>
<div className="flex pt-2">
<Button
variant="primary"
to="/onboarding/stay-aligned"
state={{ alonePage: true }}
>
{l10n.getString('settings-stay_aligned-setup-label')}
</Button>
</div>
</div>
<div className="pt-6">
<Typography variant="section-title">
{l10n.getString('settings-stay_aligned-general-label')}
</Typography>
<div className="grid sm:grid-cols-2 gap-3 pt-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="enabled"
label={l10n.getString('settings-stay_aligned-enabled-label')}
disabled={!config.setupComplete}
/>
<CheckBox
variant="toggle"
outlined
control={control}
name="hideYawCorrection"
label={l10n.getString(
'settings-stay_aligned-hide_yaw_correction-label'
)}
disabled={!config.setupComplete}
/>
</div>
</div>
<div className="pt-6">
<Typography variant="section-title">
{l10n.getString('settings-stay_aligned-relaxed_poses-label')}
</Typography>
<div className="pt-1">
<Typography>
{l10n.getString('settings-stay_aligned-relaxed_poses-description')}
</Typography>
</div>
<div className="grid sm:grid-cols-1 gap-3 pt-2">
<div className="flex gap-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="standingEnabled"
label={l10n.getString(
'settings-stay_aligned-relaxed_poses-standing'
)}
disabled={!config.setupComplete || !hasStandingPose}
/>
<StandingRelaxedPoseModal open={openStanding} />
<Localized id="settings-stay_aligned-relaxed_poses-save_pose">
<Button
variant="primary"
className="w-full max-w-32"
disabled={!config.setupComplete}
onClick={() => openStanding[1](true)}
/>
</Localized>
</div>
<div className="flex gap-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="sittingEnabled"
label={l10n.getString(
'settings-stay_aligned-relaxed_poses-sitting'
)}
disabled={!config.setupComplete || !hasSittingPose}
/>
<SittingRelaxedPoseModal open={openSitting} />
<Localized id="settings-stay_aligned-relaxed_poses-save_pose">
<Button
variant="primary"
className="w-full max-w-32"
disabled={!config.setupComplete}
onClick={() => openSitting[1](true)}
/>
</Localized>
</div>
<div className="flex gap-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="flatEnabled"
label={l10n.getString('settings-stay_aligned-relaxed_poses-flat')}
disabled={!config.setupComplete || !hasFlatPose}
/>
<FlatRelaxedPoseModal open={openFlat} />
<Localized id="settings-stay_aligned-relaxed_poses-save_pose">
<Button
variant="primary"
className="w-full max-w-32"
disabled={!config.setupComplete}
onClick={() => openFlat[1](true)}
/>
</Localized>
</div>
</div>
</div>
<div className="pt-6">
<Typography variant="section-title">
{l10n.getString('settings-stay_aligned-debug-label')}
</Typography>
<div className="pt-1">
<Typography>
{l10n.getString('settings-stay_aligned-debug-description')}
</Typography>
</div>
<div className="pt-2">
<CopySettingsButton values={values} />
</div>
</div>
</SettingsPagePaneLayout>
);
}
@@ -1,360 +0,0 @@
import { useLocalization } from '@fluent/react';
import { useEffect } from 'react';
import { DefaultValues, useForm } from 'react-hook-form';
import {
BodyPart,
ChangeTapDetectionSettingsRequestT,
RpcMessage,
TapDetectionSettingsRequestT,
TapDetectionSettingsResponseT,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { NumberSelector } from '@/components/commons/NumberSelector';
import { Typography } from '@/components/commons/Typography';
import { CheckBox } from '@/components/commons/Checkbox';
import { Dropdown } from '@/components/commons/Dropdown';
import { ASSIGNMENT_MODES } from '@/components/onboarding/BodyAssignment';
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { isEqual } from '@react-hookz/deep-equal';
import { selectAtom } from 'jotai/utils';
import { useLocaleConfig } from '@/i18n/config';
type TapDetectionForm = {
mountingResetEnabled: boolean;
yawResetEnabled: boolean;
fullResetEnabled: boolean;
yawResetDelay: number;
fullResetDelay: number;
mountingResetDelay: number;
yawResetTaps: number;
fullResetTaps: number;
mountingResetTaps: number;
numberTrackersOverThreshold: number;
yawResetTracker: string;
mountingResetTracker: string;
fullResetTracker: string;
};
const defaultValues: TapDetectionForm = {
mountingResetEnabled: false,
yawResetEnabled: false,
fullResetEnabled: false,
yawResetDelay: 0.2,
fullResetDelay: 1.0,
mountingResetDelay: 1.0,
yawResetTaps: 2,
fullResetTaps: 3,
mountingResetTaps: 3,
numberTrackersOverThreshold: 1,
yawResetTracker: String(BodyPart.CHEST),
mountingResetTracker: String(BodyPart.RIGHT_UPPER_LEG),
fullResetTracker: String(BodyPart.LEFT_UPPER_LEG),
};
const tapDetectionSettingsAtom = atom(new TapDetectionSettingsResponseT());
const tapDetectionSettingsValueAtom = selectAtom(
tapDetectionSettingsAtom,
(settings) => settings,
isEqual
);
export function TapDetectionSettings() {
const setSettings = useSetAtom(tapDetectionSettingsAtom);
const settings = useAtomValue(tapDetectionSettingsValueAtom);
const { l10n } = useLocalization();
const { currentLocales } = useLocaleConfig();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const secondsFormat = new Intl.NumberFormat(currentLocales, {
style: 'unit',
unit: 'second',
unitDisplay: 'narrow',
maximumFractionDigits: 2,
});
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 { control, watch, handleSubmit, getValues, reset } =
useForm<TapDetectionForm>({
defaultValues,
mode: 'onChange',
reValidateMode: 'onChange',
});
const onSubmit = (values: TapDetectionForm) => {
const settingsReq = new ChangeTapDetectionSettingsRequestT();
settingsReq.fullResetDelay = values.fullResetDelay;
settingsReq.fullResetEnabled = values.fullResetEnabled;
settingsReq.fullResetTaps = values.fullResetTaps;
settingsReq.yawResetDelay = values.yawResetDelay;
settingsReq.yawResetEnabled = values.yawResetEnabled;
settingsReq.yawResetTaps = values.yawResetTaps;
settingsReq.yawResetTracker = Number(values.yawResetTracker);
settingsReq.mountingResetTracker = Number(values.mountingResetTracker);
settingsReq.fullResetTracker = Number(values.fullResetTracker);
settingsReq.mountingResetEnabled = values.mountingResetEnabled;
settingsReq.mountingResetDelay = values.mountingResetDelay;
settingsReq.mountingResetTaps = values.mountingResetTaps;
settingsReq.numberTrackersOverThreshold =
values.numberTrackersOverThreshold;
sendRPCPacket(RpcMessage.ChangeTapDetectionSettingsRequest, settingsReq);
};
useEffect(() => {
const subscription = watch((_, { type }) => {
if (type === 'change') handleSubmit(onSubmit)();
});
return () => subscription.unsubscribe();
}, []);
useEffect(() => {
sendRPCPacket(
RpcMessage.TapDetectionSettingsRequest,
new TapDetectionSettingsRequestT()
);
}, []);
useEffect(() => {
const formData: DefaultValues<TapDetectionForm> = {
yawResetEnabled:
settings.yawResetEnabled || defaultValues.yawResetEnabled,
fullResetEnabled:
settings.fullResetEnabled || defaultValues.fullResetEnabled,
mountingResetEnabled:
settings.mountingResetEnabled || defaultValues.mountingResetEnabled,
yawResetDelay: settings.yawResetDelay || defaultValues.yawResetDelay,
fullResetDelay: settings.fullResetDelay || defaultValues.fullResetDelay,
mountingResetDelay:
settings.mountingResetDelay || defaultValues.mountingResetDelay,
yawResetTaps: settings.yawResetTaps || defaultValues.yawResetTaps,
fullResetTaps: settings.fullResetTaps || defaultValues.fullResetTaps,
mountingResetTaps:
settings.mountingResetTaps || defaultValues.mountingResetTaps,
yawResetTracker: String(
settings.yawResetTracker || defaultValues.yawResetTracker
),
fullResetTracker: String(
settings.fullResetTracker || defaultValues.fullResetTracker
),
mountingResetTracker: String(
settings.mountingResetTracker || defaultValues.mountingResetTracker
),
numberTrackersOverThreshold:
settings.numberTrackersOverThreshold ||
defaultValues.numberTrackersOverThreshold,
};
reset({ ...getValues(), ...formData });
}, [settings]);
useRPCPacket(
RpcMessage.TapDetectionSettingsResponse,
(settings: TapDetectionSettingsResponseT) => {
setSettings(settings);
}
);
return (
<>
<div className="flex flex-col pb-2 gap-1">
<Typography variant="section-title">
{l10n.getString('settings-general-gesture_control-subtitle')}
</Typography>
<Typography>
{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="yawResetEnabled"
label={l10n.getString(
'settings-general-gesture_control-yawResetEnabled'
)}
/>
<CheckBox
variant="toggle"
outlined
control={control}
name="fullResetEnabled"
label={l10n.getString(
'settings-general-gesture_control-fullResetEnabled'
)}
/>
<CheckBox
variant="toggle"
outlined
control={control}
name="mountingResetEnabled"
label={l10n.getString(
'settings-general-gesture_control-mountingResetEnabled'
)}
/>
</div>
<div className="grid sm:grid-cols-3 gap-5 pb-2">
<div>
<Typography variant="section-title">
{l10n.getString(
'settings-general-gesture_control-yawResetTracker'
)}
</Typography>
<Dropdown
display="block"
control={control}
placeholder={''}
name="yawResetTracker"
items={bodyParts}
/>
</div>
<div>
<Typography variant="section-title">
{l10n.getString(
'settings-general-gesture_control-mountingResetTracker'
)}
</Typography>
<Dropdown
display="block"
control={control}
placeholder={''}
name="mountingResetTracker"
items={bodyParts}
/>
</div>
<div>
<Typography variant="section-title">
{l10n.getString(
'settings-general-gesture_control-fullResetTracker'
)}
</Typography>
<Dropdown
display="block"
control={control}
placeholder={''}
name="fullResetTracker"
items={bodyParts}
/>
</div>
</div>
</div>
<div className="grid sm:grid-cols-3 gap-5 pb-2">
<NumberSelector
control={control}
name="yawResetDelay"
label={l10n.getString(
'settings-general-gesture_control-yawResetDelay'
)}
valueLabelFormat={(value) => secondsFormat.format(value)}
min={0.2}
max={3.0}
step={0.2}
/>
<NumberSelector
control={control}
name="fullResetDelay"
label={l10n.getString(
'settings-general-gesture_control-fullResetDelay'
)}
valueLabelFormat={(value) => secondsFormat.format(value)}
min={0.2}
max={3.0}
step={0.2}
/>
<NumberSelector
control={control}
name="mountingResetDelay"
label={l10n.getString(
'settings-general-gesture_control-mountingResetDelay'
)}
valueLabelFormat={(value) => secondsFormat.format(value)}
min={0.2}
max={3.0}
step={0.2}
/>
</div>
<div className="grid sm:grid-cols-3 gap-5">
<NumberSelector
control={control}
name="yawResetTaps"
label={l10n.getString(
'settings-general-gesture_control-yawResetTaps'
)}
valueLabelFormat={(value) =>
l10n.getString('settings-general-gesture_control-taps', {
amount: Math.round(value),
})
}
min={2}
max={10}
step={1}
/>
<NumberSelector
control={control}
name="fullResetTaps"
label={l10n.getString(
'settings-general-gesture_control-fullResetTaps'
)}
valueLabelFormat={(value) =>
l10n.getString('settings-general-gesture_control-taps', {
amount: Math.round(value),
})
}
min={2}
max={10}
step={1}
/>
<NumberSelector
control={control}
name="mountingResetTaps"
label={l10n.getString(
'settings-general-gesture_control-mountingResetTaps'
)}
valueLabelFormat={(value) =>
l10n.getString('settings-general-gesture_control-taps', {
amount: Math.round(value),
})
}
min={2}
max={10}
step={1}
/>
</div>
<div className="grid sm:grid-cols-1 gap-1 pt-3">
<Typography variant="section-title">
{l10n.getString(
'settings-general-gesture_control-numberTrackersOverThreshold'
)}
</Typography>
<Typography>
{l10n.getString(
'settings-general-gesture_control-numberTrackersOverThreshold-description'
)}
</Typography>
<div>
<NumberSelector
control={control}
name="numberTrackersOverThreshold"
valueLabelFormat={(value) =>
l10n.getString('settings-general-gesture_control-trackers', {
amount: Math.round(value),
})
}
min={1}
max={20}
step={1}
/>
</div>
</div>
</>
);
}
@@ -1,524 +0,0 @@
import { useLocalization } from '@fluent/react';
import { useEffect } from 'react';
import { DefaultValues, useForm } from 'react-hook-form';
import {
ChangeSkeletonSettingsRequestT,
FilteringType,
RpcMessage,
SkeletonFilteringT,
SkeletonRatiosT,
SkeletonSettingsRequestT,
SkeletonSettingsResponseT,
SkeletonTogglesT,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useLocaleConfig } from '@/i18n/config';
import { CheckBox } from '@/components/commons/Checkbox';
import { NumberSelector } from '@/components/commons/NumberSelector';
import { Radio } from '@/components/commons/Radio';
import { Typography } from '@/components/commons/Typography';
import { SettingsPagePaneLayout } from '@/components/settings/SettingsPageLayout';
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { isEqual } from '@react-hookz/deep-equal';
import { selectAtom } from 'jotai/utils';
import { MartialArtsIcon } from '@/components/commons/icon/MartialArtsIcon';
type SkeletonForm = {
toggles: {
forceArmsFromHmd: boolean;
floorClip: boolean;
skatingCorrection: boolean;
toeSnap: boolean;
footPlant: boolean;
mocapMode: boolean;
useTrackerPositions: boolean;
enforceConstraints: boolean;
correctConstraints: boolean;
};
ratios: {
imputeSpineFromUpperToLower: number;
imputeSpineCurvature: number;
interpolateHipWithKnees: number;
interpolateComputedKneesWithAnkles: number;
interpolateKneesWithAnkles: number;
skatingCorrectionStrength: number;
};
filtering: {
type: number;
amount: number;
};
};
// Exported so other components (e.g. StayAlignedSettings' debug copy) can
// read the current skeleton toggles/filtering without re-requesting them.
export const skeletonSettingsAtom = atom(new SkeletonSettingsResponseT());
const skeletonSettingsValueAtom = selectAtom(
skeletonSettingsAtom,
(settings) => settings,
isEqual
);
const defaultValues: SkeletonForm = {
toggles: {
forceArmsFromHmd: false,
floorClip: false,
skatingCorrection: false,
toeSnap: false,
footPlant: true,
mocapMode: false,
useTrackerPositions: true,
enforceConstraints: true,
correctConstraints: true,
},
ratios: {
imputeSpineFromUpperToLower: 0.5,
imputeSpineCurvature: 0.5,
interpolateHipWithKnees: 0.25,
interpolateComputedKneesWithAnkles: 0.85,
interpolateKneesWithAnkles: 0.0,
skatingCorrectionStrength: 0.3,
},
filtering: { amount: 0.1, type: FilteringType.NONE },
};
export function TrackingSettings() {
const setSettings = useSetAtom(skeletonSettingsAtom);
const settings = useAtomValue(skeletonSettingsValueAtom);
const { l10n } = useLocalization();
const { currentLocales } = useLocaleConfig();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const percentageFormat = new Intl.NumberFormat(currentLocales, {
style: 'percent',
maximumFractionDigits: 0,
});
const { control, watch, handleSubmit, getValues, reset } =
useForm<SkeletonForm>({
defaultValues,
mode: 'onChange',
reValidateMode: 'onChange',
});
const onSubmit = (values: SkeletonForm) => {
const settingsReq = new ChangeSkeletonSettingsRequestT();
const toggles = new SkeletonTogglesT();
toggles.floorClip = values.toggles.floorClip;
toggles.skatingCorrection = values.toggles.skatingCorrection;
toggles.forceArmsFromHmd = values.toggles.forceArmsFromHmd;
toggles.toeSnap = values.toggles.toeSnap;
toggles.footPlant = values.toggles.footPlant;
toggles.mocapMode = values.toggles.mocapMode;
toggles.useTrackerPositions = values.toggles.useTrackerPositions;
toggles.enforceConstraints = values.toggles.enforceConstraints;
toggles.correctConstraints = values.toggles.correctConstraints;
settingsReq.toggles = toggles;
const ratios = new SkeletonRatiosT();
ratios.imputeSpineFromUpperToLower =
values.ratios.imputeSpineFromUpperToLower;
ratios.imputeSpineCurvature = values.ratios.imputeSpineCurvature;
ratios.interpolateHipWithKnees = values.ratios.interpolateHipWithKnees;
ratios.interpolateComputedKneesWithAnkles =
values.ratios.interpolateComputedKneesWithAnkles;
ratios.interpolateKneesWithAnkles =
values.ratios.interpolateKneesWithAnkles;
ratios.skatingCorrectionStrength = values.ratios.skatingCorrectionStrength;
settingsReq.ratios = ratios;
const filtering = new SkeletonFilteringT();
filtering.type = values.filtering.type;
filtering.amount = values.filtering.amount;
settingsReq.filtering = filtering;
sendRPCPacket(RpcMessage.ChangeSkeletonSettingsRequest, settingsReq);
};
useEffect(() => {
const subscription = watch((_, { type }) => {
if (type === 'change') handleSubmit(onSubmit)();
});
return () => subscription.unsubscribe();
}, []);
useEffect(() => {
sendRPCPacket(
RpcMessage.SkeletonSettingsRequest,
new SkeletonSettingsRequestT()
);
}, []);
useEffect(() => {
const formData: DefaultValues<SkeletonForm> = {};
if (settings.toggles) {
formData.toggles = Object.keys(settings.toggles).reduce(
(curr, key: string) => ({
...curr,
[key]: (settings.toggles && (settings.toggles as any)[key]) || false,
}),
{}
);
}
if (settings.ratios) {
formData.ratios = Object.keys(settings.ratios).reduce(
(curr, key: string) => ({
...curr,
[key]: (settings.ratios && (settings.ratios as any)[key]) || 0.0,
}),
{}
);
}
if (settings.filtering) {
formData.filtering = {
type: settings.filtering.type ?? defaultValues.filtering.type,
amount: settings.filtering.amount ?? defaultValues.filtering.amount,
};
}
reset({ ...getValues(), ...formData });
}, [settings]);
useRPCPacket(
RpcMessage.SkeletonSettingsResponse,
(settings: SkeletonSettingsResponseT) => {
setSettings(settings);
}
);
return (
<SettingsPagePaneLayout icon={<MartialArtsIcon />} id="tracking">
<>
<Typography variant="main-title">
{l10n.getString('settings-general-fk_settings')}
</Typography>
<div className="flex flex-col pt-3">
<Typography variant="section-title">
{l10n.getString('settings-general-tracker_mechanics-filtering')}
</Typography>
</div>
<div className="flex flex-col pt-1 pb-3">
{l10n
.getString(
'settings-general-tracker_mechanics-filtering-description'
)
.split('\n')
.map((line, i) => (
<Typography key={i}>{line}</Typography>
))}
</div>
<Typography bold>
{l10n.getString('settings-general-tracker_mechanics-filtering-type')}
</Typography>
<div className="flex md:flex-row flex-col gap-3 pt-2">
<Radio
control={control}
name="filtering.type"
label={l10n.getString(
'settings-general-tracker_mechanics-filtering-type-none'
)}
description={l10n.getString(
'settings-general-tracker_mechanics-filtering-type-none-description'
)}
value={FilteringType.NONE.toString()}
/>
<Radio
control={control}
name="filtering.type"
label={l10n.getString(
'settings-general-tracker_mechanics-filtering-type-smoothing'
)}
description={l10n.getString(
'settings-general-tracker_mechanics-filtering-type-smoothing-description'
)}
value={FilteringType.SMOOTHING.toString()}
/>
<Radio
control={control}
name="filtering.type"
label={l10n.getString(
'settings-general-tracker_mechanics-filtering-type-prediction'
)}
description={l10n.getString(
'settings-general-tracker_mechanics-filtering-type-prediction-description'
)}
value={FilteringType.PREDICTION.toString()}
/>
</div>
<div className="flex pt-3 md:flex-row flex-col">
<NumberSelector
control={control}
name="filtering.amount"
label={l10n.getString(
'settings-general-tracker_mechanics-filtering-amount'
)}
valueLabelFormat={(value) => percentageFormat.format(value)}
min={0.1}
max={1.0}
step={0.1}
/>
</div>
<div className="flex flex-col pt-6 pb-2 gap-1">
<Typography variant="section-title">
{l10n.getString(
'settings-general-fk_settings-leg_tweak-skating_correction'
)}
</Typography>
<Typography>
{l10n.getString(
'settings-general-fk_settings-leg_tweak-skating_correction-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 gap-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.skatingCorrection"
label={l10n.getString(
'settings-general-fk_settings-leg_tweak-skating_correction'
)}
/>
<NumberSelector
control={control}
name="ratios.skatingCorrectionStrength"
label={l10n.getString(
'settings-general-fk_settings-leg_tweak-skating_correction-amount'
)}
valueLabelFormat={(value) => percentageFormat.format(value)}
min={0.1}
max={1.0}
step={0.1}
/>
</div>
<div className="flex flex-col pt-6 pb-1">
<Typography variant="section-title">
{l10n.getString('settings-general-fk_settings-leg_fk')}
</Typography>
</div>
<div className="grid sm:grid-cols-1 pb-2">
<Typography>
{l10n.getString(
'settings-general-fk_settings-leg_tweak-floor_clip-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.floorClip"
label={l10n.getString(
'settings-general-fk_settings-leg_tweak-floor_clip'
)}
/>
</div>
<div className="flex flex-col pt-5 pb-2">
<Typography>
{l10n.getString(
'settings-general-fk_settings-leg_tweak-foot_plant-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.footPlant"
label={l10n.getString(
'settings-general-fk_settings-leg_tweak-foot_plant'
)}
/>
</div>
<div className="flex flex-col pt-5">
<Typography>
{l10n.getString(
'settings-general-fk_settings-leg_tweak-toe_snap-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 gap-3 pt-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.toeSnap"
label={l10n.getString(
'settings-general-fk_settings-leg_tweak-toe_snap'
)}
/>
</div>
<div className="flex flex-col pt-5">
<Typography variant="section-title">
{l10n.getString('settings-general-fk_settings-arm_fk')}
</Typography>
<Typography>
{l10n.getString('settings-general-fk_settings-arm_fk-description')}
</Typography>
</div>
<div className="grid sm:grid-cols-1 pt-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.forceArmsFromHmd"
label={l10n.getString(
'settings-general-fk_settings-arm_fk-force_arms'
)}
/>
</div>
<div className="flex flex-col pt-5">
<Typography variant="section-title">
{l10n.getString(
'settings-general-fk_settings-enforce_joint_constraints'
)}
</Typography>
<Typography>
{l10n.getString(
'settings-general-fk_settings-enforce_joint_constraints-enforce_constraints-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 pt-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.enforceConstraints"
label={l10n.getString(
'settings-general-fk_settings-enforce_joint_constraints-enforce_constraints'
)}
/>
</div>
<div className="flex flex-col pt-5">
<Typography variant="section-title">
{l10n.getString('settings-general-fk_settings-ik')}
</Typography>
<Typography>
{l10n.getString(
'settings-general-fk_settings-ik-use_position-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 pt-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.useTrackerPositions"
label={l10n.getString(
'settings-general-fk_settings-ik-use_position'
)}
/>
</div>
<div className="flex flex-col pt-5">
<Typography variant="section-title">
{l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
</Typography>
<Typography>
{l10n.getString(
'settings-general-fk_settings-self_localization-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 pt-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.mocapMode"
label={l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
/>
</div>
<div className="flex flex-col pt-5">
<Typography variant="section-title">
{l10n.getString(
'settings-general-fk_settings-skeleton_settings-ratios'
)}
</Typography>
<Typography>
{l10n.getString(
'settings-general-fk_settings-skeleton_settings-ratios-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-2 gap-3 pt-2">
<NumberSelector
control={control}
name="ratios.imputeSpineFromUpperToLower"
label={l10n.getString(
'settings-general-fk_settings-skeleton_settings-impute_spine_from_upper_to_lower'
)}
valueLabelFormat={(value) => percentageFormat.format(value)}
min={0.0}
max={1.0}
step={0.05}
/>
<NumberSelector
control={control}
name="ratios.imputeSpineCurvature"
label={l10n.getString(
'settings-general-fk_settings-skeleton_settings-impute_spine_curvature'
)}
valueLabelFormat={(value) => percentageFormat.format(value)}
min={0.0}
max={1.0}
step={0.05}
/>
<NumberSelector
control={control}
name="ratios.interpolateHipWithKnees"
label={l10n.getString(
'settings-general-fk_settings-skeleton_settings-interpolate_hip_with_knees'
)}
valueLabelFormat={(value) => percentageFormat.format(value)}
min={0.0}
max={1.0}
step={0.05}
/>
<NumberSelector
control={control}
name="ratios.interpolateComputedKneesWithAnkles"
label={l10n.getString(
'settings-general-fk_settings-skeleton_settings-interpolate_computed_knees_with_ankles'
)}
valueLabelFormat={(value) => percentageFormat.format(value)}
min={0.0}
max={1.0}
step={0.05}
/>
<NumberSelector
control={control}
name="ratios.interpolateKneesWithAnkles"
label={l10n.getString(
'settings-general-fk_settings-skeleton_settings-interpolate_knees_with_ankles'
)}
valueLabelFormat={(value) => percentageFormat.format(value)}
min={0.0}
max={1.0}
step={0.05}
/>
</div>
</>
</SettingsPagePaneLayout>
);
}
@@ -1,372 +0,0 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { TrackerDataT } from 'solarxr-protocol';
import { useTracker } from '@/hooks/tracker';
import { Typography } from '@/components/commons/Typography';
import { formatVector3 } from '@/utils/formatting';
import {
AmbientLight,
ArrowHelper,
AxesHelper,
Color,
DoubleSide,
Group,
Mesh,
MeshBasicMaterial,
PerspectiveCamera,
PlaneGeometry,
Scene,
SpotLight,
Vector3,
WebGLRenderer,
} from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { Button } from '@/components/commons/Button';
import { QuatObject } from '@/maths/quaternion';
import { useLocalization } from '@fluent/react';
import { Vector3Object, Vector3FromVec3fT } from '@/maths/vector3';
import { ErrorBoundary } from 'react-error-boundary';
import { StayAlignedInfo } from '@/components/stay-aligned/StayAlignedInfo';
const GROUND_COLOR = '#4444aa';
const MODEL_SCALE = 6.5;
const CANVAS_HEIGHT = 200;
// Three.js context - isolated from React
type IMUVisualizerContext = {
scene: Scene;
camera: PerspectiveCamera;
renderer: WebGLRenderer;
trackerGroup: Group;
accelArrow: ArrowHelper;
magArrow: ArrowHelper;
animationId: number | null;
update: (quat: QuatObject, vec: Vector3Object, mag: Vector3Object) => void;
dispose: () => void;
};
async function initializeIMUVisualizer(
canvas: HTMLCanvasElement,
modelPath: string
): Promise<IMUVisualizerContext> {
const scene = new Scene();
const camera = new PerspectiveCamera(
60,
canvas.clientWidth / CANVAS_HEIGHT,
0.1,
1000
);
camera.position.set(0, 0, 7);
const renderer = new WebGLRenderer({ canvas, alpha: true, antialias: true });
renderer.setSize(canvas.clientWidth, CANVAS_HEIGHT);
const ambientLight = new AmbientLight(0xffffff, 0.5 * Math.PI);
scene.add(ambientLight);
const spotLight = new SpotLight(0xffffff, 4000);
spotLight.position.set(20, 20, 20);
spotLight.angle = 0.09;
spotLight.penumbra = 1;
scene.add(spotLight);
const trackerGroup = new Group();
scene.add(trackerGroup);
const loader = new GLTFLoader();
const gltf = await loader.loadAsync(modelPath);
const modelGroup = new Group();
modelGroup.scale.setScalar(MODEL_SCALE);
modelGroup.rotation.x = Math.PI / 2;
modelGroup.add(gltf.scene);
trackerGroup.add(modelGroup);
const axesHelper = new AxesHelper(10);
trackerGroup.add(axesHelper);
const accelArrow = new ArrowHelper(
new Vector3(0, 1, 0),
new Vector3(0, 0, 0),
1,
0xffff00
);
scene.add(accelArrow);
const magArrow = new ArrowHelper(
new Vector3(0, 1, 0),
new Vector3(0, 0, 0),
1,
Color.NAMES.aqua
);
scene.add(magArrow);
const groundGeometry = new PlaneGeometry(50, 50, 10, 10);
const groundMaterial = new MeshBasicMaterial({
wireframe: true,
color: GROUND_COLOR,
transparent: true,
opacity: 0.2,
side: DoubleSide,
});
const ground = new Mesh(groundGeometry, groundMaterial);
ground.position.set(0, -3, 0);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);
let animationId: number | null = null;
const animate = () => {
animationId = requestAnimationFrame(animate);
renderer.render(scene, camera);
};
animate();
const update = (quat: QuatObject, vec: Vector3Object, mag: Vector3Object) => {
trackerGroup.quaternion.set(quat.x, quat.y, quat.z, quat.w);
const accelVec = Vector3FromVec3fT(vec);
const accelLength = accelVec.length();
if (accelLength > 0) {
accelArrow.setDirection(accelVec.normalize());
accelArrow.setLength(Math.sqrt(accelLength) * 2);
}
const magVec = Vector3FromVec3fT(mag);
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();
}
};
const dispose = () => {
if (animationId !== null) {
cancelAnimationFrame(animationId);
}
renderer.dispose();
groundGeometry.dispose();
groundMaterial.dispose();
scene.clear();
};
return {
scene,
camera,
renderer,
trackerGroup,
accelArrow,
magArrow,
animationId,
update,
dispose,
};
}
function IMUVisualizerCanvas({
quat,
vec,
mag,
model,
}: {
quat: QuatObject;
vec: Vector3Object;
mag: Vector3Object;
model: string;
}) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const contextRef = useRef<IMUVisualizerContext | null>(null);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
if (!canvasRef.current) return;
let mounted = true;
initializeIMUVisualizer(canvasRef.current, model)
.then((ctx) => {
if (mounted) {
contextRef.current = ctx;
ctx.update(quat, vec, mag);
} else {
ctx.dispose();
}
})
.catch((err) => {
if (mounted) {
setError(err);
}
});
return () => {
mounted = false;
contextRef.current?.dispose();
contextRef.current = null;
};
}, [model]);
useEffect(() => {
contextRef.current?.update(quat, vec, mag);
}, [quat, vec, mag]);
if (error) {
throw error;
}
return (
<canvas
ref={canvasRef}
className="container"
style={{
width: '100%',
height: CANVAS_HEIGHT,
background: 'transparent',
}}
/>
);
}
export function IMUVisualizerWidget({ tracker }: { tracker: TrackerDataT }) {
const { l10n } = useLocalization();
const [enabled, setEnabled] = useState(false);
const isExtension = false; // TODO Do we want to display extensions?
useEffect(() => {
const state = localStorage.getItem('modelPreview');
if (state) setEnabled(state === 'true');
}, []);
const { useRawRotationEulerDegrees, useIdentAdjRotationEulerDegrees } =
useTracker(tracker);
const rotationRaw = useRawRotationEulerDegrees();
const rotationIdent = useIdentAdjRotationEulerDegrees() || rotationRaw;
const quat = useMemo(
() =>
tracker?.rotationIdentityAdjusted ||
tracker?.rotation || { x: 0, y: 0, z: 0, w: 1 },
[tracker?.rotationIdentityAdjusted, tracker?.rotation]
);
const vec = useMemo(
() =>
tracker?.linearAcceleration ||
tracker?.rawAcceleration || { x: 0, y: 0, z: 0 },
[tracker?.linearAcceleration, tracker?.rawAcceleration]
);
const mag = useMemo(
() => tracker?.rawMagneticVector || { x: 0, y: 0, z: 0 },
[tracker?.rawMagneticVector]
);
const model = useMemo(
() => (isExtension ? '/models/extension.gltf' : '/models/tracker.gltf'),
[isExtension]
);
return (
<div className="bg-background-70 flex flex-col p-3 rounded-lg gap-2">
<Typography variant="section-title">
{l10n.getString('widget-imu_visualizer')}
</Typography>
{tracker.position && (
<div className="flex justify-between">
<Typography>
{l10n.getString('widget-imu_visualizer-position')}
</Typography>
<Typography>{formatVector3(tracker.position, 2)}</Typography>
</div>
)}
<div className="flex justify-between">
<Typography>
{l10n.getString('widget-imu_visualizer-rotation_raw')}
</Typography>
<Typography>{formatVector3(rotationRaw, 2)}</Typography>
</div>
<div className="flex justify-between">
<Typography>
{l10n.getString('widget-imu_visualizer-rotation_preview')}
</Typography>
<Typography>{formatVector3(rotationIdent, 2)}</Typography>
</div>
{tracker.linearAcceleration && (
<div className="flex justify-between">
<Typography>
{l10n.getString('widget-imu_visualizer-acceleration')}
</Typography>
<Typography>
{formatVector3(tracker.linearAcceleration, 1)}
</Typography>
</div>
)}
{tracker.rawMagneticVector && (
<div className="flex justify-between">
<Typography>
{l10n.getString('tracker-infos-magnetometer')}
</Typography>
<Typography>{formatVector3(tracker.rawMagneticVector, 1)}</Typography>
</div>
)}
{!!tracker.stayAligned && (
<div className="flex justify-between">
<Typography>
{l10n.getString('widget-imu_visualizer-stay_aligned')}
</Typography>
<StayAlignedInfo color="primary" tracker={tracker} />
</div>
)}
{!enabled && (
<Button
variant="secondary"
onClick={() => {
setEnabled(true);
localStorage.setItem('modelPreview', 'true');
}}
>
{l10n.getString('widget-imu_visualizer-preview')}
</Button>
)}
{enabled && (
<>
<Button
variant="secondary"
onClick={() => {
setEnabled(false);
localStorage.setItem('modelPreview', 'false');
}}
>
{l10n.getString('widget-imu_visualizer-hide')}
</Button>
<ErrorBoundary
fallback={
<Typography color="primary" textAlign="text-center">
{l10n.getString('tips-failed_webgl')}
</Typography>
}
>
<IMUVisualizerCanvas
quat={quat}
vec={vec}
mag={mag}
model={model}
/>
</ErrorBoundary>
</>
)}
</div>
);
}
-7
View File
@@ -1,7 +0,0 @@
export async function openUrl(url: string) {
if (window.electronAPI) {
window.electronAPI.openUrl(url);
} else {
window.open(url, '_blank');
}
}
-31
View File
@@ -1,31 +0,0 @@
import { useEffect, useMemo } from 'react';
import { useConfig } from './config';
import { useLocalization } from '@fluent/react';
import { connectedIMUTrackersAtom } from '@/store/app-store';
import { useAtomValue } from 'jotai';
import { useElectron } from './electron';
export function useDiscordPresence() {
const electron = useElectron();
if (!electron.isElectron) return;
const { config } = useConfig();
const { l10n } = useLocalization();
const imuTrackers = useAtomValue(connectedIMUTrackersAtom);
const imuTrackersCount = useMemo(() => imuTrackers.length, [imuTrackers.length]);
useEffect(() => {
if (config?.discordPresence === false) {
electron.api.setPresence({ enable: false });
return;
}
electron.api.setPresence({
enable: true,
activity: l10n.getString('settings-general-interface-discord_presence-message', {
amount: imuTrackersCount,
}),
iconText: (__VERSION_TAG__ || __COMMIT_HASH__) + (__GIT_CLEAN__ ? '' : '-dirty'),
});
}, [config?.discordPresence, imuTrackersCount]);
}
-46
View File
@@ -1,46 +0,0 @@
import { IElectronAPI, OSStats } from '@slimevr/gui-shared';
import { createContext, useContext, useLayoutEffect, useState } from 'react';
type CachedData = {
os: OSStats;
};
type AvailableElectron = {
isElectron: true;
api: IElectronAPI;
data: () => CachedData;
};
type ElectronContext = AvailableElectron | { isElectron: false };
export const ElectronContextC = createContext<ElectronContext>(undefined as any);
export function provideElectron(): ElectronContext {
const api = window.electronAPI;
if (!api) return { isElectron: false };
const [cachedData, setCachedData] = useState<CachedData>();
useLayoutEffect(() => {
Promise.all([api.osStats()]).then(([os]) => {
setCachedData({
os,
});
});
}, []);
return {
isElectron: true,
api,
data: () => {
if (!cachedData) throw 'not loaded yet';
return cachedData;
},
};
}
export function useElectron() {
const context = useContext<ElectronContext>(ElectronContextC);
if (!context) {
throw new Error('useElectron must be within a ElectronContext Provider');
}
return context;
}
-195
View File
@@ -1,195 +0,0 @@
import {
createContext,
Reducer,
useContext,
useEffect,
useLayoutEffect,
useReducer,
useState,
} from 'react';
import { useLocation } from 'react-router-dom';
import { useConfig } from './config';
import { useWebsocketAPI } from './websocket-api';
import {
ChangeResetsSettingsRequestT,
ChangeSkeletonSettingsRequestT,
ResetsSettingsRequestT,
ResetsSettingsResponseT,
RpcMessage,
SkeletonBone,
SkeletonSettingsRequestT,
SkeletonSettingsResponseT,
SkeletonTogglesT,
VRCOSCSettingsRequestT,
VRCOSCSettingsResponseT,
} from 'solarxr-protocol';
import { useManualProportions } from './manual-proportions';
type OnboardingAction =
| { type: 'progress'; value: number }
| { type: 'alone-page'; value: boolean }
| { type: 'wifi-creds'; ssid: string; password: string };
interface OnboardingState {
progress: number;
wifi?: { ssid: string; password: string };
alonePage: boolean;
}
export function reducer(state: OnboardingState, action: OnboardingAction) {
switch (action.type) {
case 'wifi-creds':
return {
...state,
wifi: { ssid: action.ssid, password: action.password },
};
case 'progress':
return {
...state,
progress: action.value,
};
case 'alone-page':
return {
...state,
alonePage: action.value,
};
default:
throw new Error(`unhandled state action ${(action as any).type}`);
}
}
export type OnboardingContext = ReturnType<typeof useProvideOnboarding>;
export function useProvideOnboarding() {
const { setConfig } = useConfig();
const [slimeSet, setSlimeSet] = useState<
'butterfly' | 'slime-v1' | 'dongle-slime' | 'wifi-slime'
>();
const [usage, setUsage] = useState<'vr-gaming' | 'mocap' | 'vtubing'>();
const [vrcOsc, setVrcOSC] = useState<boolean>();
const [mocapPos, setMocapPos] = useState<'forehead' | 'face'>();
const [playspace, setPlayspace] = useState<'sitting' | 'standing'>();
const [state, dispatch] = useReducer<Reducer<OnboardingState, OnboardingAction>>(
reducer,
{
progress: 0,
alonePage: false,
}
);
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const { state: locatioState } = useLocation();
const [skeletonSettings, setSkeletonSettings] = useState<SkeletonSettingsResponseT>();
const [resetsSettings, setResetsSettings] = useState<ResetsSettingsResponseT>();
const [vrcOscSettings, setVrcOscSettings] = useState<VRCOSCSettingsResponseT>();
useLayoutEffect(() => {
const { alonePage = false }: { alonePage?: boolean } = (locatioState as any) || {};
if (alonePage !== state.alonePage)
dispatch({ type: 'alone-page', value: alonePage });
}, [locatioState, state]);
useEffect(() => {
sendRPCPacket(RpcMessage.SkeletonSettingsRequest, new SkeletonSettingsRequestT());
sendRPCPacket(RpcMessage.ResetsSettingsRequest, new ResetsSettingsRequestT());
sendRPCPacket(RpcMessage.VRCOSCSettingsRequest, new VRCOSCSettingsRequestT());
}, []);
useRPCPacket(
RpcMessage.SkeletonSettingsResponse,
(settings: SkeletonSettingsResponseT) => {
setSkeletonSettings(settings);
}
);
useRPCPacket(
RpcMessage.ResetsSettingsResponse,
(settings: ResetsSettingsResponseT) => {
setResetsSettings(settings);
}
);
useRPCPacket(
RpcMessage.VRCOSCSettingsResponse,
(settings: VRCOSCSettingsResponseT) => {
setVrcOscSettings(settings);
}
);
const { changeBoneValue } = useManualProportions({
type: 'linear',
});
const onboardingEnded = () => {
setConfig({ doneOnboarding: true });
if (!skeletonSettings || !resetsSettings || !vrcOscSettings) return;
const mocap = usage === 'mocap' || usage === 'vtubing';
const toggles = Object.assign(new SkeletonTogglesT(), skeletonSettings.toggles);
toggles.mocapMode = mocap && playspace === 'standing';
const skeletonReq = new ChangeSkeletonSettingsRequestT();
skeletonReq.toggles = toggles;
skeletonReq.ratios = skeletonSettings.ratios;
skeletonReq.filtering = skeletonSettings.filtering;
sendRPCPacket(RpcMessage.ChangeSkeletonSettingsRequest, skeletonReq);
const resetsReq = Object.assign(new ChangeResetsSettingsRequestT(), resetsSettings);
resetsReq.resetHmdPitch = mocapPos === 'forehead';
sendRPCPacket(RpcMessage.ChangeResetsSettingsRequest, resetsReq);
const osc = Object.assign(new VRCOSCSettingsResponseT(), vrcOscSettings);
osc.enabled = vrcOsc ?? false;
sendRPCPacket(RpcMessage.ChangeVRCOSCSettingsRequest, osc);
if (mocap) {
changeBoneValue({ bone: SkeletonBone.HAND_Z, type: 'bone', newValue: 0 });
}
};
const onboardingStarted = () => {
setSlimeSet(undefined);
setUsage(undefined);
setVrcOSC(undefined);
setMocapPos(undefined);
setPlayspace(undefined);
};
return {
state,
slimeSet,
usage,
vrcOsc,
mocapPos,
playspace,
setPlayspace,
applyProgress: (value: number) => {
useLayoutEffect(() => {
dispatch({ type: 'progress', value });
}, []);
},
setWifiCredentials: (ssid: string, password?: string) => {
dispatch({ type: 'wifi-creds', ssid, password: password ?? '' });
},
skipSetup: () => {
setConfig({ doneOnboarding: true });
},
setSlimeSet,
setUsage,
setVrcOSC,
setMocapPos,
onboardingEnded,
onboardingStarted,
};
}
export const OnboardingContextC = createContext<OnboardingContext>(undefined as any);
export function useOnboarding() {
const context = useContext<OnboardingContext>(OnboardingContextC);
if (!context) {
throw new Error('useOnboarding must be within a OnboardingContext Provider');
}
return context;
}
-14
View File
@@ -1,14 +0,0 @@
export function log(...msgs: any[]) {
console.log(...msgs);
if (window.electronAPI) window.electronAPI.log('info', ...msgs);
}
export function error(...msgs: any[]) {
console.error(...msgs);
if (window.electronAPI) window.electronAPI.log('error', ...msgs);
}
export function warn(...msgs: any[]) {
console.warn(...msgs);
if (window.electronAPI) window.electronAPI.log('warn', ...msgs);
}
-1
View File
@@ -1 +0,0 @@
resources/java-version/JavaVersion.class
-84
View File
@@ -1,84 +0,0 @@
appId: dev.slimevr.SlimeVR
productName: SlimeVR
# The package is named @slimevr/gui-electron; pin the executable name so
# electron-builder doesn't derive an invalid one from the scoped package name.
executableName: slimevr
# Global naming pattern
artifactName: "${productName}-${version}-${os}-${arch}.${ext}"
directories:
output: dist/artifacts/${os}
asar: true
asarUnpack:
# JavaVersion.jar is spawned as an external `java -jar` process, so it must
# live outside the asar. electron-vite references ?asset files under the
# main-process public dir (resources/) at runtime as ../../resources/...
- resources/java-version/*.jar
electronLanguages:
- en-US
files:
- out/**/*
- resources/**/*
- package.json
- node_modules/**
- "!node_modules/*/{README,readme,README.md,readme.md,CHANGELOG,CHANGELOG.md,changelog.md}"
- "!node_modules/*/{test,tests,__tests__,docs,doc,example,examples}"
- "!node_modules/*/.{git,github,vscode,editorconfig,eslintrc,prettierrc}"
- "!node_modules/**/*.{map,ts,tsx,d.ts}"
- "!**/.DS_Store"
linux:
category: Game
artifactName: "${productName}-${arch}.${ext}"
target:
- target: AppImage
- target: deb
- target: rpm
extraFiles:
- from: "../../server/desktop/build/libs/slimevr.jar"
to: "."
- from: "../../bindings-provider/build/linux-${arch}/slimevr-bindings-provider"
to: "."
- from: "../../bindings-provider/build/linux-${arch}/libopenvr_api.so"
to: "."
- from: "./resources/69-slimevr-devices.rules"
to: "."
icon: "./resources/icons"
deb:
depends: [openjdk-17-jre-headless, udev]
afterInstall: "./resources/scripts/postinstall.sh"
afterRemove: "./resources/scripts/postremove.sh"
rpm:
depends: [java-latest-openjdk, udev]
afterInstall: "./resources/scripts/postinstall.sh"
afterRemove: "./resources/scripts/postremove.sh"
win:
artifactName: "${productName}-${os}-${arch}.${ext}"
target: zip
icon: "./resources/icons/icon.ico"
extraFiles:
- from: "../../server/desktop/build/libs/slimevr.jar"
to: "."
- from: "../../server/core/resources"
to: "."
filter: ["**/*"]
- from: "../../bindings-provider/build/${os}-${arch}/Release/SlimeVR-Bindings-Provider.exe"
to: "."
- from: "../../bindings-provider/build/${os}-${arch}/openvr_api.dll"
to: "."
mac:
target: dmg
artifactName: "SlimeVR-mac.${ext}"
x64ArchFiles: "**/register-protocol-handler.node"
icon: "./resources/icons/icon.icns"
extraFiles:
- from: "../../server/desktop/build/libs/slimevr.jar"
to: "Resources/slimevr.jar"
-30
View File
@@ -1,30 +0,0 @@
import { defineConfig } from 'electron-vite';
import { resolve } from 'path';
export default defineConfig({
main: {
build: {
// @slimevr/gui-shared is a workspace source package (TS). electron-vite
// externalizes all package.json deps by default; exclude this one so it
// gets bundled in (its runtime IPC_CHANNELS compiled into the output
// instead of imported as raw .ts at runtime).
externalizeDeps: { exclude: ['@slimevr/gui-shared'] },
rollupOptions: {
input: resolve(__dirname, 'main/index.ts'),
external: ['pino', 'pino-pretty', 'pino-roll', 'commander', 'open'],
},
},
},
preload: {
build: {
externalizeDeps: { exclude: ['@slimevr/gui-shared'] },
rollupOptions: {
input: resolve(__dirname, 'preload/index.ts'),
output: {
format: 'cjs', // Force CJS for the preload
entryFileNames: 'index.js', // Change back to .js
},
},
},
},
});
-1
View File
@@ -1 +0,0 @@
/// <reference types="electron-vite/node" />
-22
View File
@@ -1,22 +0,0 @@
import { Option, program } from 'commander';
program
.option('-p, --path <path>', 'set launch path')
.option('-s, --steam', 'steam mode')
.option('-i, --install', 'run the driver installer')
.option(
'--skip-server-if-running',
'gui will not launch the server if it is already running'
)
.allowUnknownOption()
// Allow passing arguments to Electron.
.allowExcessArguments();
if (process.platform === 'linux') {
const noUdevOption = new Option('--no-udev', 'disable udev warning');
noUdevOption.negate = false;
program.addOption(noUdevOption);
}
program.parse(process.argv);
export const options = program.opts();
-531
View File
@@ -1,531 +0,0 @@
import {
app,
BrowserWindow,
dialog,
Menu,
nativeImage,
net,
protocol,
screen,
shell,
Tray,
} from 'electron';
import { GHGet, GHReturn, IPC_CHANNELS } from '@slimevr/gui-shared';
import path, { dirname, join } from 'path';
import open from 'open';
import trayIcon from '../resources/icons/icon.png?asset';
import appleTrayIcon from '../resources/icons/Square30x30Logo.png?asset';
import { readFile, stat } from 'fs/promises';
import { pathToFileURL } from 'node:url';
import { getPlatform, handleIpc, isPortAvailable } from './utils';
import {
findServerJar,
findSystemJRE,
getExeFolder,
getGuiDataFolder,
getLogsFolder,
getServerDataFolder,
getWindowStateFile,
} from './paths';
import { initStores } from './store';
import { closeLogger, logger } from './logger';
import { spawn } from 'node:child_process';
import { discordPresence } from './presence';
import { options } from './cli';
import { ServerStatusEvent } from '@slimevr/gui-shared';
import { mkdir, writeFile } from 'node:fs/promises';
import { MenuItem } from 'electron/main';
type Stores = Awaited<ReturnType<typeof initStores>>;
let stores: Stores;
// Fixes colors looking washed on linux
// Might affect hdr
if (process.platform === 'linux') {
app.commandLine.appendSwitch('disable-features', 'WaylandWpColorManagerV1');
app.commandLine.appendSwitch('force-color-profile', 'srgb');
}
app.setPath('userData', getGuiDataFolder());
app.setPath('sessionData', join(getGuiDataFolder(), 'electron'));
protocol.registerSchemesAsPrivileged([
{
scheme: 'app',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
stream: true,
},
},
]);
let mainWindow: BrowserWindow | null = null;
handleIpc(
IPC_CHANNELS.GH_FETCH,
async <T extends GHGet>(_e: unknown, options: T): Promise<GHReturn[T['type']]> => {
switch (options.type) {
case 'fw-releases': {
return fetch(
'https://api.github.com/repos/SlimeVR/SlimeVR-Tracker-ESP/releases'
).then((res) => res.json()) as Promise<GHReturn[T['type']]>;
}
case 'asset': {
if (
!options.url.startsWith(
'https://github.com/SlimeVR/SlimeVR-Tracker-ESP/releases/download'
)
)
return null;
return fetch(options.url).then((res) => res.json()) as Promise<
GHReturn[T['type']]
>;
}
default:
throw 'unhandled type';
}
}
);
handleIpc(IPC_CHANNELS.OS_STATS, async () => {
return {
type: getPlatform(),
};
});
handleIpc(IPC_CHANNELS.I18N_OVERRIDE, async () => {
const overridefile = join(getServerDataFolder(), 'override.ftl');
const exists = await stat(overridefile)
.then(() => true)
.catch(() => false);
if (!exists) return false;
return readFile(overridefile, { encoding: 'utf-8' });
});
handleIpc(IPC_CHANNELS.LOG, (e, type, ...args) => {
let payload: Record<string, unknown> = {};
const messageParts: unknown[] = [];
args.forEach((arg) => {
if (arg instanceof Error) {
payload.err = arg;
} else if (typeof arg === 'object' && arg !== null) {
payload = { ...payload, ...arg };
} else {
messageParts.push(arg);
}
});
const msg = messageParts.join(' ');
switch (type) {
case 'error':
logger.error(payload, msg);
break;
case 'warn':
logger.warn(payload, msg);
break;
default:
logger.info(payload, msg);
}
});
handleIpc(IPC_CHANNELS.OPEN_URL, (e, url) => {
const allowedUrls = [
/^steam:\/\//,
/^ms-settings:network$/,
/^https:\/\/(?:.+\.)?slimevr\.dev(?:\/.+)?$/,
/^https:\/\/github\.com\/SlimeVR(?:\/.+)?$/,
/^https:\/\/discord\.gg\/slimevr$/,
];
if (allowedUrls.find((a) => url.match(a))) open(url);
else logger.error({ url }, 'attempted to open non-whitelisted URL');
});
handleIpc(IPC_CHANNELS.STORAGE, async (e, { type, method, key, value }) => {
const store = stores[type];
if (!store) throw new Error(`Storage type ${type} not found`);
switch (method) {
case 'get':
return store.get(key!);
case 'set':
return store.set(key!, value);
case 'delete':
return store.delete(key!);
case 'save':
return store.save();
}
});
handleIpc(IPC_CHANNELS.DISCORD_PRESENCE, async (e, options) => {
if (options.enable) {
if (!discordPresence.state.ready) await discordPresence.connect();
discordPresence.updateActivity(options.activity, options.iconText);
} else if (discordPresence.state.ready) {
discordPresence.destroy();
}
});
handleIpc(IPC_CHANNELS.OPEN_FILE, (e, folder) => {
const requestedPath = path.resolve(folder);
const isAllowed = [getServerDataFolder(), getGuiDataFolder(), getLogsFolder()].some(
(parent) => {
const absoluteParent = path.resolve(parent);
const relative = path.relative(absoluteParent, requestedPath);
return !relative.includes('..') && !path.isAbsolute(relative);
}
);
if (isAllowed) {
shell.openPath(requestedPath);
} else {
logger.error({ path: requestedPath }, 'Blocked unauthorized path');
}
});
handleIpc(IPC_CHANNELS.GET_FOLDER, (e, folder) => {
switch (folder) {
case 'config':
return getGuiDataFolder();
case 'logs':
return getLogsFolder();
case 'exe':
return getExeFolder();
}
});
handleIpc(IPC_CHANNELS.IS_STEAM, () => {
return options.steam;
});
const defaultWindowState: {
width: number;
height: number;
x?: number;
y?: number;
} = {
width: 1289.0,
height: 709.0,
x: undefined,
y: undefined,
};
const windowState = await readFile(getWindowStateFile(), {
encoding: 'utf-8',
})
.then((data) => JSON.parse(data))
.catch(() => {
logger.error('Failed to load window state, using defaults');
return defaultWindowState;
});
const MIN_WIDTH = 393;
const MIN_HEIGHT = 667;
function validateWindowState(state: typeof defaultWindowState) {
if (state.x === undefined || state.y === undefined) {
return state;
}
const displays = screen.getAllDisplays();
const isVisible = displays.some((display) => {
return (
state.x! >= display.bounds.x &&
state.y! >= display.bounds.y &&
state.x! + state.width <= display.bounds.x + display.bounds.width &&
state.y! + state.height <= display.bounds.y + display.bounds.height
);
});
const minWidth = MIN_WIDTH;
const minHeight = MIN_HEIGHT;
if (!isVisible || state.width < minWidth || state.height < minHeight) {
return defaultWindowState;
}
return state;
}
const saveWindowState = async () => {
await mkdir(dirname(getWindowStateFile()), { recursive: true });
await writeFile(getWindowStateFile(), JSON.stringify(windowState), {
encoding: 'utf-8',
});
};
function createWindow() {
const validatedState = validateWindowState(windowState);
mainWindow = new BrowserWindow({
width: validatedState.width,
height: validatedState.height,
x: validatedState.x,
y: validatedState.y,
minHeight: MIN_HEIGHT,
minWidth: MIN_WIDTH,
movable: true,
frame: false,
roundedCorners: true,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
nodeIntegration: false,
contextIsolation: true,
devTools: true,
},
});
if (process.env.ELECTRON_RENDERER_URL) {
mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL);
mainWindow.webContents.openDevTools();
} else {
mainWindow.loadURL('app://./index.html');
}
mainWindow.on('closed', () => {
mainWindow = null;
});
handleIpc('window-actions', (e, action) => {
if (mainWindow === null) return;
switch (action) {
case 'close':
mainWindow.close();
break;
case 'hide':
mainWindow.hide();
break;
case 'minimize':
mainWindow.minimize();
break;
case 'toggle-maximize':
if (mainWindow.isMaximized()) mainWindow.unmaximize();
else mainWindow.maximize();
break;
}
});
handleIpc('open-dialog', (e, options) => dialog.showOpenDialog(options));
handleIpc('save-dialog', (e, options) => dialog.showSaveDialog(options));
const icon = nativeImage.createFromPath(
getPlatform() === 'macos' ? appleTrayIcon : trayIcon
);
const tray = new Tray(icon);
tray.setToolTip('SlimeVR');
tray.on('click', () => {
mainWindow?.show();
});
const contextMenu = Menu.buildFromTemplate([
{
label: 'Show',
click: () => {
mainWindow?.show();
},
},
{
label: 'Hide',
click: () => {
mainWindow?.hide();
},
},
{ role: 'quit' },
]);
tray.setContextMenu(contextMenu);
const updateWindowState = () => {
if (!mainWindow) return;
windowState.minimized = mainWindow.isMinimized();
if (!mainWindow.isMinimized() && !mainWindow.isMaximized()) {
const bounds = mainWindow.getBounds();
windowState.width = bounds.width;
windowState.height = bounds.height;
windowState.x = bounds.x;
windowState.y = bounds.y;
}
};
mainWindow.on('move', updateWindowState);
mainWindow.on('resize', updateWindowState);
mainWindow.on('minimize', updateWindowState);
mainWindow.on('maximize', updateWindowState);
mainWindow.webContents.on('context-menu', (event, params) => {
const menu = new Menu();
menu.append(
new MenuItem({
label: 'Inspect Element',
click: () => {
mainWindow?.webContents.inspectElement(params.x, params.y);
},
})
);
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: 'Copy', role: 'copy' }));
menu.append(new MenuItem({ label: 'Paste', role: 'paste' }));
if (mainWindow) menu.popup({ window: mainWindow });
});
}
const checkEnvironmentVariables = () => {
const disallowedVars = ['_JAVA_OPTIONS', 'JAVA_TOOL_OPTIONS'];
const set = disallowedVars.filter((env) => !!process.env[env]);
if (set.length > 0) {
dialog.showErrorBox(
'SlimeVR',
`You have environment variables ${set.join(', ')} set, which may cause the SlimeVR Server to fail to launch properly.`
);
app.quit();
}
};
const isServerRunning = async () => !(await isPortAvailable(21110));
const spawnServer = async () => {
if (options.skipServerIfRunning && (await isServerRunning())) {
logger.info(
{ skipServerIfRunning: options.skipServerIfRunning },
'Server is already running, skipping server start'
);
return;
}
const serverJar = findServerJar();
if (!serverJar) {
logger.info('server jar not found, skipping');
return;
}
const sharedDir = dirname(serverJar);
const javaBin = await findSystemJRE(sharedDir);
if (!javaBin) {
dialog.showErrorBox(
'SlimeVR',
'Unable to find a compatible Java version, please download Java 17 or higher'
);
app.quit();
return;
}
logger.info({ javaBin, serverJar }, 'Found Java and server jar');
const platform = getPlatform();
const serverArgs = ['-Xmx128M', '-jar', serverJar];
if (options.steam) serverArgs.push('--steam');
if (options.install) serverArgs.push('--install');
if (options.noUdev) serverArgs.push('--no-udev');
serverArgs.push('run');
const serverProcess = spawn(javaBin, serverArgs, {
cwd: sharedDir,
shell: false,
env:
platform === 'windows'
? {
...process.env,
APPDATA: app.getPath('appData'),
LOCALAPPDATA: process.env['USERPROFILE']
? path.join(process.env['USERPROFILE'], 'AppData', 'Local')
: undefined,
}
: undefined,
});
const sendToWindow = (event: ServerStatusEvent) => {
if (mainWindow && !mainWindow.webContents.isDestroyed()) {
mainWindow.webContents.send(IPC_CHANNELS.SERVER_STATUS, event);
}
};
serverProcess.stdout?.on('data', (message) => {
sendToWindow({ message: message.toString(), type: 'stdout' });
});
serverProcess.stderr?.on('data', (message) => {
sendToWindow({ message: message.toString(), type: 'stderr' });
});
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));
return {
process: serverProcess,
close: () => serverProcess.kill(),
waitForExit: () => exited,
};
};
const createFolders = async () => {
await mkdir(getServerDataFolder(), { recursive: true });
await mkdir(getGuiDataFolder(), { recursive: true });
};
let isQuitting = false;
app.whenReady().then(async () => {
protocol.handle('app', (request) => {
const { pathname } = new URL(request.url);
const filePath = path.normalize(join(__dirname, '../renderer', pathname));
return net.fetch(pathToFileURL(filePath).toString(), { headers: request.headers });
});
try {
await createFolders();
} catch (err) {
logger.error(err, 'Failed to initialize stores');
dialog.showErrorBox(
'SlimeVR',
'Failed to initialize application storage. Please make sure the application has write permissions to its data folder.'
);
app.quit();
return;
}
stores = await initStores();
checkEnvironmentVariables();
const server = await spawnServer();
createWindow();
logger.info('SlimeVR started!');
app.on('window-all-closed', () => {
app.quit();
});
app.on('before-quit', async (event) => {
if (isQuitting) return;
isQuitting = true;
event.preventDefault();
logger.info('App quitting, saving...');
server?.close();
await server?.waitForExit();
await stores.settings.save();
await stores.cache.save();
discordPresence.destroy();
await saveWindowState();
await closeLogger();
app.exit(0);
});
});
-34
View File
@@ -1,34 +0,0 @@
import pino from 'pino';
import { getLogsFolder } from './paths';
import { join } from 'node:path';
const transport = pino.transport({
targets: [
{
target: 'pino-roll',
options: {
file: join(getLogsFolder(), 'slimevr-gui.log'),
frequency: 'daily',
size: '10m',
mkdir: true,
limit: { count: 7 },
},
level: 'info',
},
{
target: 'pino-pretty',
options: { colorize: true },
level: 'debug',
},
],
});
export const logger = pino(transport);
export const closeLogger = () =>
new Promise<void>((resolve) => {
logger.flush(() => {
transport.once('close', resolve);
transport.end();
});
});
-132
View File
@@ -1,132 +0,0 @@
import { app } from 'electron';
import path, { join } from 'node:path';
import { getPlatform } from './utils';
import { glob } from 'glob';
import { spawn } from 'node:child_process';
import javaVersionJar from '../resources/java-version/JavaVersion.jar?asset&asarUnpack';
import { existsSync } from 'node:fs';
import { options } from './cli';
const javaBin = getPlatform() === 'windows' ? 'java.exe' : 'java';
export const CONFIG_IDENTIFIER = 'dev.slimevr.SlimeVR';
export const getGuiDataFolder = () => {
const platform = getPlatform();
switch (platform) {
case 'linux':
if (process.env['XDG_DATA_HOME'])
return join(process.env['XDG_DATA_HOME'], CONFIG_IDENTIFIER);
return join(app.getPath('home'), '.local/share', CONFIG_IDENTIFIER);
case 'windows':
return join(app.getPath('appData'), CONFIG_IDENTIFIER);
case 'macos':
return join(
app.getPath('home'),
'Library/Application Support',
CONFIG_IDENTIFIER
);
case 'unknown':
throw 'error';
}
};
export const getServerDataFolder = () => {
const platform = getPlatform();
switch (platform) {
case 'linux':
case 'windows':
case 'macos':
return join(app.getPath('appData'), CONFIG_IDENTIFIER);
case 'unknown':
throw 'error';
}
};
export const getLogsFolder = () => {
return join(getGuiDataFolder(), 'logs');
};
export const getExeFolder = () => {
return path.dirname(app.getPath('exe'));
};
export const getWindowStateFile = () =>
join(getServerDataFolder(), '.window-state.json');
const localJavaBin = (sharedDir: string) => {
const platform = getPlatform();
switch (platform) {
case 'macos':
return join(sharedDir, '../../../../jre/Contents/Home/bin', javaBin);
default:
return join(sharedDir, 'jre/bin', javaBin);
}
};
const javaHomeBin = () => {
const javaHome = process.env['JAVA_HOME'];
if (!javaHome) return null;
const javaHomeJre = join(javaHome, 'bin', javaBin);
return javaHomeJre;
};
export const findSystemJRE = async (sharedDir: string) => {
const paths = [
localJavaBin(sharedDir),
javaHomeBin(),
...(await glob('/usr/lib/jvm/*/bin/' + javaBin)),
...(await glob('/Library/Java/JavaVirtualMachines/*/Contents/Home/bin/' + javaBin)),
];
for (const path of paths) {
if (!path) continue;
const version = await new Promise<number | null>((resolve) => {
const process = spawn(path, ['-jar', javaVersionJar], {});
let version: number | null = null;
process.stdout?.once('data', (data) => {
try {
version = parseFloat(data.toString());
} catch {
version = null;
}
});
process.on('error', () => {
resolve(null);
});
process.on('exit', () => {
resolve(version);
});
});
if (version && version >= 17) return path;
}
return null;
};
export const findServerJar = () => {
const paths = [
options.path ? path.resolve(options.path) : undefined,
app.isPackaged ? path.resolve(process.resourcesPath) : undefined,
// AppImage passes the fakeroot in `APPDIR` env var.
process.env['APPDIR']
? path.resolve(join(process.env['APPDIR'], 'usr/share/slimevr/'))
: undefined,
path.dirname(app.getPath('exe')),
// For flatpack container
path.resolve('/app/share/slimevr/'),
path.resolve('/usr/share/slimevr/'),
// For macos on steam
path.resolve(`${app.getPath('exe')}/../../../../`),
];
return paths
.filter((p) => !!p)
.map((p) => join(p!, 'slimevr.jar'))
.find((p) => existsSync(p));
};
-52
View File
@@ -1,52 +0,0 @@
import { Client } from '@xhayper/discord-rpc';
import { logger } from './logger';
export const richPresence = () => {
const initialState = () => ({ ready: false, start: Date.now() });
const state = initialState();
const client = new Client({
clientId: '1237970689009647639',
transport: { type: 'ipc' },
});
client.on('ready', () => {
state.ready = true;
});
client.on('disconnected', () => {
state.ready = false;
});
return {
state,
connect: async () => {
try {
logger.info('Logging into Discord RPC');
await client.login();
} catch (e) {
logger.error(e, 'Unable to connect to Discord RPC');
}
},
updateActivity: (content: string, iconText: string | undefined) => {
if (!state.ready) return;
client.user
?.setActivity({
state: content,
largeImageKey: 'icon',
largeImageText: iconText,
startTimestamp: state.start,
})
.catch((e) => {
logger.error(e, 'Failed to update Discord RPC activity');
});
},
destroy: () => {
logger.info('Destroying Discord RPC');
client.destroy();
Object.assign(state, initialState());
},
};
};
export const discordPresence = richPresence();
-86
View File
@@ -1,86 +0,0 @@
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> = {};
private saveTimeout: NodeJS.Timeout | null = null;
private filePath: string;
private debounceMs: number;
private constructor(filePath: string, debounceMs: number = 2000) {
this.filePath = filePath;
this.debounceMs = debounceMs;
}
static async create(
filePath: string,
debounceMs: number = 2000
): Promise<CustomStore> {
const store = new CustomStore(filePath, debounceMs);
await store.load();
return store;
}
private async load(): Promise<void> {
try {
await access(this.filePath);
const raw = await readFile(this.filePath, 'utf-8');
this.data = JSON.parse(raw);
} catch {
this.data = {};
logger.warn(
`No existing store found at ${this.filePath}, starting with empty store.`
);
}
}
set(key: string, value: unknown) {
this.data[key] = value;
this.triggerAutoSave();
}
get<T>(key: string): T | undefined {
return this.data[key] as T;
}
delete(key: string): boolean {
if (key in this.data) {
delete this.data[key];
this.triggerAutoSave();
return true;
}
return false;
}
private triggerAutoSave() {
if (this.saveTimeout) clearTimeout(this.saveTimeout);
this.saveTimeout = setTimeout(() => {
this.save();
}, this.debounceMs);
}
async save(): Promise<boolean> {
try {
if (this.saveTimeout) clearTimeout(this.saveTimeout);
await mkdir(dirname(this.filePath), { recursive: true });
await writeFile(this.filePath, JSON.stringify(this.data, null, 2), 'utf-8');
return true;
} catch (err) {
logger.error(err, 'Save failed', this.filePath);
return false;
}
}
}
export async function initStores() {
return {
settings: await CustomStore.create(
join(getGuiDataFolder(), 'gui-settings.dat'),
1000
),
cache: await CustomStore.create(join(getGuiDataFolder(), 'gui-cache.dat'), 100),
};
}
Loaded 100 of 1013 files, more files were not shown because too many files have changed in this diff. Show more