mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-23 10:31:24 -08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1c2133127 | ||
|
|
4a39726fbb | ||
|
|
49dc68886d | ||
|
|
de8757c09f | ||
|
|
b57390e92b | ||
|
|
6cbfb3b34d | ||
|
|
8358ca14a8 | ||
|
|
67fbf0faca | ||
|
|
ce762ba242 | ||
|
|
70eda4f70c | ||
|
|
cdc0e21913 | ||
|
|
6575a11da7 | ||
|
|
9edc747344 | ||
|
|
71895dec63 | ||
|
|
11669d40b8 | ||
|
|
0bbe35b5d1 | ||
|
|
0530cebf92 | ||
|
|
d0b361a821 | ||
|
|
22999975ad | ||
|
|
98ccc7c667 | ||
|
|
0723625272 | ||
|
|
4686e915b7 | ||
|
|
d1b1195213 | ||
|
|
f202f96246 | ||
|
|
aa0d2e86a5 | ||
|
|
dc2b47a7dc | ||
|
|
47638cc9d5 | ||
|
|
0757935d60 | ||
|
|
066a73c0c2 | ||
|
|
dd198d2205 | ||
|
|
d7bdeaa48a | ||
|
|
5681c351c5 | ||
|
|
28bedc12f1 | ||
|
|
a69c10d733 | ||
|
|
c0cf2af9be | ||
|
|
71391e7f5a | ||
|
|
33d84f19f1 | ||
|
|
2996858770 | ||
|
|
1e92eafdad | ||
|
|
150c0640cf | ||
|
|
25a066da30 | ||
|
|
8c78f1c371 | ||
|
|
2cf6c0b97c | ||
|
|
710088e513 | ||
|
|
91011120f0 | ||
|
|
837316ba8d | ||
|
|
d9338dc863 | ||
|
|
1763fe9ceb | ||
|
|
f6d662ab71 | ||
|
|
791ae07fe2 | ||
|
|
fe3bee2417 | ||
|
|
431774be16 | ||
|
|
2f5b2eaa94 | ||
|
|
0755413b87 | ||
|
|
cf46ca9f9f | ||
|
|
ba5660be33 | ||
|
|
40bb3d1cbe | ||
|
|
e85bb26537 | ||
|
|
10df44ee2b | ||
|
|
2559cdf9bc | ||
|
|
fe2a7bf442 | ||
|
|
1d554334cc | ||
|
|
a75a1ad195 | ||
|
|
a4aa76aa82 | ||
|
|
c43b44ccc8 | ||
|
|
5f3b1fd0a5 | ||
|
|
facce888a0 | ||
|
|
0c0aac0415 | ||
|
|
1ebd8a4f02 | ||
|
|
95b64883f6 | ||
|
|
861a9fbf12 | ||
|
|
d6e6926d44 | ||
|
|
16d2e0b46b | ||
|
|
83f48a7eba | ||
|
|
24da10715f | ||
|
|
559c076b26 | ||
|
|
67ae02a1b0 | ||
|
|
e1802987ca | ||
|
|
3f7580ac1a | ||
|
|
11783de08b | ||
|
|
256574dc2c | ||
|
|
5a4ba1f73b | ||
|
|
feb3eae3d3 | ||
|
|
bdde772c5c | ||
|
|
c208b7cda2 | ||
|
|
c10d536a6c | ||
|
|
cef72ee9ae | ||
|
|
6dbe872958 | ||
|
|
f390347b56 | ||
|
|
22cb14bb21 | ||
|
|
cc387a6c02 | ||
|
|
412e182079 | ||
|
|
7b80cb926d | ||
|
|
22d1126c66 | ||
|
|
3574130207 | ||
|
|
c5eda4b818 | ||
|
|
cc68e0e750 | ||
|
|
36f2398190 | ||
|
|
ddae53ab42 | ||
|
|
57c39c78b0 | ||
|
|
c71bb3e9c4 | ||
|
|
2f6cb0ab0d | ||
|
|
47a706792b | ||
|
|
7645ff6752 | ||
|
|
a86a6fb2f0 | ||
|
|
945796dade | ||
|
|
f59e5aa869 | ||
|
|
96998a644f | ||
|
|
f2b540d0bd | ||
|
|
d8041833f1 | ||
|
|
b3e61a5482 | ||
|
|
f3de32a7cb | ||
|
|
abc5c7b38c | ||
|
|
0907fe50db | ||
|
|
4b7af0bbed | ||
|
|
6d625d1d25 | ||
|
|
9d3afda739 | ||
|
|
d492061c0a | ||
|
|
e657d97480 | ||
|
|
4446b8d689 | ||
|
|
6c7d6add67 | ||
|
|
3ae788e8af | ||
|
|
7ddb3e74e6 | ||
|
|
6fe10bf71d | ||
|
|
3749b77c75 | ||
|
|
ae4402b5b5 | ||
|
|
170c688db8 | ||
|
|
be34dc981c | ||
|
|
6087178ecf | ||
|
|
04a26ec539 | ||
|
|
3095ce4867 | ||
|
|
b336897bfe | ||
|
|
14e77b6af3 | ||
|
|
cdd47d8b74 | ||
|
|
448f0754ad | ||
|
|
834111c769 | ||
|
|
a21e769d97 | ||
|
|
791a358893 | ||
|
|
428f2ba774 | ||
|
|
951b96d548 | ||
|
|
09724f1fa3 | ||
|
|
3336f6dff1 | ||
|
|
943d51dbdc | ||
|
|
fa3ebf4eb1 | ||
|
|
aa505d041b | ||
|
|
b7cd179cc6 | ||
|
|
1185825b3e | ||
|
|
984c98fd5b | ||
|
|
94e34ca3af | ||
|
|
1775d54bf1 | ||
|
|
4113a091c1 | ||
|
|
acde3a0e34 | ||
|
|
db231f368d | ||
|
|
18c5d0dad6 | ||
|
|
fa46f7d5fb | ||
|
|
7d04273b0e | ||
|
|
a097c26261 | ||
|
|
b17624d87a | ||
|
|
a43ba532e1 | ||
|
|
2d6b250539 | ||
|
|
4bf1e706d3 | ||
|
|
e2fa7c8963 | ||
|
|
6db666840b | ||
|
|
918f28dfc8 | ||
|
|
ac07e65b27 | ||
|
|
902ab1fee1 | ||
|
|
ada2ee3c81 | ||
|
|
c5d8968d58 | ||
|
|
9c7ca73dbc | ||
|
|
6266802a27 | ||
|
|
d1b96a5c6b | ||
|
|
5aaade2915 | ||
|
|
bf3168af2b | ||
|
|
4e69262240 | ||
|
|
ae5a8f4e97 | ||
|
|
a171bc2783 | ||
|
|
242920316b | ||
|
|
2fc64b3e8b | ||
|
|
02ca403e24 | ||
|
|
17e87178fc | ||
|
|
dd6c1e7567 | ||
|
|
0ab80528fe | ||
|
|
e07ef046a6 | ||
|
|
71b74914a3 | ||
|
|
f65f41ad17 | ||
|
|
df4569fe17 | ||
|
|
38743dc8b8 | ||
|
|
9d1e7764e6 | ||
|
|
fa1d2012e1 | ||
|
|
8168e1366a | ||
|
|
ea92fb4c01 | ||
|
|
fc476a1683 | ||
|
|
5946ca1b7a | ||
|
|
6c4fdedcd1 | ||
|
|
1001b7f887 | ||
|
|
86dbdbddf8 | ||
|
|
d46fb013ac | ||
|
|
8ffd00eb47 | ||
|
|
853155600a | ||
|
|
ad9bc911b6 | ||
|
|
2235b8178b | ||
|
|
e37a37bcf9 | ||
|
|
af4665e7c9 | ||
|
|
a42ed79003 | ||
|
|
334be5f7cc | ||
|
|
4c1e4691be | ||
|
|
4fd4997e60 | ||
|
|
6eb63ce9f8 | ||
|
|
01b7b8dbba | ||
|
|
e060bc7cc5 | ||
|
|
d691619b98 |
No files matched your search
+14
-12
@@ -84,23 +84,25 @@ jobs:
|
||||
- name: GUI Lint
|
||||
run: pnpm i && cd gui && pnpm run lint
|
||||
|
||||
java-checks:
|
||||
name: Java Checks
|
||||
server-checks:
|
||||
name: Server Checks
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v6
|
||||
- name: Set up JDK 24
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
java-version: '24'
|
||||
distribution: 'adopt'
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
- name: Java Spotless Check
|
||||
- name: Server Spotless Check
|
||||
run: ./gradlew spotlessCheck --build-cache
|
||||
- name: Server Detekt Lint
|
||||
run: ./gradlew :server:detekt --build-cache
|
||||
|
||||
|
||||
build-server-jar:
|
||||
@@ -113,10 +115,10 @@ jobs:
|
||||
submodules: recursive
|
||||
- name: Get tags
|
||||
run: git fetch --tags origin --recurse-submodules=no --force
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v6
|
||||
- name: Set up JDK 24
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
java-version: '24'
|
||||
distribution: 'adopt'
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
@@ -260,10 +262,10 @@ jobs:
|
||||
submodules: recursive
|
||||
- name: Get tags
|
||||
run: git fetch --tags origin --recurse-submodules=no --force
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v6
|
||||
- name: Set up JDK 24
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
java-version: '24'
|
||||
distribution: 'adopt'
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
name: Test Crowdin Sync (Dry Run)
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: 'Perform a dry run (logs changes without modifying repository)'
|
||||
type: boolean
|
||||
default: true
|
||||
localization_branch:
|
||||
description: 'Branch to target for translations'
|
||||
type: string
|
||||
default: 'l10n_main'
|
||||
|
||||
jobs:
|
||||
test-crowdin:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Test Crowdin Synchronization
|
||||
uses: crowdin/github-action@v2
|
||||
with:
|
||||
upload_sources: true
|
||||
upload_translations: false
|
||||
download_translations: true
|
||||
localization_branch_name: ${{ inputs.localization_branch }}
|
||||
dry_run: ${{ inputs.dry_run }}
|
||||
create_pull_request: false
|
||||
env:
|
||||
CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }}
|
||||
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
|
||||
CROWDIN_API_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
|
||||
@@ -3,7 +3,6 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- pontoon
|
||||
- l10n_main
|
||||
jobs:
|
||||
pull_request:
|
||||
if: ${{ github.repository == 'SlimeVR/SlimeVR-Server' }}
|
||||
@@ -18,5 +17,5 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.PONTOON_BOT_KEY }}
|
||||
run: |
|
||||
gh_pr_up() { gh pr create "$@" --draft --base main || gh pr edit "$@"; }
|
||||
gh_pr_up --title "New translations" --body "Please don't squash me 🥺"
|
||||
gh_pr_up() { gh pr create "$@" --label "Area: Translation" --base main || gh pr edit "$@"; }
|
||||
gh_pr_up --title "New Pontoon translations" --body "Please don't squash me 🥺"
|
||||
@@ -1,44 +1,14 @@
|
||||
# This workflow will rebase `l10n_main` and `pontoon` with `main` changes, it's for making the
|
||||
# translation bots not try making commits to main
|
||||
# This workflow will rebase `pontoon` with `main` changes, it's for making the
|
||||
# Pontoon bot not try making commits to main
|
||||
|
||||
name: Rebase translation branches to main
|
||||
name: Rebase pontoon branch to main
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
rebase-l10n:
|
||||
if: ${{ github.repository == 'SlimeVR/SlimeVR-Server' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: l10n_main
|
||||
submodules: recursive
|
||||
# Get all the git history for rebasing
|
||||
fetch-depth: 0
|
||||
- name: Rebase
|
||||
run: |
|
||||
git config --local user.name "slimevr-bot"
|
||||
git config --local user.email '[email protected]'
|
||||
git fetch origin main
|
||||
git rebase origin/main
|
||||
git submodule update
|
||||
- name: Push rebase
|
||||
uses: github-actions-x/[email protected]
|
||||
with:
|
||||
github-token: ${{ secrets.PONTOON_BOT_KEY }}
|
||||
push-branch: "l10n_main"
|
||||
commit-message: "update"
|
||||
force-push: "true"
|
||||
name: "slimevr-bot"
|
||||
email: "[email protected]"
|
||||
|
||||
rebase-pontoon:
|
||||
rebase:
|
||||
if: ${{ github.repository == 'SlimeVR/SlimeVR-Server' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
|
||||
+5
-9
@@ -4,8 +4,10 @@
|
||||
# Syncthing ignore file
|
||||
.stignore
|
||||
|
||||
# Ignore .idea
|
||||
.idea
|
||||
# Ignore .idea, except shared project inspection profiles
|
||||
.idea/*
|
||||
!.idea/inspectionProfiles/
|
||||
!.idea/inspectionProfiles/*.xml
|
||||
|
||||
# Ignore .fleet
|
||||
.fleet
|
||||
@@ -25,9 +27,7 @@
|
||||
.settings
|
||||
|
||||
# Node Stuff
|
||||
node_modules/
|
||||
dist/
|
||||
stats.html
|
||||
/node_modules
|
||||
.husky
|
||||
|
||||
# kotlin stuff
|
||||
@@ -35,10 +35,6 @@ stats.html
|
||||
|
||||
# ignore gradle build folder
|
||||
build/
|
||||
server/desktop/config/
|
||||
|
||||
# created by clangd for index cache
|
||||
.cache/
|
||||
|
||||
# direnv has been claimed for Nix usage
|
||||
.direnv/
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<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
@@ -0,0 +1,7 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="PROJECT_PROFILE" value="Project Default" />
|
||||
<option name="USE_PROJECT_PROFILE" value="true" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
@@ -0,0 +1,64 @@
|
||||
# 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.
|
||||
+7
-6
@@ -1,7 +1,5 @@
|
||||
# Contributing to SlimeVR
|
||||
|
||||
Please follow general contribution guidelines: [CONTRIBUTING.md](https://github.com/SlimeVR/.github/blob/main/profile/CONTRIBUTING.md).
|
||||
|
||||
This document describes essential knowledge required to contribute to the SlimeVR Server.
|
||||
|
||||
### Prerequisites
|
||||
@@ -24,21 +22,24 @@ 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 run` in your IDE's terminal.
|
||||
- To compile the code, run `./gradlew shadowJar`. The result will
|
||||
be at `server/build/libs/slimevr.jar` (you can ignore `server.jar`).
|
||||
be at `server/desktop/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)
|
||||
|
||||
- Activate corepack (included with Node.JS) via `corepack enable` (might require administrator permissions)
|
||||
- Activate corepack (included with Node.js) via `corepack enable`
|
||||
(might require launching Git Bash as administrator on Windows)
|
||||
- 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`. The result
|
||||
will be at `dist/artifacts/` content will change depending of the platform.
|
||||
- Finally, to compile for production, run `pnpm package:build`.
|
||||
The result will be in `gui/dist/artifacts/`. Content will change depending on the platform.
|
||||
|
||||
## Code style
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ 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.
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if ((Get-Command "clang-format" -ErrorAction SilentlyContinue) -eq $null) {
|
||||
$errorObj = New-Object System.IO.FileNotFoundException("clang-format is not installed, please install clang-format via your package manager (e.g. winget/chocolatey/scoop) and re-run the script")
|
||||
throw $errorObj
|
||||
}
|
||||
|
||||
$SourceFiles = Get-ChildItem -Path '.\src\' -Recurse -Include "*.cpp","*.hpp"
|
||||
foreach ($file in $SourceFiles) {
|
||||
Write-Output "Formatting $(Resolve-Path -Relative $file.FullName)"
|
||||
clang-format -i "$($file.FullName)"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
#!/bin/bash
|
||||
if ! command -v clang-format >/dev/null 2>&1; then
|
||||
echo "clang-format is not installed, please install clang-format via your package manager (e.g. pacman/apt/dnf/winget) and re-run the script" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
find src/ \( \
|
||||
-iname '*.cpp' \
|
||||
-or -iname '*.hpp' \
|
||||
\) \
|
||||
-exec echo Formatting {} \; \
|
||||
-exec clang-format -i {} \;
|
||||
@@ -102,34 +102,19 @@ static void signal_handler(int signal) {
|
||||
|
||||
int main() {
|
||||
auto &logger = Logger::get();
|
||||
|
||||
// Steam and SteamVR respectively set these environment variables on applications that
|
||||
// they spawn, which the SteamVR client library (vrclient) will then use as the
|
||||
// application key when initiating the connection with vrserver. This may not
|
||||
// be ideal if we are launched by another Steam or OpenVR application, as we will inherit
|
||||
// their app key through the environment, which means SteamVR will load the wrong bindings.
|
||||
// A real-world example of this is if someone uses an application such as OpenVR-Autostarter
|
||||
// to start the SlimeVR Server. OpenVR-Autostarter installs an application manifest with the
|
||||
// app key "dreiekk.openvr-autostarter", so when it starts SlimeVR Server, which then starts us,
|
||||
// the STEAMVR_APPKEY="dreiekk.openvr-autostarter" environment variable will be set.
|
||||
//
|
||||
// We want SteamVR to use the appkey of the Steam version of our application if possible.
|
||||
// Unfortunately, we cannot install an application vrmanifest to force the app key,
|
||||
// as SteamVR requires a binary path in the manifest to consider it valid. We do not want to install
|
||||
// a manifest with a binary path because we want the SlimeVR Server to start us when the
|
||||
// driver initiates a connection, rather than getting auto-started by SteamVR.
|
||||
//
|
||||
// This is not documented anywhere publicly, see CVRClient::SendConnectMessage in vrclient instead.
|
||||
|
||||
constexpr const char *STEAM_APPID = "3245490";
|
||||
constexpr const char *STEAMVR_APPKEY = "steam.overlay.3245490";
|
||||
|
||||
// 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", STEAM_APPID);
|
||||
SetEnvironmentVariableA("STEAMVR_APPKEY", STEAMVR_APPKEY);
|
||||
SetEnvironmentVariableA("SteamAppId", nullptr);
|
||||
SetEnvironmentVariableA("STEAMVR_APPKEY", nullptr);
|
||||
#else
|
||||
setenv("SteamAppId", STEAM_APPID, 1);
|
||||
setenv("STEAMVR_APPKEY", STEAMVR_APPKEY, 1);
|
||||
unsetenv("SteamAppId");
|
||||
unsetenv("STEAMVR_APPKEY");
|
||||
#endif
|
||||
|
||||
try {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
#include "solarxr.hpp"
|
||||
#include "logger.hpp"
|
||||
#include "paths.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#if defined(__linux__)
|
||||
#include <sys/socket.h>
|
||||
@@ -16,24 +14,15 @@
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
static std::string getenvSafe(const char *env) {
|
||||
char *v = getenv(env);
|
||||
if (v == nullptr)
|
||||
return {};
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
fs::path SolarXRConnection::getSocketPath() {
|
||||
using namespace std::string_view_literals;
|
||||
#if defined(__linux__)
|
||||
#define MAKE_SOCKET_PATH(PATH) \
|
||||
std::make_pair(PATH##sv, getenvSafe(PATH))
|
||||
std::make_pair(PATH##sv, static_cast<const char *>(getenv(PATH)))
|
||||
|
||||
constexpr std::string_view socketName = "SlimeVRRpc";
|
||||
std::array<std::pair<std::string_view, fs::path>, 5> socketPaths{
|
||||
std::array<std::pair<std::string_view, const char *>, 4> socketPaths{
|
||||
MAKE_SOCKET_PATH("SLIMEVR_SOCKET_DIR"),
|
||||
{ "Steam socket path", Paths::getDataPath() },
|
||||
MAKE_SOCKET_PATH("XDG_RUNTIME_DIR"),
|
||||
MAKE_SOCKET_PATH("TMPDIR"),
|
||||
{ "/tmp", "/tmp" }
|
||||
@@ -42,17 +31,17 @@ fs::path SolarXRConnection::getSocketPath() {
|
||||
#undef MAKE_SOCKET_PATH
|
||||
|
||||
for (auto [name, path] : socketPaths) {
|
||||
if (path.empty()) {
|
||||
if (path == nullptr) {
|
||||
Logger::get().info(
|
||||
"Skipping socket directory '{}' because it doesn't exist", name);
|
||||
"Skipping socket directory {} because it doesn't exist", name);
|
||||
continue;
|
||||
}
|
||||
fs::path socketPath = path / socketName;
|
||||
fs::path socketPath = fs::path(path) / socketName;
|
||||
if (fs::exists(socketPath))
|
||||
return socketPath;
|
||||
|
||||
Logger::get().info(
|
||||
"Skipping socket directory '{}' because socket does not exist", name);
|
||||
"Skipping socket directory {} because socket does not exist", name);
|
||||
}
|
||||
#elif defined(_WIN32)
|
||||
throw std::logic_error(
|
||||
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
# Crowdin Configuration File
|
||||
# https://developer.crowdin.com/configuration-file/
|
||||
|
||||
project_id_env: CROWDIN_PROJECT_ID
|
||||
api_token_env: CROWDIN_PERSONAL_TOKEN
|
||||
|
||||
files:
|
||||
- source: /gui/app/public/i18n/en/translation.ftl
|
||||
translation: /gui/app/public/i18n/%locale%/%original_file_name%
|
||||
languages_mapping:
|
||||
locale:
|
||||
zh-CN: zh-Hans
|
||||
zh-TW: zh-Hant
|
||||
nb: nb-NO
|
||||
nb-NO: nb-NO
|
||||
sv: sv-SE
|
||||
sv-SE: sv-SE
|
||||
en-OWO: en-x-owo
|
||||
owo: en-x-owo
|
||||
Generated
+18
-1
@@ -34,6 +34,22 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs-jdk24": {
|
||||
"locked": {
|
||||
"lastModified": 1756787288,
|
||||
"narHash": "sha256-rw/PHa1cqiePdBxhF66V7R+WAP8WekQ0mCDG4CFqT8Y=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "d0fc30899600b9b3466ddb260fd83deb486c32f1",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "d0fc30899600b9b3466ddb260fd83deb486c32f1",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs-lib": {
|
||||
"locked": {
|
||||
"lastModified": 1777168982,
|
||||
@@ -52,7 +68,8 @@
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-parts": "flake-parts",
|
||||
"nixpkgs": "nixpkgs"
|
||||
"nixpkgs": "nixpkgs",
|
||||
"nixpkgs-jdk24": "nixpkgs-jdk24"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
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";
|
||||
};
|
||||
|
||||
@@ -10,6 +12,7 @@
|
||||
inputs@{
|
||||
self,
|
||||
nixpkgs,
|
||||
nixpkgs-jdk24,
|
||||
flake-parts,
|
||||
...
|
||||
}:
|
||||
@@ -20,8 +23,15 @@
|
||||
];
|
||||
|
||||
perSystem =
|
||||
{ lib, pkgs, ... }:
|
||||
{
|
||||
system,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
java = (import nixpkgs-jdk24 { inherit system; }).jdk24;
|
||||
|
||||
runtimeLibs = [
|
||||
pkgs.alsa-lib
|
||||
pkgs.libpulseaudio
|
||||
@@ -114,7 +124,8 @@
|
||||
devShells.default = pkgs.mkShell {
|
||||
packages = [
|
||||
# for running the jar
|
||||
pkgs.jdk17
|
||||
java
|
||||
|
||||
# for build
|
||||
pkgs.electron
|
||||
pkgs.rpm
|
||||
@@ -139,7 +150,7 @@
|
||||
];
|
||||
buildInputs = runtimeLibs;
|
||||
|
||||
JAVA_HOME = "${pkgs.jdk17}/lib/openjdk";
|
||||
JAVA_HOME = "${java}/lib/openjdk";
|
||||
USE_SYSTEM_FPM = "true";
|
||||
ELECTRON_BUILDER_7ZIP_PATH = "${pkgs.p7zip}/bin/7za";
|
||||
APPIMAGE_TOOLS_PATH = "${appImageTools}";
|
||||
|
||||
+1
-4
@@ -17,7 +17,4 @@ kotlinVersion=2.3.10
|
||||
spotlessVersion=8.2.1
|
||||
shadowJarVersion=9.3.1
|
||||
buildconfigVersion=6.0.7
|
||||
|
||||
# Fix gradle leaving multiple java processes running that accumulate and use multiple GBs of RAM
|
||||
# This mostly seems to affect it when running from console, and then sending a SIGINT (Ctrl + C)
|
||||
org.gradle.daemon.idletimeout=10000
|
||||
wireVersion=5.3.1
|
||||
Vendored
BIN
Binary file not shown.
+2
-2
@@ -1,7 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.4-bin.zip
|
||||
distributionSha256Sum=f1771298a70f6db5a29daf62378c4e18a17fc33c9ba6b14362e0cdf40610380d
|
||||
distributionSha256Sum=bbaeb2fef8710818cf0e261201dab964c572f92b942812df0c3620d62a529a01
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
@@ -86,8 +86,7 @@ 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
|
||||
' "$PWD" ) || exit
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
@@ -115,7 +114,7 @@ case "$( uname )" in #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
@@ -206,7 +205,7 @@ fi
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# * DEFAULT_JVM_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.
|
||||
@@ -214,7 +213,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
|
||||
Vendored
+2
-2
@@ -70,11 +70,11 @@ goto fail
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
"%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" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
|
||||
@@ -292,9 +292,6 @@ widget-overlay = Overlay
|
||||
widget-overlay-is_visible_label = Show Overlay in SteamVR
|
||||
widget-overlay-is_mirrored_label = Display Overlay as Mirror
|
||||
|
||||
## Widget: Drift compensation
|
||||
widget-drift_compensation-clear = Clear drift compensation
|
||||
|
||||
## Widget: Clear Mounting calibration
|
||||
widget-clear_mounting = Clear mounting calibration
|
||||
|
||||
@@ -389,9 +386,6 @@ tracker-settings-assignment_section-edit = Edit assignment
|
||||
tracker-settings-mounting_section = Mounting orientation
|
||||
tracker-settings-mounting_section-description = Where is the tracker mounted?
|
||||
tracker-settings-mounting_section-edit = Edit mounting
|
||||
tracker-settings-drift_compensation_section = Allow drift compensation
|
||||
tracker-settings-drift_compensation_section-description = Should this tracker compensate for its drift when drift compensation is enabled?
|
||||
tracker-settings-drift_compensation_section-edit = Allow drift compensation
|
||||
tracker-settings-use_mag = Allow magnetometer on this tracker
|
||||
# Multiline!
|
||||
tracker-settings-use_mag-description =
|
||||
@@ -481,13 +475,12 @@ mounting_selection_menu-close = Close
|
||||
## Sidebar settings
|
||||
settings-sidebar-title = Settings
|
||||
settings-sidebar-general = General
|
||||
settings-sidebar-steamvr = SteamVR
|
||||
settings-sidebar-output = Output
|
||||
settings-sidebar-tracker_mechanics = Tracker mechanics
|
||||
settings-sidebar-stay_aligned = Stay Aligned
|
||||
settings-sidebar-fk_settings = Tracking settings
|
||||
settings-sidebar-gesture_control = Gesture control
|
||||
settings-sidebar-interface = Interface
|
||||
settings-sidebar-osc_router = OSC router
|
||||
settings-sidebar-osc_trackers = VRChat OSC Trackers
|
||||
settings-sidebar-osc_vmc = VMC
|
||||
settings-sidebar-utils = Utilities
|
||||
@@ -501,15 +494,16 @@ settings-sidebar-firmware-tool = DIY Firmware Tool
|
||||
settings-sidebar-vrc_warnings = VRChat Config Warnings
|
||||
settings-sidebar-advanced = Advanced
|
||||
|
||||
## SteamVR settings
|
||||
settings-general-steamvr = SteamVR
|
||||
settings-general-steamvr-subtitle = SteamVR trackers
|
||||
## Output settings
|
||||
# Some keys have steamvr in them as we switched to output but want to keep existing translations
|
||||
settings-general-output = Output
|
||||
settings-general-output_trackers = Output trackers
|
||||
# Not all translation keys support multiline, only the ones that specify it will actually
|
||||
# split it in lines (that also means you can split in lines however you want in those).
|
||||
# The first spaces (not tabs) for indentation will be ignored, just to make the file look nice when writing.
|
||||
# This one is one of this cases that cares about multilines
|
||||
settings-general-steamvr-description =
|
||||
Enable or disable specific SteamVR trackers.
|
||||
settings-general-output_trackers-description =
|
||||
Enable or disable specific trackers to output.
|
||||
Useful for games or apps that only support certain trackers.
|
||||
settings-general-steamvr-trackers-waist = Waist
|
||||
settings-general-steamvr-trackers-chest = Chest
|
||||
@@ -522,10 +516,9 @@ settings-general-steamvr-trackers-right_elbow = Right elbow
|
||||
settings-general-steamvr-trackers-left_hand = Left hand
|
||||
settings-general-steamvr-trackers-right_hand = Right hand
|
||||
settings-general-steamvr-trackers-tracker_toggling = Automatic tracker assignment
|
||||
settings-general-steamvr-trackers-tracker_toggling-description = Automatically handles toggling SteamVR trackers on or off depending on your current tracker assignments.
|
||||
settings-general-output-trackers-tracker_toggling-description = Automatically handles toggling output trackers on or off depending on your current tracker assignments.
|
||||
settings-general-steamvr-trackers-tracker_toggling-label = Automatic tracker assignment
|
||||
settings-general-steamvr-trackers-hands-warning = <b>Warning:</b> Enabling the SteamVR hand trackers will disable inputs from real controllers.
|
||||
This should only be enabled if you are using SlimeVR for hand tracking.
|
||||
settings-general-output-trackers-hands-warning = <b>Warning:</b> Enabling the hand trackers will disable inputs from real controllers in SteamVR.
|
||||
|
||||
Are you sure you want to do this?
|
||||
settings-general-steamvr-trackers-hands-warning-cancel = Cancel
|
||||
@@ -547,25 +540,6 @@ settings-general-tracker_mechanics-filtering-type-prediction = Prediction
|
||||
settings-general-tracker_mechanics-filtering-type-prediction-description = Reduces latency and makes movements more snappy, but may increase jitter.
|
||||
settings-general-tracker_mechanics-filtering-amount = Amount
|
||||
settings-general-tracker_mechanics-yaw-reset-smooth-time = Yaw reset smooth time (0s disables smoothing)
|
||||
settings-general-tracker_mechanics-drift_compensation = Drift compensation
|
||||
# This cares about multilines
|
||||
settings-general-tracker_mechanics-drift_compensation-description =
|
||||
Compensates for IMU yaw drift by applying an inverse rotation.
|
||||
Change the amount of compensation and the number of resets taken into account.
|
||||
This should only be used if you need to reset very often!
|
||||
settings-general-tracker_mechanics-drift_compensation-enabled-label = Drift compensation
|
||||
settings-general-tracker_mechanics-drift_compensation-prediction = Drift compensation prediction
|
||||
# This cares about multilines
|
||||
settings-general-tracker_mechanics-drift_compensation-prediction-description =
|
||||
Predicts yaw drift compensation beyond previously measured range.
|
||||
Enable this if your trackers are continuously spinning on the yaw axis.
|
||||
settings-general-tracker_mechanics-drift_compensation-prediction-label = Drift compensation prediction
|
||||
settings-general-tracker_mechanics-drift_compensation_warning =
|
||||
<b>Warning:</b> Only use drift compensation if you need to reset
|
||||
very often (every ~5-10 minutes).
|
||||
|
||||
Some IMUs prone to frequent resets include:
|
||||
Joy-Cons, owoTrack, and MPUs (without recent firmware).
|
||||
settings-general-tracker_mechanics-drift_compensation_warning-cancel = Cancel
|
||||
settings-general-tracker_mechanics-drift_compensation_warning-done = I understand
|
||||
settings-general-tracker_mechanics-drift_compensation-amount-label = Compensation amount
|
||||
@@ -589,9 +563,8 @@ settings-stay_aligned = Stay Aligned
|
||||
settings-stay_aligned-description = Stay Aligned reduces drift by gradually adjusting your trackers to match your relaxed poses.
|
||||
settings-stay_aligned-setup-label = Setup Stay Aligned
|
||||
settings-stay_aligned-setup-description = You must complete "Setup Stay Aligned" to enable Stay Aligned.
|
||||
settings-stay_aligned-warnings-drift_compensation = ⚠ Please turn off Drift Compensation! Drift Compensation will conflict with Stay Aligned.
|
||||
settings-stay_aligned-enabled-label = Adjust trackers
|
||||
settings-stay_aligned-hide_yaw_correction-label = Hide adjustment (to compare with no Stay Aligned)
|
||||
settings-stay_aligned-hide_yaw_correction-label = Hide adjustment (to compare without Stay Aligned)
|
||||
settings-stay_aligned-general-label = General
|
||||
settings-stay_aligned-relaxed_poses-label = Relaxed Poses
|
||||
settings-stay_aligned-relaxed_poses-description = Stay Aligned uses your relaxed poses to keep the trackers aligned. Use "Setup Stay Aligned" to update these poses.
|
||||
@@ -653,17 +626,10 @@ settings-general-fk_settings-arm_fk-tpose_down = T-pose (down)
|
||||
settings-general-fk_settings-arm_fk-tpose_down-description = Expects your arms to be 90 degrees up to the sides during Full Reset, and down at your sides during Mounting Calibration.
|
||||
settings-general-fk_settings-arm_fk-forward = Forward
|
||||
settings-general-fk_settings-arm_fk-forward-description = Expects your arms to be raised forward at 90 degrees. Useful for VTubing.
|
||||
settings-general-fk_settings-skeleton_settings-toggles = Skeleton toggles
|
||||
settings-general-fk_settings-skeleton_settings-description = Toggle skeleton settings on or off. It is recommended to leave these on.
|
||||
settings-general-fk_settings-skeleton_settings-extended_spine_model = Extended spine model
|
||||
settings-general-fk_settings-skeleton_settings-extended_pelvis_model = Extended pelvis model
|
||||
settings-general-fk_settings-skeleton_settings-extended_knees_model = Extended knee model
|
||||
settings-general-fk_settings-skeleton_settings-ratios = Skeleton ratios
|
||||
settings-general-fk_settings-skeleton_settings-ratios-description = Change the values of skeleton settings. You may need to adjust your proportions after changing these.
|
||||
settings-general-fk_settings-skeleton_settings-impute_waist_from_chest_hip = Impute waist from chest to hip
|
||||
settings-general-fk_settings-skeleton_settings-impute_waist_from_chest_legs = Impute waist from chest to legs
|
||||
settings-general-fk_settings-skeleton_settings-impute_hip_from_chest_legs = Impute hip from chest to legs
|
||||
settings-general-fk_settings-skeleton_settings-impute_hip_from_waist_legs = Impute hip from waist to legs
|
||||
settings-general-fk_settings-skeleton_settings-impute_spine_from_top_down = Impute missing spine trackers from upper to lower
|
||||
settings-general-fk_settings-skeleton_settings-impute_spine_curvature = How much to curve the spine with at least 2 adjacent spine trackers
|
||||
settings-general-fk_settings-skeleton_settings-interp_hip_legs = Average the hip's yaw and roll with the legs'
|
||||
settings-general-fk_settings-skeleton_settings-interp_knee_tracker_ankle = Average the knee trackers' yaw and roll with the ankles'
|
||||
settings-general-fk_settings-skeleton_settings-interp_knee_ankle = Average the knees' yaw and roll with the ankles'
|
||||
@@ -690,15 +656,17 @@ settings-general-gesture_control-trackers = { $amount ->
|
||||
settings-general-gesture_control-yawResetEnabled = Enable tap to yaw reset
|
||||
settings-general-gesture_control-yawResetDelay = Yaw reset delay
|
||||
settings-general-gesture_control-yawResetTaps = Taps for yaw reset
|
||||
settings-general-gesture_control-yawResetTracker = Yaw reset tracker
|
||||
settings-general-gesture_control-yawResetTracker = Yaw Reset Tracker
|
||||
settings-general-gesture_control-fullResetEnabled = Enable tap to full reset
|
||||
settings-general-gesture_control-fullResetDelay = Full reset delay
|
||||
settings-general-gesture_control-fullResetTaps = Taps for full reset
|
||||
settings-general-gesture_control-fullResetTracker = Full reset tracker
|
||||
settings-general-gesture_control-mountingResetEnabled = Enable tap to perform mounting calibration
|
||||
settings-general-gesture_control-fullResetTracker = Full Reset Tracker
|
||||
settings-general-gesture_control-mountingResetEnabled = Enable tap to mounting reset
|
||||
settings-general-gesture_control-mountingResetDelay = Mounting calibration delay
|
||||
settings-general-gesture_control-mountingResetTaps = Taps for mounting calibration
|
||||
settings-general-gesture_control-mountingResetTracker = Mounting reset tracker
|
||||
settings-general-gesture_control-mountingResetTracker = Mounting Reset Tracker
|
||||
settings-general-gesture_control-yawResetTracker-title = Yaw Reset Tracker
|
||||
settings-general-gesture_control-fullResetTracker-title = Full Reset Tracker
|
||||
# The number of trackers that can have higher acceleration before a tap is rejected
|
||||
settings-general-gesture_control-numberTrackersOverThreshold = Trackers over threshold
|
||||
settings-general-gesture_control-numberTrackersOverThreshold-description = Increase this value if tap detection is not working. Do not increase it above what is needed to make tap detection work as it would cause more false positives.
|
||||
@@ -803,30 +771,6 @@ settings-serial-send_command-warning =
|
||||
settings-serial-send_command-warning-ok = I know what I'm doing
|
||||
settings-serial-send_command-warning-cancel = Cancel
|
||||
|
||||
## OSC router settings
|
||||
settings-osc-router = OSC router
|
||||
# This cares about multilines
|
||||
settings-osc-router-description =
|
||||
Forward OSC messages from another program.
|
||||
Useful for using another OSC program with VRChat, for example.
|
||||
settings-osc-router-enable = Enable
|
||||
settings-osc-router-enable-description = Toggle the forwarding of messages.
|
||||
settings-osc-router-enable-label = Enable
|
||||
settings-osc-router-network = Network ports
|
||||
# This cares about multilines
|
||||
settings-osc-router-network-description =
|
||||
Set the ports for listening and sending data.
|
||||
These can be the same as other ports used in the SlimeVR server.
|
||||
settings-osc-router-network-port_in =
|
||||
.label = Port In
|
||||
.placeholder = Port in (default: 9002)
|
||||
settings-osc-router-network-port_out =
|
||||
.label = Port Out
|
||||
.placeholder = Port out (default: 9000)
|
||||
settings-osc-router-network-address = Network address
|
||||
settings-osc-router-network-address-description = Set the address to send out data at.
|
||||
settings-osc-router-network-address-placeholder = IPV4 address
|
||||
|
||||
## OSC VRChat settings
|
||||
settings-osc-vrchat = VRChat OSC Trackers
|
||||
# This cares about multilines
|
||||
@@ -855,13 +799,40 @@ settings-osc-vrchat-network-port_out =
|
||||
settings-osc-vrchat-network-address = Network address
|
||||
settings-osc-vrchat-network-address-description-v1 = Choose which address to send out data to. Can be left untouched for VRChat.
|
||||
settings-osc-vrchat-network-address-placeholder = VRChat ip address
|
||||
settings-osc-vrchat-network-trackers = Trackers
|
||||
settings-osc-vrchat-network-trackers-description = Toggle the sending of specific trackers via OSC.
|
||||
settings-osc-vrchat-network-trackers-chest = Chest
|
||||
settings-osc-vrchat-network-trackers-hip = Hip
|
||||
settings-osc-vrchat-network-trackers-knees = Knees
|
||||
settings-osc-vrchat-network-trackers-feet = Feet
|
||||
settings-osc-vrchat-network-trackers-elbows = Elbows
|
||||
|
||||
## VRChat OSC status
|
||||
settings-osc-vrchat-status-title = Status
|
||||
settings-osc-vrchat-status-disabled = Disabled
|
||||
settings-osc-vrchat-status-input = Input
|
||||
settings-osc-vrchat-status-output = Output
|
||||
settings-osc-vrchat-status-oscquery = OSCQuery
|
||||
settings-osc-vrchat-status-input-idle = Not listening
|
||||
settings-osc-vrchat-status-input-listening = Listening on port {$port}
|
||||
settings-osc-vrchat-status-input-last-data = Last data from VRChat: {$elapsed}
|
||||
settings-osc-vrchat-status-input-no-data = No data received from VRChat yet
|
||||
settings-osc-vrchat-status-output-idle = No target
|
||||
settings-osc-vrchat-status-output-sending = Sending to {$address}:{$port} ({$source})
|
||||
settings-osc-vrchat-status-output-target = Target {$address}:{$port} ({$source})
|
||||
settings-osc-vrchat-status-output-last-frame = Last frame sent: {$elapsed}
|
||||
settings-osc-vrchat-status-output-no-frame = No frame sent yet
|
||||
settings-osc-vrchat-status-source-manual = manual
|
||||
settings-osc-vrchat-status-source-auto = auto-detected
|
||||
settings-osc-vrchat-status-oscquery-disabled = OSCQuery off (manual network mode)
|
||||
settings-osc-vrchat-status-oscquery-advertising = Advertising on port {$port}
|
||||
settings-osc-vrchat-status-oscquery-searching = No VRChat clients found yet
|
||||
settings-osc-vrchat-status-oscquery-discovered-title = Discovered VRChat clients:
|
||||
settings-osc-vrchat-status-oscquery-switch = Switch
|
||||
settings-osc-vrchat-status-network-mode = Network mode
|
||||
settings-osc-vrchat-status-network-mode-description = Automatic mode discovers VRChat through OSCQuery. Manual mode uses the configured address and ports.
|
||||
settings-osc-vrchat-status-network-mode-toggle = Manual network settings
|
||||
settings-osc-vrchat-status-network-manual-description = Configure the local input port and the VRChat OSC target manually.
|
||||
settings-osc-vrchat-status-badge-idle = Idle
|
||||
settings-osc-vrchat-status-badge-listening = Listening
|
||||
settings-osc-vrchat-status-badge-ready = Ready
|
||||
settings-osc-vrchat-status-badge-found = Found
|
||||
settings-osc-vrchat-status-badge-searching = Searching
|
||||
settings-osc-vrchat-status-badge-disabled = Disabled
|
||||
settings-osc-vrchat-status-badge-error = Error
|
||||
|
||||
## VMC OSC settings
|
||||
settings-osc-vmc = Virtual Motion Capture
|
||||
@@ -895,7 +866,7 @@ settings-osc-vmc-mirror_tracking-description = Mirror the tracking horizontally.
|
||||
settings-osc-vmc-mirror_tracking-label = Mirror tracking
|
||||
|
||||
## Common OSC settings
|
||||
settings-osc-common-network-ports_match_error = The OSC Router in and out ports can't be the same!
|
||||
settings-osc-common-network-ports_match_error-v2 = The in and out ports can't be the same!
|
||||
settings-osc-common-network-port_banned_error = The port { $port } can't be used!
|
||||
|
||||
## Advanced settings
|
||||
|
||||
@@ -28,7 +28,6 @@ import { SerialDetectionModal } from './components/SerialDetectionModal';
|
||||
import { VRCOSCSettings } from './components/settings/pages/VRCOSCSettings';
|
||||
import { TopBar } from './components/TopBar';
|
||||
import { TrackerSettingsPage } from './components/tracker/TrackerSettings';
|
||||
import { OSCRouterSettings } from './components/settings/pages/OSCRouterSettings';
|
||||
import { VMCSettings } from './components/settings/pages/VMCSettings';
|
||||
import { MountingChoose } from './components/onboarding/pages/mounting/MountingChoose';
|
||||
import { VersionUpdateModal } from './components/VersionUpdateModal';
|
||||
@@ -139,7 +138,6 @@ function Layout() {
|
||||
<Route path="firmware-tool" element={<FirmwareToolSettings />} />
|
||||
<Route path="trackers" element={<GeneralSettings />} />
|
||||
<Route path="serial" element={<Serial />} />
|
||||
<Route path="osc/router" element={<OSCRouterSettings />} />
|
||||
<Route path="osc/vrchat" element={<VRCOSCSettings />} />
|
||||
<Route path="osc/vmc" element={<VMCSettings />} />
|
||||
<Route path="interface" element={<InterfaceSettings />} />
|
||||
|
||||
@@ -66,7 +66,7 @@ function BasicResetButton(options: UseResetOptions & { customName?: string }) {
|
||||
const name = options.customName || resetName;
|
||||
|
||||
const skiReset =
|
||||
options.type === ResetType.Mounting && options.group === 'default';
|
||||
options.type === ResetType.MOUNTING && options.group === 'default';
|
||||
|
||||
return (
|
||||
<Tooltip
|
||||
@@ -175,8 +175,8 @@ export function Toolbar() {
|
||||
<div className="flex-col flex gap-1 md:w-[60%]">
|
||||
<Typography variant="section-title" id="toolbar-drift_reset" />
|
||||
<div className="gap-2 md:h-[72px] h-[62px] w-full grid-cols-2 grid">
|
||||
<BasicResetButton type={ResetType.Full} />
|
||||
<BasicResetButton type={ResetType.Yaw} />
|
||||
<BasicResetButton type={ResetType.FULL} />
|
||||
<BasicResetButton type={ResetType.YAW} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-col flex gap-1 md:flex-grow">
|
||||
@@ -191,18 +191,18 @@ export function Toolbar() {
|
||||
}}
|
||||
>
|
||||
<BasicResetButton
|
||||
type={ResetType.Mounting}
|
||||
type={ResetType.MOUNTING}
|
||||
group={'default'}
|
||||
customName="toolbar-mounting_calibration-default"
|
||||
/>
|
||||
<BasicResetButton
|
||||
type={ResetType.Mounting}
|
||||
type={ResetType.MOUNTING}
|
||||
group={'feet'}
|
||||
customName="toolbar-mounting_calibration-feet"
|
||||
/>
|
||||
{groupVisibility['fingers'] && (
|
||||
<BasicResetButton
|
||||
type={ResetType.Mounting}
|
||||
type={ResetType.MOUNTING}
|
||||
group={'fingers'}
|
||||
customName="toolbar-mounting_calibration-fingers"
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export function TouchDoubleIcon({ size = 22 }) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
height={size}
|
||||
viewBox="0 -960 960 960"
|
||||
width={size}
|
||||
fill="#e3e3e3"
|
||||
>
|
||||
<path d="M411.59-71.87q-31.92 0-59.85-13.68-27.93-13.69-47.31-38.78L83.8-405.63l27.13-25.26q22.4-21.72 52.91-25.48 30.51-3.76 56.9 12.44l67.3 40.45V-721.2q0-18.67 12.82-31.48 12.81-12.82 31.5-12.82 18.68 0 31.87 12.82 13.18 12.81 13.18 31.48v475.35l-106.08-64.3L375.8-177.63q6.72 7.96 15.87 12.55 9.15 4.6 19.44 4.6h232.72q31.22 0 53.46-22.23 22.23-22.24 22.23-53.46v-151.87q0-20.11-13.89-34t-34-13.89H457.41v-88.61h214.22q56.7 0 96.6 39.9 39.9 39.9 39.9 96.6v151.87q0 67.91-48.2 116.1-48.19 48.2-116.1 48.2H411.59ZM151.93-616.65q-13.57-22.95-20.88-49.55-7.31-26.6-7.31-54.76 0-86.58 61.03-147.59 61.02-61.02 147.61-61.02 28.16 0 54.12 6.86 25.96 6.86 48.91 20.34 48.92 27.44 77.23 76.23 28.32 48.79 28.32 105.14 0 28.17-7.31 54.78t-20.89 49.57l-76.41-44.31q8-14 12-28.5t4-31.5q0-32-16.5-60t-44.5-44q-13-8-28-12t-31-4q-50 0-85 35t-35 85q0 17 4 31.5t12 28.5l-76.42 44.31Zm343.61 274.02Zm62.98-482.33 44.07-77.41q48.91 27.44 77.23 76.23 28.31 48.79 28.31 105.14 0 28.17-7.31 54.78t-20.89 49.57l-76.41-44.31q8-14 12-28.5t4-31.5q0-32-16.5-60t-44.5-44Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
File renamed without changes.
@@ -27,7 +27,7 @@ export function Home() {
|
||||
|
||||
const sendToSettings = (tracker: TrackerDataT) => {
|
||||
navigate(
|
||||
`/tracker/${tracker.trackerId?.trackerNum}/${tracker.trackerId?.deviceId?.id}`
|
||||
`/tracker/${tracker.trackerId}/${tracker.deviceId}`
|
||||
);
|
||||
};
|
||||
|
||||
@@ -86,8 +86,8 @@ export function Home() {
|
||||
warning={
|
||||
!!highlightedTrackers?.trackers.find(
|
||||
(t) =>
|
||||
t?.deviceId?.id === tracker.trackerId?.deviceId?.id &&
|
||||
t?.trackerNum === tracker.trackerId?.trackerNum
|
||||
t?.deviceId?.id === tracker.deviceId &&
|
||||
t?.trackerNum === tracker.trackerId
|
||||
) && highlightedTrackers.step
|
||||
}
|
||||
/>
|
||||
@@ -128,8 +128,8 @@ export function Home() {
|
||||
warning={
|
||||
!!highlightedTrackers?.trackers.find(
|
||||
(t) =>
|
||||
t?.deviceId?.id === tracker.trackerId?.deviceId?.id &&
|
||||
t?.trackerNum === tracker.trackerId?.trackerNum
|
||||
t?.deviceId?.id === tracker.deviceId &&
|
||||
t?.trackerNum === tracker.trackerId
|
||||
) && highlightedTrackers.step
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -15,12 +15,12 @@ import { Tooltip } from '@/components/commons/Tooltip';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
|
||||
export function ResetButtonIcon(options: UseResetOptions) {
|
||||
if (options.type === ResetType.Mounting && !options.group)
|
||||
if (options.type === ResetType.MOUNTING && !options.group)
|
||||
options.group = 'default';
|
||||
|
||||
if (options.type === ResetType.Yaw) return <YawResetIcon width={18} />;
|
||||
if (options.type === ResetType.Full) return <FullResetIcon width={18} />;
|
||||
if (options.type === ResetType.Mounting) {
|
||||
if (options.type === ResetType.YAW) return <YawResetIcon width={18} />;
|
||||
if (options.type === ResetType.FULL) return <FullResetIcon width={18} />;
|
||||
if (options.type === ResetType.MOUNTING) {
|
||||
if (options.group === 'default') return <SkiIcon />;
|
||||
if (options.group === 'feet') return <FootIcon />;
|
||||
if (options.group === 'fingers') return <FingersIcon width={16} />;
|
||||
@@ -83,7 +83,7 @@ export function ResetButton({
|
||||
<div className="opacity-0 h-0">
|
||||
{children || <Localized id={name} />}
|
||||
</div>
|
||||
{status !== 'counting' || options.type === ResetType.Yaw
|
||||
{status !== 'counting' || options.type === ResetType.YAW
|
||||
? children || <Localized id={name} />
|
||||
: String(timer)}
|
||||
</div>
|
||||
|
||||
@@ -200,7 +200,7 @@ export const RIGHT_LEG_PARTS = [
|
||||
];
|
||||
|
||||
export const RESET_TYPE_ORDER = [
|
||||
ResetType.Yaw,
|
||||
ResetType.Full,
|
||||
ResetType.Mounting,
|
||||
ResetType.YAW,
|
||||
ResetType.FULL,
|
||||
ResetType.MOUNTING,
|
||||
];
|
||||
@@ -1,12 +1,9 @@
|
||||
import { Control, Controller, useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeSkeletonConfigRequestT,
|
||||
ChangeSkeletonProportionsRequestT,
|
||||
ResetType,
|
||||
RpcMessage,
|
||||
SkeletonBone,
|
||||
SkeletonConfigRequestT,
|
||||
SkeletonConfigResponseT,
|
||||
SkeletonResetAllRequestT,
|
||||
SkeletonBone, SkeletonProportionsRequestT, SkeletonProportionsResetAllRequestT, SkeletonProportionsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useOnboarding } from '@/hooks/onboarding';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
@@ -85,7 +82,7 @@ function IconButton({
|
||||
|
||||
function parseConfigImport(
|
||||
config: SkeletonConfigExport
|
||||
): ChangeSkeletonConfigRequestT[] {
|
||||
): ChangeSkeletonProportionsRequestT[] {
|
||||
if (!config.version) config.version = 1;
|
||||
if (config.version < 1) {
|
||||
// Add config migration stuff here, this one is just an example.
|
||||
@@ -95,7 +92,7 @@ function parseConfigImport(
|
||||
const bone =
|
||||
typeof part.bone === 'string' ? SkeletonBone[part.bone] : part.bone;
|
||||
|
||||
return new ChangeSkeletonConfigRequestT(bone, part.value);
|
||||
return new ChangeSkeletonProportionsRequestT(bone, part.value);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -121,7 +118,7 @@ function ImportExportButtons() {
|
||||
const exporting = useRef(false);
|
||||
|
||||
useRPCPacket(
|
||||
RpcMessage.SkeletonConfigResponse,
|
||||
RpcMessage.SkeletonProportionsResponse,
|
||||
(data: SkeletonConfigExport) => {
|
||||
if (!exporting.current) return;
|
||||
exporting.current = false;
|
||||
@@ -183,11 +180,11 @@ function ImportExportButtons() {
|
||||
}
|
||||
|
||||
parseConfigImport(config).forEach((req) =>
|
||||
sendRPCPacket(RpcMessage.ChangeSkeletonConfigRequest, req)
|
||||
sendRPCPacket(RpcMessage.ChangeSkeletonProportionsRequest, req)
|
||||
);
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonConfigRequest,
|
||||
new SkeletonConfigRequestT()
|
||||
RpcMessage.SkeletonProportionsRequest,
|
||||
new SkeletonProportionsRequestT()
|
||||
);
|
||||
setImportState(ImportStatus.SUCCESS);
|
||||
setTimeout(() => {
|
||||
@@ -219,8 +216,8 @@ function ImportExportButtons() {
|
||||
exporting.current = true;
|
||||
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonConfigRequest,
|
||||
new SkeletonConfigRequestT()
|
||||
RpcMessage.SkeletonProportionsRequest,
|
||||
new SkeletonProportionsRequestT()
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -311,16 +308,17 @@ function ButtonsControl({ control }: { control: ManualProportionControls }) {
|
||||
const [showWarning, setShowWarning] = useState(false);
|
||||
const resetAll = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonResetAllRequest,
|
||||
new SkeletonResetAllRequestT()
|
||||
RpcMessage.SkeletonProportionsResetAllRequest,
|
||||
new SkeletonProportionsResetAllRequestT()
|
||||
);
|
||||
};
|
||||
|
||||
const beneathFloor = useMemo(() => {
|
||||
// TODO I think this needs to be rewritten with rewrite but it also just may be unneeded
|
||||
const hmd = computedTrackers.find(
|
||||
(tracker) =>
|
||||
tracker.tracker.trackerId?.trackerNum === 1 &&
|
||||
tracker.tracker.trackerId.deviceId?.id === undefined
|
||||
tracker.tracker.trackerId === 1 &&
|
||||
tracker.tracker.deviceId === undefined
|
||||
);
|
||||
return !(hmd?.tracker.position && hmd.tracker.position.y >= MIN_HEIGHT);
|
||||
}, [computedTrackers]);
|
||||
@@ -418,8 +416,8 @@ export function ManualProportionsPage() {
|
||||
}, [ratio]);
|
||||
|
||||
useRPCPacket(
|
||||
RpcMessage.SkeletonConfigResponse,
|
||||
(data: SkeletonConfigResponseT) => {
|
||||
RpcMessage.SkeletonProportionsResponse,
|
||||
(data: SkeletonProportionsResponseT) => {
|
||||
if (data.userHeight) setUserHeight(data.userHeight);
|
||||
}
|
||||
);
|
||||
@@ -470,7 +468,7 @@ export function ManualProportionsPage() {
|
||||
<div className="top-4 w-full px-4 absolute flex gap-2 flex-col lg:flex-row md:flex-wrap">
|
||||
<div className="h-14 flex flex-grow items-center">
|
||||
<ResetButton
|
||||
type={ResetType.Full}
|
||||
type={ResetType.FULL}
|
||||
className="w-full h-full bg-background-50 hover:bg-background-40 text-background-10"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -7,14 +7,12 @@ import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
CancelUserHeightCalibrationT,
|
||||
ChangeSettingsRequestT,
|
||||
ModelSettingsT,
|
||||
ResetType,
|
||||
RpcMessage,
|
||||
SkeletonConfigRequestT,
|
||||
SkeletonConfigResponseT,
|
||||
SkeletonHeightT,
|
||||
SkeletonResetAllRequestT,
|
||||
SkeletonProportionsRequestT,
|
||||
SkeletonProportionsResetAllRequestT,
|
||||
SkeletonProportionsResponseT,
|
||||
StartUserHeightCalibrationT,
|
||||
UserHeightCalibrationStatus,
|
||||
UserHeightRecordingStatusResponseT,
|
||||
@@ -265,7 +263,7 @@ export function ScaledProportionsPage() {
|
||||
);
|
||||
};
|
||||
|
||||
// Makes it so you dont get spammed by sounds if multiple status complete at once
|
||||
// Makes it so you don't get spammed by sounds if multiple status complete at once
|
||||
useDebouncedEffect(
|
||||
() => {
|
||||
if (!config || !config.feedbackSound) return;
|
||||
@@ -295,8 +293,8 @@ export function ScaledProportionsPage() {
|
||||
);
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsRequest);
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonResetAllRequest,
|
||||
new SkeletonResetAllRequestT()
|
||||
RpcMessage.SkeletonProportionsResetAllRequest,
|
||||
new SkeletonProportionsResetAllRequestT()
|
||||
);
|
||||
setConfig({ lastUsedProportions: 'scaled' });
|
||||
setLastUsed('manual');
|
||||
@@ -320,8 +318,8 @@ export function ScaledProportionsPage() {
|
||||
);
|
||||
|
||||
useRPCPacket(
|
||||
RpcMessage.SkeletonConfigResponse,
|
||||
(res: SkeletonConfigResponseT) => {
|
||||
RpcMessage.SkeletonProportionsResponse,
|
||||
(res: SkeletonProportionsResponseT) => {
|
||||
setHmdHeight(res.userHeight);
|
||||
}
|
||||
);
|
||||
@@ -336,8 +334,8 @@ export function ScaledProportionsPage() {
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonConfigRequest,
|
||||
new SkeletonConfigRequestT()
|
||||
RpcMessage.SkeletonProportionsRequest,
|
||||
new SkeletonProportionsRequestT()
|
||||
);
|
||||
|
||||
return () => {
|
||||
@@ -356,8 +354,8 @@ export function ScaledProportionsPage() {
|
||||
if (status && checkNotAuto(status.status)) {
|
||||
setAuto(false);
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonConfigRequest,
|
||||
new SkeletonConfigRequestT()
|
||||
RpcMessage.SkeletonProportionsRequest,
|
||||
new SkeletonProportionsRequestT()
|
||||
); // Re ask the user height so it resets back to the correct value
|
||||
}
|
||||
},
|
||||
@@ -469,7 +467,7 @@ export function ScaledProportionsPage() {
|
||||
state={{ alonePage: state.alonePage }}
|
||||
/>
|
||||
<ResetButton
|
||||
type={ResetType.Full}
|
||||
type={ResetType.FULL}
|
||||
className="bg-background-50 hover:bg-background-40 text-background-10"
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -69,7 +69,7 @@ export function PreparationStep({
|
||||
>
|
||||
{l10n.getString('onboarding-automatic_mounting-prev_step')}
|
||||
</Button>
|
||||
<ResetButton type={ResetType.Full} onReseted={nextStep} />
|
||||
<ResetButton type={ResetType.FULL} onReseted={nextStep} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -56,7 +56,6 @@ export function ManualMountingPage() {
|
||||
mountingOrientationDegrees
|
||||
);
|
||||
assignreq.trackerId = td.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
Sentry.metrics.count('manual_mounting_set', 1, {
|
||||
@@ -177,7 +176,6 @@ export function ManualMountingPageStayAligned({
|
||||
mountingOrientationDegrees
|
||||
);
|
||||
assignreq.trackerId = td.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
Sentry.metrics.count('manual_mounting_set', 1, {
|
||||
|
||||
@@ -58,7 +58,7 @@ export function MountingResetStep({
|
||||
{l10n.getString('onboarding-automatic_mounting-prev_step')}
|
||||
</Button>
|
||||
<ResetButton
|
||||
type={ResetType.Mounting}
|
||||
type={ResetType.MOUNTING}
|
||||
group="default"
|
||||
onReseted={nextStep}
|
||||
/>
|
||||
|
||||
@@ -69,7 +69,7 @@ export function PreparationStep({
|
||||
>
|
||||
{l10n.getString('onboarding-automatic_mounting-prev_step')}
|
||||
</Button>
|
||||
<ResetButton type={ResetType.Full} onReseted={nextStep} />
|
||||
<ResetButton type={ResetType.FULL} onReseted={nextStep} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { HumanIcon } from '@/components/commons/icon/HumanIcon';
|
||||
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
|
||||
import { useState } from 'react';
|
||||
import { SittingIcon } from '@/components/commons/icon/SittingIcon';
|
||||
import { VMCFileUpload } from '@/components/settings/pages/VMCSettings';
|
||||
import { VRMFileUpload } from '@/components/settings/pages/VMCSettings';
|
||||
import { QuizButton } from './SlimeSetQuestion';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
@@ -81,7 +81,7 @@ export function QuizMocapPosQuestion() {
|
||||
/>
|
||||
<Typography id="onboarding-quiz-mocap_preferences-vrm_model-desc" />
|
||||
</div>
|
||||
<VMCFileUpload />
|
||||
<VRMFileUpload />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -109,32 +109,14 @@ export function TrackersAssignPage() {
|
||||
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSettingsRequest,
|
||||
new ChangeSettingsRequestT(
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
newTapSettings
|
||||
)
|
||||
new ChangeSettingsRequestT(null, null, null, null, null, newTapSettings)
|
||||
);
|
||||
|
||||
return () => {
|
||||
newTapSettings.setupMode = false;
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSettingsRequest,
|
||||
new ChangeSettingsRequestT(
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
newTapSettings
|
||||
)
|
||||
new ChangeSettingsRequestT(null, null, null, null, null, newTapSettings)
|
||||
);
|
||||
};
|
||||
}, [tapDetectionSettings]);
|
||||
@@ -220,7 +202,6 @@ export function TrackersAssignPage() {
|
||||
assignreq.bodyPosition = role;
|
||||
assignreq.mountingOrientation = rotation;
|
||||
assignreq.trackerId = trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
};
|
||||
|
||||
@@ -50,8 +50,8 @@ export function SettingsSidebar() {
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink
|
||||
to="/settings/trackers"
|
||||
scrollTo="steamvr"
|
||||
id="settings-sidebar-steamvr"
|
||||
scrollTo="output"
|
||||
id="settings-sidebar-output"
|
||||
/>
|
||||
<SettingsLink
|
||||
to="/settings/trackers"
|
||||
@@ -93,6 +93,11 @@ export function SettingsSidebar() {
|
||||
scrollTo="appearance"
|
||||
id="settings-sidebar-appearance"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title" id="settings-sidebar-home" />
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink
|
||||
to="/settings/interface/home"
|
||||
scrollTo="home"
|
||||
@@ -104,46 +109,41 @@ export function SettingsSidebar() {
|
||||
id="settings-sidebar-checklist"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title">OSC</Typography>
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink
|
||||
to="/settings/osc/router"
|
||||
scrollTo="router"
|
||||
id="settings-sidebar-osc_router"
|
||||
/>
|
||||
<SettingsLink
|
||||
to="/settings/osc/vrchat"
|
||||
scrollTo="vrchat"
|
||||
id="settings-sidebar-osc_trackers"
|
||||
/>
|
||||
<SettingsLink
|
||||
to="/settings/osc/vmc"
|
||||
scrollTo="vmc"
|
||||
id="settings-sidebar-osc_vmc"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title">OSC</Typography>
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink
|
||||
to="/settings/osc/vrchat"
|
||||
scrollTo="vrchat"
|
||||
id="settings-sidebar-osc_trackers"
|
||||
/>
|
||||
<SettingsLink
|
||||
to="/settings/osc/vmc"
|
||||
scrollTo="vmc"
|
||||
id="settings-sidebar-osc_vmc"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title" id="settings-sidebar-utils" />
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink to="/settings/serial" id="settings-sidebar-serial" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title" id="settings-sidebar-utils" />
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink to="/settings/serial" id="settings-sidebar-serial" />
|
||||
<SettingsLink
|
||||
to="/settings/firmware-tool"
|
||||
id="settings-sidebar-firmware-tool"
|
||||
/>
|
||||
<SettingsLink to="/onboarding/home" id="navbar-onboarding" />
|
||||
{vrcConfigState?.isSupported && (
|
||||
<SettingsLink
|
||||
to="/settings/firmware-tool"
|
||||
id="settings-sidebar-firmware-tool"
|
||||
to="/vrc-warnings"
|
||||
id="settings-sidebar-vrc_warnings"
|
||||
/>
|
||||
<SettingsLink to="/onboarding/home" id="navbar-onboarding" />
|
||||
{vrcConfigState?.isSupported && (
|
||||
<SettingsLink
|
||||
to="/vrc-warnings"
|
||||
id="settings-sidebar-vrc_warnings"
|
||||
/>
|
||||
)}
|
||||
<SettingsLink
|
||||
to="/settings/advanced"
|
||||
id="settings-sidebar-advanced"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<SettingsLink
|
||||
to="/settings/advanced"
|
||||
id="settings-sidebar-advanced"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,27 +3,19 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { DefaultValues, useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
FilteringSettingsT,
|
||||
FilteringType,
|
||||
LegTweaksSettingsT,
|
||||
ModelRatiosT,
|
||||
ModelSettingsT,
|
||||
ModelTogglesT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
SteamVRTrackersSettingT,
|
||||
TapDetectionSettingsT,
|
||||
HIDSettingsT,
|
||||
VelocitySettingsT,
|
||||
BodyPart,
|
||||
OutputTrackersSettingT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useConfig } from '@/hooks/config';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { useLocaleConfig } from '@/i18n/config';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { SteamIcon } from '@/components/commons/icon/SteamIcon';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcons';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcon';
|
||||
import { NumberSelector } from '@/components/commons/NumberSelector';
|
||||
import { Radio } from '@/components/commons/Radio';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
@@ -50,29 +42,16 @@ import { isEqual } from '@react-hookz/deep-equal';
|
||||
import { selectAtom } from 'jotai/utils';
|
||||
import { Dropdown } from '@/components/commons/Dropdown';
|
||||
import { ASSIGNMENT_MODES } from '@/components/onboarding/BodyAssignment';
|
||||
import { OutputIcon } from '@/components/commons/icon/OutputIcon';
|
||||
import { TouchDoubleIcon } from '@/components/commons/icon/TouchDoubleIcon';
|
||||
import { MartialArtsIcon } from '@/components/commons/icon/MartialArtsIcon';
|
||||
|
||||
export type SettingsForm = {
|
||||
trackers: {
|
||||
waist: boolean;
|
||||
chest: boolean;
|
||||
automaticTrackerToggle: boolean;
|
||||
leftFoot: boolean;
|
||||
rightFoot: boolean;
|
||||
leftKnee: boolean;
|
||||
rightKnee: boolean;
|
||||
leftElbow: boolean;
|
||||
rightElbow: boolean;
|
||||
leftHand: boolean;
|
||||
rightHand: boolean;
|
||||
};
|
||||
filtering: {
|
||||
type: number;
|
||||
amount: number;
|
||||
};
|
||||
toggles: {
|
||||
extendedSpine: boolean;
|
||||
extendedPelvis: boolean;
|
||||
extendedKnee: boolean;
|
||||
forceArmsFromHmd: boolean;
|
||||
floorClip: boolean;
|
||||
skatingCorrection: boolean;
|
||||
@@ -84,10 +63,8 @@ export type SettingsForm = {
|
||||
correctConstraints: boolean;
|
||||
};
|
||||
ratios: {
|
||||
imputeWaistFromChestHip: number;
|
||||
imputeWaistFromChestLegs: number;
|
||||
imputeHipFromChestLegs: number;
|
||||
imputeHipFromWaistLegs: number;
|
||||
imputeSpineFromUpperLower: number;
|
||||
imputeSpineCurvature: number;
|
||||
interpHipLegs: number;
|
||||
interpKneeTrackerAnkle: number;
|
||||
interpKneeAnkle: number;
|
||||
@@ -115,29 +92,10 @@ export type SettingsForm = {
|
||||
hidSettings: {
|
||||
trackersOverHID: boolean;
|
||||
};
|
||||
velocitySettings: {
|
||||
sendDerivedVelocity: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
const defaultValues: SettingsForm = {
|
||||
trackers: {
|
||||
waist: false,
|
||||
chest: false,
|
||||
automaticTrackerToggle: true,
|
||||
leftFoot: false,
|
||||
rightFoot: false,
|
||||
leftElbow: false,
|
||||
rightElbow: false,
|
||||
leftHand: false,
|
||||
rightHand: false,
|
||||
leftKnee: false,
|
||||
rightKnee: false,
|
||||
},
|
||||
toggles: {
|
||||
extendedSpine: true,
|
||||
extendedPelvis: true,
|
||||
extendedKnee: true,
|
||||
forceArmsFromHmd: false,
|
||||
floorClip: false,
|
||||
skatingCorrection: false,
|
||||
@@ -149,10 +107,8 @@ const defaultValues: SettingsForm = {
|
||||
correctConstraints: true,
|
||||
},
|
||||
ratios: {
|
||||
imputeWaistFromChestHip: 0.3,
|
||||
imputeWaistFromChestLegs: 0.2,
|
||||
imputeHipFromChestLegs: 0.45,
|
||||
imputeHipFromWaistLegs: 0.4,
|
||||
imputeSpineFromUpperLower: 0.5,
|
||||
imputeSpineCurvature: 0.5,
|
||||
interpHipLegs: 0.25,
|
||||
interpKneeTrackerAnkle: 0.85,
|
||||
interpKneeAnkle: 0.2,
|
||||
@@ -177,7 +133,6 @@ const defaultValues: SettingsForm = {
|
||||
resetsSettings: defaultResetSettings,
|
||||
stayAligned: defaultStayAlignedSettings,
|
||||
hidSettings: { trackersOverHID: false },
|
||||
velocitySettings: { sendDerivedVelocity: false },
|
||||
};
|
||||
|
||||
const settingsAtom = atom(new SettingsResponseT());
|
||||
@@ -201,12 +156,6 @@ export function GeneralSettings() {
|
||||
value: String(value),
|
||||
label: l10n.getString(`body_part-${BodyPart[value]}`),
|
||||
}));
|
||||
const blockHandsWarning = useRef(false);
|
||||
// If not null, warning will be shown, and showHandsWarning will
|
||||
// hold which hands should be toggled ([leftHand, rightHand])
|
||||
const [showHandsWarning, setShowHandsWarning] = useState<
|
||||
[boolean, boolean] | null
|
||||
>(null);
|
||||
|
||||
const percentageFormat = new Intl.NumberFormat(currentLocales, {
|
||||
style: 'percent',
|
||||
@@ -227,53 +176,10 @@ export function GeneralSettings() {
|
||||
reValidateMode: 'onChange',
|
||||
});
|
||||
|
||||
const {
|
||||
trackers: { automaticTrackerToggle },
|
||||
} = watch();
|
||||
|
||||
|
||||
const onSubmit = (values: SettingsForm) => {
|
||||
const settingsReq = new ChangeSettingsRequestT();
|
||||
|
||||
if (values.trackers) {
|
||||
const trackers = new SteamVRTrackersSettingT();
|
||||
trackers.waist = values.trackers.waist;
|
||||
trackers.chest = values.trackers.chest;
|
||||
trackers.leftFoot = values.trackers.leftFoot;
|
||||
trackers.rightFoot = values.trackers.rightFoot;
|
||||
|
||||
trackers.leftKnee = values.trackers.leftKnee;
|
||||
trackers.rightKnee = values.trackers.rightKnee;
|
||||
|
||||
trackers.leftElbow = values.trackers.leftElbow;
|
||||
trackers.rightElbow = values.trackers.rightElbow;
|
||||
|
||||
trackers.leftHand = values.trackers.leftHand;
|
||||
trackers.rightHand = values.trackers.rightHand;
|
||||
|
||||
if (
|
||||
!blockHandsWarning.current &&
|
||||
!showHandsWarning &&
|
||||
!settings.steamVrTrackers?.leftHand &&
|
||||
!settings.steamVrTrackers?.rightHand &&
|
||||
(trackers.leftHand || trackers.rightHand)
|
||||
) {
|
||||
// We have just toggled on one of the hand trackers, show the user a warning
|
||||
setShowHandsWarning([trackers.leftHand, trackers.rightHand]);
|
||||
trackers.leftHand = false;
|
||||
trackers.rightHand = false;
|
||||
} else if (
|
||||
blockHandsWarning.current &&
|
||||
!trackers.leftHand &&
|
||||
!trackers.rightHand
|
||||
) {
|
||||
// Both hand trackers have just been disabled, make sure the warning shows up
|
||||
// again next time the user toggles one back on
|
||||
blockHandsWarning.current = false;
|
||||
}
|
||||
|
||||
trackers.automaticTrackerToggle = values.trackers.automaticTrackerToggle;
|
||||
settingsReq.steamVrTrackers = trackers;
|
||||
}
|
||||
const req = new ChangeSettingsRequestT();
|
||||
|
||||
const modelSettings = new ModelSettingsT();
|
||||
|
||||
@@ -281,9 +187,6 @@ export function GeneralSettings() {
|
||||
const toggles = new ModelTogglesT();
|
||||
toggles.floorClip = values.toggles.floorClip;
|
||||
toggles.skatingCorrection = values.toggles.skatingCorrection;
|
||||
toggles.extendedKnee = values.toggles.extendedKnee;
|
||||
toggles.extendedPelvis = values.toggles.extendedPelvis;
|
||||
toggles.extendedSpine = values.toggles.extendedSpine;
|
||||
toggles.forceArmsFromHmd = values.toggles.forceArmsFromHmd;
|
||||
toggles.toeSnap = values.toggles.toeSnap;
|
||||
toggles.footPlant = values.toggles.footPlant;
|
||||
@@ -296,14 +199,9 @@ export function GeneralSettings() {
|
||||
|
||||
if (values.ratios) {
|
||||
const ratios = new ModelRatiosT();
|
||||
ratios.imputeWaistFromChestHip =
|
||||
values.ratios.imputeWaistFromChestHip || -1;
|
||||
ratios.imputeWaistFromChestLegs =
|
||||
values.ratios.imputeWaistFromChestLegs || -1;
|
||||
ratios.imputeHipFromChestLegs =
|
||||
values.ratios.imputeHipFromChestLegs || -1;
|
||||
ratios.imputeHipFromWaistLegs =
|
||||
values.ratios.imputeHipFromWaistLegs || -1;
|
||||
ratios.imputeSpineFromUpperLower =
|
||||
values.ratios.imputeSpineFromUpperLower || -1;
|
||||
ratios.imputeSpineCurvature = values.ratios.imputeSpineCurvature || -1;
|
||||
ratios.interpHipLegs = values.ratios.interpHipLegs || -1;
|
||||
ratios.interpKneeTrackerAnkle =
|
||||
values.ratios.interpKneeTrackerAnkle || -1;
|
||||
@@ -317,7 +215,7 @@ export function GeneralSettings() {
|
||||
modelSettings.legTweaks = legTweaks;
|
||||
}
|
||||
|
||||
settingsReq.modelSettings = modelSettings;
|
||||
req.modelSettings = modelSettings;
|
||||
|
||||
const tapDetection = new TapDetectionSettingsT();
|
||||
tapDetection.fullResetDelay = values.tapDetection.fullResetDelay;
|
||||
@@ -340,29 +238,29 @@ export function GeneralSettings() {
|
||||
tapDetection.numberTrackersOverThreshold =
|
||||
values.tapDetection.numberTrackersOverThreshold;
|
||||
tapDetection.setupMode = false;
|
||||
settingsReq.tapDetectionSettings = tapDetection;
|
||||
req.tapDetectionSettings = tapDetection;
|
||||
|
||||
const filtering = new FilteringSettingsT();
|
||||
filtering.type = values.filtering.type;
|
||||
filtering.amount = values.filtering.amount;
|
||||
settingsReq.filtering = filtering;
|
||||
req.filtering = filtering;
|
||||
|
||||
settingsReq.stayAligned = serializeStayAlignedSettings(values.stayAligned);
|
||||
req.stayAligned = serializeStayAlignedSettings(values.stayAligned);
|
||||
|
||||
const hidSettings = new HIDSettingsT();
|
||||
hidSettings.trackersOverHid = values.hidSettings.trackersOverHID;
|
||||
settingsReq.hidSettings = hidSettings;
|
||||
req.hidSettings = hidSettings;
|
||||
|
||||
const velocitySettings = new VelocitySettingsT();
|
||||
velocitySettings.sendDerivedVelocity =
|
||||
values.velocitySettings.sendDerivedVelocity;
|
||||
settingsReq.velocitySettings = velocitySettings;
|
||||
req.velocitySettings = velocitySettings;
|
||||
|
||||
if (values.resetsSettings) {
|
||||
settingsReq.resetsSettings = loadResetSettings(values.resetsSettings);
|
||||
req.resetsSettings = loadResetSettings(values.resetsSettings);
|
||||
}
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsReq);
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -383,12 +281,12 @@ export function GeneralSettings() {
|
||||
formData.filtering = settings.filtering;
|
||||
}
|
||||
|
||||
if (settings.steamVrTrackers) {
|
||||
formData.trackers = settings.steamVrTrackers;
|
||||
if (settings.outputTrackers) {
|
||||
formData.trackers = settings.outputTrackers;
|
||||
if (
|
||||
!blockHandsWarning.current &&
|
||||
(settings.steamVrTrackers.leftHand ||
|
||||
settings.steamVrTrackers.rightHand)
|
||||
(settings.outputTrackers.trackers.includes(BodyPart.LEFT_HAND) ||
|
||||
settings.outputTrackers.trackers.includes(BodyPart.RIGHT_HAND))
|
||||
) {
|
||||
blockHandsWarning.current = true;
|
||||
}
|
||||
@@ -522,32 +420,22 @@ export function GeneralSettings() {
|
||||
}}
|
||||
/>
|
||||
<form className="flex flex-col gap-2 w-full">
|
||||
<SettingsPagePaneLayout icon={<SteamIcon />} id="steamvr">
|
||||
<SettingsPagePaneLayout icon={<OutputIcon />} id="output">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-general-steamvr')}
|
||||
{l10n.getString('settings-general-output')}
|
||||
</Typography>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-general-steamvr-subtitle')}
|
||||
</Typography>
|
||||
<div className="flex flex-col py-2">
|
||||
{l10n
|
||||
.getString('settings-general-steamvr-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col pt-4" />
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-steamvr-trackers-tracker_toggling'
|
||||
)}
|
||||
</Typography>
|
||||
<div className="flex flex-col pt-2 pb-4">
|
||||
<div className="flex flex-col py-2">
|
||||
{l10n
|
||||
.getString(
|
||||
'settings-general-steamvr-trackers-tracker_toggling-description'
|
||||
'settings-general-output-trackers-tracker_toggling-description'
|
||||
)
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
@@ -564,6 +452,18 @@ export function GeneralSettings() {
|
||||
)}
|
||||
/>
|
||||
<div className="flex flex-col pt-4" />
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-general-output_trackers')}
|
||||
</Typography>
|
||||
<div className="flex flex-col py-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"
|
||||
@@ -664,6 +564,33 @@ export function GeneralSettings() {
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col pt-4" />
|
||||
|
||||
<div className="flex flex-col pt-2 pb-1">
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings'
|
||||
)}
|
||||
</Typography>
|
||||
<div className="pt-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-1 pb-3">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="velocitySettings.sendDerivedVelocity"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings-send_derived_velocity'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
<StayAlignedSettings values={getValues()} control={control} />
|
||||
@@ -801,7 +728,7 @@ export function GeneralSettings() {
|
||||
/>
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
<SettingsPagePaneLayout icon={<WrenchIcon />} id="fksettings">
|
||||
<SettingsPagePaneLayout icon={<MartialArtsIcon />} id="fksettings">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-general-fk_settings')}
|
||||
@@ -974,7 +901,7 @@ export function GeneralSettings() {
|
||||
<div className="grid md:grid-cols-2 flex-col gap-3 pt-2 pb-3">
|
||||
<Radio
|
||||
control={control}
|
||||
name="resetsSettings.armsMountingResetMode"
|
||||
name="resetsSettings.armsResetMode"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-arm_fk-back'
|
||||
)}
|
||||
@@ -985,7 +912,7 @@ export function GeneralSettings() {
|
||||
/>
|
||||
<Radio
|
||||
control={control}
|
||||
name="resetsSettings.armsMountingResetMode"
|
||||
name="resetsSettings.armsResetMode"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-arm_fk-forward'
|
||||
)}
|
||||
@@ -996,7 +923,7 @@ export function GeneralSettings() {
|
||||
/>
|
||||
<Radio
|
||||
control={control}
|
||||
name="resetsSettings.armsMountingResetMode"
|
||||
name="resetsSettings.armsResetMode"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-arm_fk-tpose_up'
|
||||
)}
|
||||
@@ -1007,7 +934,7 @@ export function GeneralSettings() {
|
||||
/>
|
||||
<Radio
|
||||
control={control}
|
||||
name="resetsSettings.armsMountingResetMode"
|
||||
name="resetsSettings.armsResetMode"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-arm_fk-tpose_down'
|
||||
)}
|
||||
@@ -1067,75 +994,8 @@ export function GeneralSettings() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col pt-2 pb-1">
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings'
|
||||
)}
|
||||
</Typography>
|
||||
<div className="pt-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-1 pb-3">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="velocitySettings.sendDerivedVelocity"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings-send_derived_velocity'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{config?.debug && (
|
||||
<>
|
||||
<div className="flex flex-col pt-2 pb-3">
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-toggles'
|
||||
)}
|
||||
</Typography>
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-2 gap-3 pb-3">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="toggles.extendedSpine"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-extended_spine_model'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="toggles.extendedPelvis"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-extended_pelvis_model'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="toggles.extendedKnee"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-extended_knees_model'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<div className="flex flex-col pt-2 pb-3 gap-2">
|
||||
<Typography variant="section-title">
|
||||
@@ -1152,9 +1012,9 @@ export function GeneralSettings() {
|
||||
<div className="grid sm:grid-cols-2 gap-3 pb-3">
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name="ratios.imputeWaistFromChestHip"
|
||||
name="ratios.imputeSpineFromUpperLower"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-impute_waist_from_chest_hip'
|
||||
'settings-general-fk_settings-skeleton_settings-impute_spine_from_top_down'
|
||||
)}
|
||||
valueLabelFormat={(value) =>
|
||||
percentageFormat.format(value)
|
||||
@@ -1165,35 +1025,9 @@ export function GeneralSettings() {
|
||||
/>
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name="ratios.imputeWaistFromChestLegs"
|
||||
name="ratios.imputeSpineCurvature"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-impute_waist_from_chest_legs'
|
||||
)}
|
||||
valueLabelFormat={(value) =>
|
||||
percentageFormat.format(value)
|
||||
}
|
||||
min={0.0}
|
||||
max={1.0}
|
||||
step={0.05}
|
||||
/>
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name="ratios.imputeHipFromChestLegs"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-impute_hip_from_chest_legs'
|
||||
)}
|
||||
valueLabelFormat={(value) =>
|
||||
percentageFormat.format(value)
|
||||
}
|
||||
min={0.0}
|
||||
max={1.0}
|
||||
step={0.05}
|
||||
/>
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name="ratios.imputeHipFromWaistLegs"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-impute_hip_from_waist_legs'
|
||||
'settings-general-fk_settings-skeleton_settings-impute_spine_curvature'
|
||||
)}
|
||||
valueLabelFormat={(value) =>
|
||||
percentageFormat.format(value)
|
||||
@@ -1271,7 +1105,7 @@ export function GeneralSettings() {
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
|
||||
<SettingsPagePaneLayout icon={<WrenchIcon />} id="gestureControl">
|
||||
<SettingsPagePaneLayout icon={<TouchDoubleIcon />} id="gestureControl">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-general-gesture_control')}
|
||||
@@ -1317,7 +1151,7 @@ export function GeneralSettings() {
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-3 gap-5 pb-2">
|
||||
<div>
|
||||
<Typography bold>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-gesture_control-yawResetTracker'
|
||||
)}
|
||||
@@ -1331,21 +1165,7 @@ export function GeneralSettings() {
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Typography bold>
|
||||
{l10n.getString(
|
||||
'settings-general-gesture_control-fullResetTracker'
|
||||
)}
|
||||
</Typography>
|
||||
<Dropdown
|
||||
display="block"
|
||||
control={control}
|
||||
placeholder={''}
|
||||
name="tapDetection.fullResetTracker"
|
||||
items={bodyParts}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Typography bold>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-gesture_control-mountingResetTracker'
|
||||
)}
|
||||
@@ -1358,6 +1178,20 @@ export function GeneralSettings() {
|
||||
items={bodyParts}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-gesture_control-fullResetTracker'
|
||||
)}
|
||||
</Typography>
|
||||
<Dropdown
|
||||
display="block"
|
||||
control={control}
|
||||
placeholder={''}
|
||||
name="tapDetection.fullResetTracker"
|
||||
items={bodyParts}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-3 gap-5 pb-2">
|
||||
|
||||
@@ -6,11 +6,9 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeMagToggleRequestT,
|
||||
DeviceIdT,
|
||||
MagToggleRequestT,
|
||||
MagToggleResponseT,
|
||||
RpcMessage,
|
||||
TrackerIdT,
|
||||
} from 'solarxr-protocol';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
@@ -19,13 +17,11 @@ interface MagnetometerToggleForm {
|
||||
}
|
||||
|
||||
export function MagnetometerToggleSetting({
|
||||
trackerNum,
|
||||
deviceId,
|
||||
trackerId,
|
||||
settingType,
|
||||
id,
|
||||
}: {
|
||||
trackerNum?: number;
|
||||
deviceId?: number;
|
||||
trackerId?: number;
|
||||
settingType: 'general' | 'tracker';
|
||||
id?: string;
|
||||
}) {
|
||||
@@ -45,18 +41,14 @@ export function MagnetometerToggleSetting({
|
||||
if (originalValue.current === values.magToggle) return;
|
||||
setWaitingMag(true);
|
||||
const req = new ChangeMagToggleRequestT();
|
||||
if (trackerNum !== undefined) {
|
||||
const id = new TrackerIdT(
|
||||
deviceId ? new DeviceIdT(deviceId) : undefined,
|
||||
trackerNum
|
||||
);
|
||||
req.trackerId = id;
|
||||
if (trackerId !== undefined) {
|
||||
req.trackerId = trackerId;
|
||||
}
|
||||
|
||||
req.enable = values.magToggle;
|
||||
sendRPCPacket(RpcMessage.ChangeMagToggleRequest, req);
|
||||
},
|
||||
[trackerNum, deviceId]
|
||||
[trackerId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -66,25 +58,18 @@ export function MagnetometerToggleSetting({
|
||||
|
||||
useEffect(() => {
|
||||
const req = new MagToggleRequestT();
|
||||
if (trackerNum !== undefined) {
|
||||
const id = new TrackerIdT(
|
||||
deviceId ? new DeviceIdT(deviceId) : undefined,
|
||||
trackerNum
|
||||
);
|
||||
req.trackerId = id;
|
||||
if (trackerId !== undefined) {
|
||||
req.trackerId = trackerId;
|
||||
sendRPCPacket(RpcMessage.MagToggleRequest, new MagToggleRequestT());
|
||||
}
|
||||
sendRPCPacket(RpcMessage.MagToggleRequest, req);
|
||||
}, [trackerNum, deviceId]);
|
||||
}, [trackerId]);
|
||||
|
||||
useRPCPacket(RpcMessage.MagToggleResponse, (mag: MagToggleResponseT) => {
|
||||
if (trackerNum !== undefined && mag.trackerId?.trackerNum === undefined) {
|
||||
if (trackerId !== undefined && mag.trackerId === undefined) {
|
||||
setGlobalToggle(mag.enable);
|
||||
}
|
||||
if (
|
||||
mag.trackerId?.trackerNum !== trackerNum ||
|
||||
mag.trackerId?.deviceId?.id !== deviceId
|
||||
) {
|
||||
if (mag.trackerId !== trackerId) {
|
||||
return;
|
||||
}
|
||||
originalValue.current = mag.enable;
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
import { useEffect } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
OSCRouterSettingsT,
|
||||
OSCSettingsT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { RouterIcon } from '@/components/commons/icon/RouterIcon';
|
||||
import { Input } from '@/components/commons/Input';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import {
|
||||
SettingsPageLayout,
|
||||
SettingsPagePaneLayout,
|
||||
} from '@/components/settings/SettingsPageLayout';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { object } from 'yup';
|
||||
import {
|
||||
OSCSettings,
|
||||
useOscSettingsValidator,
|
||||
} from '@/hooks/osc-setting-validator';
|
||||
|
||||
interface OSCRouterSettingsForm {
|
||||
router: {
|
||||
oscSettings: OSCSettings;
|
||||
};
|
||||
}
|
||||
|
||||
const defaultValues = {
|
||||
router: {
|
||||
oscSettings: {
|
||||
enabled: false,
|
||||
portIn: 9002,
|
||||
portOut: 9000,
|
||||
address: '127.0.0.1',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export function OSCRouterSettings() {
|
||||
const { l10n } = useLocalization();
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const { oscValidator } = useOscSettingsValidator();
|
||||
|
||||
const { reset, control, watch, handleSubmit } =
|
||||
useForm<OSCRouterSettingsForm>({
|
||||
defaultValues: defaultValues,
|
||||
reValidateMode: 'onChange',
|
||||
mode: 'onChange',
|
||||
resolver: yupResolver(
|
||||
object({
|
||||
router: object({
|
||||
oscSettings: oscValidator,
|
||||
}),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
const onSubmit = (values: OSCRouterSettingsForm) => {
|
||||
const settings = new ChangeSettingsRequestT();
|
||||
|
||||
if (values.router) {
|
||||
const router = new OSCRouterSettingsT();
|
||||
|
||||
router.oscSettings = Object.assign(
|
||||
new OSCSettingsT(),
|
||||
values.router.oscSettings
|
||||
);
|
||||
|
||||
settings.oscRouter = router;
|
||||
}
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = watch(() => handleSubmit(onSubmit)());
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
const formData: OSCRouterSettingsForm = defaultValues;
|
||||
if (settings.oscRouter) {
|
||||
if (settings.oscRouter.oscSettings) {
|
||||
formData.router.oscSettings.enabled =
|
||||
settings.oscRouter.oscSettings.enabled;
|
||||
if (settings.oscRouter.oscSettings.portIn)
|
||||
formData.router.oscSettings.portIn =
|
||||
settings.oscRouter.oscSettings.portIn;
|
||||
if (settings.oscRouter.oscSettings.portOut)
|
||||
formData.router.oscSettings.portOut =
|
||||
settings.oscRouter.oscSettings.portOut;
|
||||
if (settings.oscRouter.oscSettings.address)
|
||||
formData.router.oscSettings.address =
|
||||
settings.oscRouter.oscSettings.address.toString();
|
||||
}
|
||||
|
||||
reset(formData);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<SettingsPageLayout>
|
||||
<form className="flex flex-col gap-2 w-full">
|
||||
<SettingsPagePaneLayout icon={<RouterIcon />} id="router">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-osc-router')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pt-2 pb-4">
|
||||
<>
|
||||
{l10n
|
||||
.getString('settings-osc-router-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-router-enable')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-router-enable-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="router.oscSettings.enabled"
|
||||
label={l10n.getString('settings-osc-router-enable-label')}
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-router-network')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<>
|
||||
{l10n
|
||||
.getString('settings-osc-router-network-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<Localized
|
||||
id="settings-osc-router-network-port_in"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="router.oscSettings.portIn"
|
||||
placeholder="9002"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
<Localized
|
||||
id="settings-osc-router-network-port_out"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="router.oscSettings.portOut"
|
||||
placeholder="9000"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-router-network-address')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-osc-router-network-address-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<Input
|
||||
type="text"
|
||||
control={control}
|
||||
name="router.oscSettings.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-router-network-address-placeholder'
|
||||
)}
|
||||
label=""
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
</form>
|
||||
</SettingsPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
import {useEffect, useRef, useState} from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
BodyPart,
|
||||
ChangeOutputTrackersSettingsRequestT, OutputTrackersSettingsResponseT,
|
||||
RpcMessage, SettingsResponseT, TapDetectionSettingsT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { FileInput } from '@/components/commons/FileInput';
|
||||
import { OutputTrackersIcon } from '@/components/commons/icon/OutputTrackersIcon';
|
||||
import { Input } from '@/components/commons/Input';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { magic } from '@/utils/formatting';
|
||||
import {
|
||||
SettingsPageLayout,
|
||||
SettingsPagePaneLayout,
|
||||
} from '@/components/settings/SettingsPageLayout';
|
||||
import { error } from '@/utils/logging';
|
||||
import {
|
||||
OSCPortsAddress,
|
||||
useOscPortsAddressValidator,
|
||||
} from '@/hooks/osc-setting-validator';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { boolean, object } from 'yup';
|
||||
import {atom, useAtomValue, useSetAtom} from "jotai";
|
||||
import {selectAtom} from "jotai/utils";
|
||||
import {isEqual} from "@react-hookz/deep-equal";
|
||||
|
||||
interface OutputTrackersSettingsForm {
|
||||
automaticTrackerToggle: boolean;
|
||||
waist: boolean;
|
||||
chest: boolean;
|
||||
leftFoot: boolean;
|
||||
rightFoot: boolean;
|
||||
leftKnee: boolean;
|
||||
rightKnee: boolean;
|
||||
leftElbow: boolean;
|
||||
rightElbow: boolean;
|
||||
leftHand: boolean;
|
||||
rightHand: boolean;
|
||||
sendDerivedVelocity: boolean;
|
||||
}
|
||||
|
||||
const defaultOutputTrackersSettings: OutputTrackersSettingsForm = {
|
||||
automaticTrackerToggle: true,
|
||||
waist: false,
|
||||
chest: false,
|
||||
leftFoot: false,
|
||||
rightFoot: false,
|
||||
leftElbow: false,
|
||||
rightElbow: false,
|
||||
leftHand: false,
|
||||
rightHand: false,
|
||||
leftKnee: false,
|
||||
rightKnee: false,
|
||||
sendDerivedVelocity: false,
|
||||
};
|
||||
|
||||
const settingsAtom = atom(new OutputTrackersSettingsResponseT());
|
||||
const settingsValueAtom = selectAtom(
|
||||
settingsAtom,
|
||||
(settings) => settings,
|
||||
isEqual
|
||||
);
|
||||
|
||||
export function OutputTrackersSettings() {
|
||||
const setSettings = useSetAtom(settingsAtom);
|
||||
const settings = useAtomValue(settingsValueAtom);
|
||||
const { l10n } = useLocalization();
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
|
||||
const { reset, control, watch, handleSubmit } = useForm<OutputTrackersSettingsForm>({
|
||||
defaultValues: defaultOutputTrackersSettings,
|
||||
reValidateMode: 'onChange',
|
||||
mode: 'onChange',
|
||||
resolver: yupResolver(
|
||||
object({
|
||||
automaticTrackerToggle: boolean().required(),
|
||||
waist: boolean().required(),
|
||||
chest: boolean().required(),
|
||||
leftFoot: boolean().required(),
|
||||
rightFoot: boolean().required(),
|
||||
leftKnee: boolean().required(),
|
||||
rightKnee: boolean().required(),
|
||||
leftElbow: boolean().required(),
|
||||
rightElbow: boolean().required(),
|
||||
leftHand: boolean().required(),
|
||||
rightHand: boolean().required(),
|
||||
sendDerivedVelocity: boolean().required(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
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 {
|
||||
trackers: { automaticTrackerToggle },
|
||||
} = watch();
|
||||
|
||||
const onSubmit = async (values: OutputTrackersSettingsForm) => {
|
||||
const req = new ChangeOutputTrackersSettingsRequestT();
|
||||
|
||||
// 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
|
||||
const enabledBodyParts: [boolean, BodyPart][] = [
|
||||
[values.waist, BodyPart.HIP],
|
||||
[values.chest, BodyPart.CHEST],
|
||||
[values.leftFoot, BodyPart.LEFT_FOOT],
|
||||
[values.rightFoot, BodyPart.RIGHT_FOOT],
|
||||
[values.leftKnee, BodyPart.LEFT_UPPER_LEG],
|
||||
[values.rightKnee, BodyPart.RIGHT_UPPER_LEG],
|
||||
[values.leftElbow, BodyPart.LEFT_UPPER_ARM],
|
||||
[values.rightElbow, BodyPart.RIGHT_UPPER_ARM],
|
||||
[values.leftHand, BodyPart.LEFT_HAND],
|
||||
[values.rightHand, BodyPart.RIGHT_HAND],
|
||||
];
|
||||
req.trackers = enabledBodyParts
|
||||
.filter(([enabled]) => enabled)
|
||||
.map(([, part]) => part);
|
||||
|
||||
// Hand warning
|
||||
if (
|
||||
!blockHandsWarning.current &&
|
||||
!showHandsWarning &&
|
||||
!settings?.trackers.includes(BodyPart.LEFT_HAND) &&
|
||||
!settings?.trackers.includes(BodyPart.RIGHT_HAND) &&
|
||||
(values.leftHand || values.rightHand)
|
||||
) {
|
||||
// We have just toggled on one of the hand trackers, show the user a warning
|
||||
setShowHandsWarning([values.leftHand, values.rightHand]);
|
||||
values.leftHand = false;
|
||||
values.rightHand = false;
|
||||
} else if (
|
||||
blockHandsWarning.current &&
|
||||
!values.leftHand && !values.rightHand
|
||||
) {
|
||||
// Both hand trackers have just been disabled, make sure the warning shows up
|
||||
// again next time the user toggles one back on
|
||||
blockHandsWarning.current = false;
|
||||
}
|
||||
|
||||
req.automaticTrackerToggle = values.automaticTrackerToggle;
|
||||
req.sendDerivedVelocity = values.sendDerivedVelocity;
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeOutputTrackersSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = watch(() => handleSubmit(onSubmit)());
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.OutputTrackersSettingsResponse, (settings: OutputTrackersSettingsResponseT) => {
|
||||
const formData: OutputTrackersSettingsForm = defaultOutputTrackersSettings;
|
||||
formData.automaticTrackerToggle = settings.automaticTrackerToggle;
|
||||
formData.sendDerivedVelocity = settings.sendDerivedVelocity;
|
||||
|
||||
reset(formData);
|
||||
});
|
||||
|
||||
return (
|
||||
<SettingsPageLayout>
|
||||
<form className="flex flex-col gap-2 w-full">
|
||||
<SettingsPagePaneLayout icon={<OutputTrackersIcon />} id="vmc">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-osc-vmc')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pt-2 pb-4">
|
||||
<>
|
||||
{l10n
|
||||
.getString('settings-osc-vmc-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-enable')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-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-vmc-enable-label')}
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-network')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<>
|
||||
{l10n
|
||||
.getString('settings-osc-vmc-network-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<Localized
|
||||
id="settings-osc-vmc-network-port_in"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="portsAddress.portIn"
|
||||
placeholder="9002"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
<Localized
|
||||
id="settings-osc-vmc-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-vmc-network-address')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-network-address-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<Input
|
||||
type="text"
|
||||
control={control}
|
||||
name="portsAddress.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-vmc-network-address-placeholder'
|
||||
)}
|
||||
label=""
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-vrm')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-vrm-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<OutputTrackersFileUpload />
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-anchor_hip')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-anchor_hip-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="anchorHip"
|
||||
label={l10n.getString('settings-osc-vmc-anchor_hip-label')}
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-mirror_tracking')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-mirror_tracking-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="mirrorTracking"
|
||||
label={l10n.getString('settings-osc-vmc-mirror_tracking-label')}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
</form>
|
||||
</SettingsPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -2,13 +2,13 @@ import { Localized, useLocalization } from '@fluent/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
ChangeVMCOSCSettingsRequestT,
|
||||
ChangeVRMSettingsRequestT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
OSCSettingsT,
|
||||
VMCOSCSettingsT,
|
||||
VRMSettingsT,
|
||||
VMCOSCSettingsRequestT,
|
||||
VMCOSCSettingsResponseT,
|
||||
VRMSettingsRequestT,
|
||||
VRMSettingsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
@@ -23,34 +23,31 @@ import {
|
||||
} from '@/components/settings/SettingsPageLayout';
|
||||
import { error } from '@/utils/logging';
|
||||
import {
|
||||
OSCSettings,
|
||||
useOscSettingsValidator,
|
||||
OSCPortsAddress,
|
||||
useOscPortsAddressValidator,
|
||||
} from '@/hooks/osc-setting-validator';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { boolean, object } from 'yup';
|
||||
|
||||
interface VMCSettingsForm {
|
||||
vmc: {
|
||||
oscSettings: OSCSettings;
|
||||
anchorHip: boolean;
|
||||
mirrorTracking: boolean;
|
||||
};
|
||||
enabled: boolean,
|
||||
portsAddress: OSCPortsAddress,
|
||||
anchorHip: boolean;
|
||||
mirrorTracking: boolean;
|
||||
}
|
||||
|
||||
const defaultValues = {
|
||||
vmc: {
|
||||
oscSettings: {
|
||||
enabled: false,
|
||||
portIn: 39540,
|
||||
portOut: 39539,
|
||||
address: '127.0.0.1',
|
||||
},
|
||||
anchorHip: true,
|
||||
mirrorTracking: true,
|
||||
const defaultVMCSettings: VMCSettingsForm = {
|
||||
enabled: false,
|
||||
portsAddress: {
|
||||
portIn: 39540,
|
||||
portOut: 39539,
|
||||
address: '127.0.0.1',
|
||||
},
|
||||
anchorHip: true,
|
||||
mirrorTracking: true,
|
||||
};
|
||||
|
||||
export function VMCFileUpload() {
|
||||
export function VRMFileUpload() {
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const { l10n } = useLocalization();
|
||||
const [modelName, setModelName] = useState<string | null>(null);
|
||||
@@ -66,22 +63,20 @@ export function VMCFileUpload() {
|
||||
const vrmJson = watch('vrmJson');
|
||||
|
||||
const updateVRMJson = async () => {
|
||||
const req = new ChangeSettingsRequestT();
|
||||
const vrm = new VRMSettingsT();
|
||||
const req = new ChangeVRMSettingsRequestT();
|
||||
if (vrmJson !== undefined) {
|
||||
if (vrmJson.length > 0) {
|
||||
const file = await parseVRMFile(vrmJson[0]);
|
||||
if (file) {
|
||||
vrm.vrmJson = file.json;
|
||||
req.vrmJson = file.json;
|
||||
setModelName(file.name);
|
||||
}
|
||||
} else {
|
||||
vrm.vrmJson = '';
|
||||
req.vrmJson = '';
|
||||
setModelName(null);
|
||||
}
|
||||
}
|
||||
req.vrm = vrm;
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
|
||||
sendRPCPacket(RpcMessage.ChangeVRMSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -89,11 +84,12 @@ export function VMCFileUpload() {
|
||||
}, [vrmJson]);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
sendRPCPacket(RpcMessage.VMCOSCSettingsRequest, new VMCOSCSettingsRequestT());
|
||||
sendRPCPacket(RpcMessage.VRMSettingsRequest, new VRMSettingsRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
const vrmJson = settings.vrm?.vrmJson?.toString();
|
||||
useRPCPacket(RpcMessage.VRMSettingsResponse, (settings: VRMSettingsResponseT) => {
|
||||
const vrmJson = settings.vrmJson?.toString();
|
||||
if (vrmJson) {
|
||||
let data: any;
|
||||
try {
|
||||
@@ -114,7 +110,7 @@ export function VMCFileUpload() {
|
||||
}}
|
||||
value="help"
|
||||
importedFileName={
|
||||
// if modelname is an empty string, it's an untitled model
|
||||
// if modelName is an empty string, it's an untitled model
|
||||
modelName === ''
|
||||
? l10n.getString('settings-osc-vmc-vrm-untitled_model')
|
||||
: modelName
|
||||
@@ -128,39 +124,33 @@ export function VMCFileUpload() {
|
||||
export function VMCSettings() {
|
||||
const { l10n } = useLocalization();
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const { oscValidator } = useOscSettingsValidator();
|
||||
const { oscValidator } = useOscPortsAddressValidator();
|
||||
|
||||
const { reset, control, watch, handleSubmit } = useForm<VMCSettingsForm>({
|
||||
defaultValues,
|
||||
defaultValues: defaultVMCSettings,
|
||||
reValidateMode: 'onChange',
|
||||
mode: 'onChange',
|
||||
resolver: yupResolver(
|
||||
object({
|
||||
vmc: object({
|
||||
oscSettings: oscValidator,
|
||||
anchorHip: boolean().required(),
|
||||
mirrorTracking: boolean().required(),
|
||||
}),
|
||||
enabled: boolean().required(),
|
||||
portsAddress: oscValidator,
|
||||
anchorHip: boolean().required(),
|
||||
mirrorTracking: boolean().required(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
const onSubmit = async (values: VMCSettingsForm) => {
|
||||
const settings = new ChangeSettingsRequestT();
|
||||
const req = new ChangeVMCOSCSettingsRequestT();
|
||||
|
||||
if (values.vmc) {
|
||||
const vmcOsc = new VMCOSCSettingsT();
|
||||
req.enabled = values.enabled
|
||||
req.portIn = values.portsAddress.portIn
|
||||
req.portOut = values.portsAddress.portOut
|
||||
req.address = values.portsAddress.address
|
||||
req.anchorHip = values.anchorHip;
|
||||
req.mirrorTracking = values.mirrorTracking;
|
||||
|
||||
vmcOsc.oscSettings = Object.assign(
|
||||
new OSCSettingsT(),
|
||||
values.vmc.oscSettings
|
||||
);
|
||||
vmcOsc.anchorHip = values.vmc.anchorHip;
|
||||
vmcOsc.mirrorTracking = values.vmc.mirrorTracking;
|
||||
|
||||
settings.vmcOsc = vmcOsc;
|
||||
}
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
|
||||
sendRPCPacket(RpcMessage.ChangeVMCOSCSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -168,27 +158,19 @@ export function VMCSettings() {
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
}, []);
|
||||
useRPCPacket(RpcMessage.VMCOSCSettingsResponse, (settings: VMCOSCSettingsResponseT) => {
|
||||
const formData: VMCSettingsForm = defaultVMCSettings;
|
||||
if (settings) {
|
||||
formData.enabled = settings.enabled;
|
||||
if (settings.portIn)
|
||||
formData.portsAddress.portIn = settings.portIn;
|
||||
if (settings.portOut)
|
||||
formData.portsAddress.portOut = settings.portOut;
|
||||
if (settings.address)
|
||||
formData.portsAddress.address = settings.address.toString();
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
const formData: VMCSettingsForm = defaultValues;
|
||||
if (settings.vmcOsc) {
|
||||
if (settings.vmcOsc.oscSettings) {
|
||||
formData.vmc.oscSettings.enabled = settings.vmcOsc.oscSettings.enabled;
|
||||
if (settings.vmcOsc.oscSettings.portIn)
|
||||
formData.vmc.oscSettings.portIn = settings.vmcOsc.oscSettings.portIn;
|
||||
if (settings.vmcOsc.oscSettings.portOut)
|
||||
formData.vmc.oscSettings.portOut =
|
||||
settings.vmcOsc.oscSettings.portOut;
|
||||
if (settings.vmcOsc.oscSettings.address)
|
||||
formData.vmc.oscSettings.address =
|
||||
settings.vmcOsc.oscSettings.address.toString();
|
||||
}
|
||||
|
||||
formData.vmc.anchorHip = settings.vmcOsc.anchorHip;
|
||||
formData.vmc.mirrorTracking = settings.vmcOsc.mirrorTracking;
|
||||
formData.anchorHip = settings.anchorHip;
|
||||
formData.mirrorTracking = settings.mirrorTracking;
|
||||
|
||||
reset(formData);
|
||||
}
|
||||
@@ -225,7 +207,7 @@ export function VMCSettings() {
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vmc.oscSettings.enabled"
|
||||
name="enabled"
|
||||
label={l10n.getString('settings-osc-vmc-enable-label')}
|
||||
/>
|
||||
</div>
|
||||
@@ -250,7 +232,7 @@ export function VMCSettings() {
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="vmc.oscSettings.portIn"
|
||||
name="portsAddress.portIn"
|
||||
placeholder="9002"
|
||||
label=""
|
||||
/>
|
||||
@@ -262,7 +244,7 @@ export function VMCSettings() {
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="vmc.oscSettings.portOut"
|
||||
name="portsAddress.portOut"
|
||||
placeholder="9000"
|
||||
label=""
|
||||
/>
|
||||
@@ -280,7 +262,7 @@ export function VMCSettings() {
|
||||
<Input
|
||||
type="text"
|
||||
control={control}
|
||||
name="vmc.oscSettings.address"
|
||||
name="portsAddress.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-vmc-network-address-placeholder'
|
||||
)}
|
||||
@@ -296,7 +278,7 @@ export function VMCSettings() {
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<VMCFileUpload />
|
||||
<VRMFileUpload />
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-anchor_hip')}
|
||||
@@ -311,7 +293,7 @@ export function VMCSettings() {
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vmc.anchorHip"
|
||||
name="anchorHip"
|
||||
label={l10n.getString('settings-osc-vmc-anchor_hip-label')}
|
||||
/>
|
||||
</div>
|
||||
@@ -328,7 +310,7 @@ export function VMCSettings() {
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vmc.mirrorTracking"
|
||||
name="mirrorTracking"
|
||||
label={l10n.getString('settings-osc-vmc-mirror_tracking-label')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,115 +1,387 @@
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
import { useEffect } from '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 {
|
||||
ChangeSettingsRequestT,
|
||||
OSCSettingsT,
|
||||
OSCTrackersSettingT,
|
||||
ChangeVRCOSCSettingsRequestT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
VRCOSCSettingsT,
|
||||
VRCOSCInputState,
|
||||
VRCOSCNetworkSettingsT,
|
||||
VRCOSCOscQueryState,
|
||||
VRCOSCOutputState,
|
||||
VRCOSCSettingsRequestT,
|
||||
VRCOSCSettingsResponseT,
|
||||
VRCOSCStatusChangeResponseT,
|
||||
VRCOSCStatusRequestT,
|
||||
VRCOSCTargetSource,
|
||||
type VRCOSCDiscoveredTargetT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { Button } from '@/components/commons/Button';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { VRCIcon } from '@/components/commons/icon/VRCIcon';
|
||||
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 { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { boolean, object } from 'yup';
|
||||
import {
|
||||
OSCSettings,
|
||||
useOscSettingsValidator,
|
||||
} from '@/hooks/osc-setting-validator';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import {OSCPortsAddress, useOscPortsAddressValidator} from "@/hooks/osc-setting-validator";
|
||||
|
||||
interface VRCOSCSettingsForm {
|
||||
vrchat: {
|
||||
oscSettings: OSCSettings;
|
||||
trackers: {
|
||||
head: boolean;
|
||||
chest: boolean;
|
||||
elbows: boolean;
|
||||
feet: boolean;
|
||||
knees: boolean;
|
||||
hands: boolean;
|
||||
waist: boolean;
|
||||
};
|
||||
oscqueryEnabled: boolean;
|
||||
};
|
||||
enabled: boolean;
|
||||
useManualNetwork: boolean;
|
||||
manualNetwork: OSCPortsAddress
|
||||
}
|
||||
|
||||
const defaultValues = {
|
||||
vrchat: {
|
||||
oscSettings: {
|
||||
enabled: false,
|
||||
portIn: 9001,
|
||||
portOut: 9000,
|
||||
address: '127.0.0.1',
|
||||
},
|
||||
trackers: {
|
||||
head: false,
|
||||
chest: false,
|
||||
elbows: false,
|
||||
feet: false,
|
||||
knees: false,
|
||||
hands: false,
|
||||
waist: false,
|
||||
},
|
||||
oscqueryEnabled: true,
|
||||
const defaultVRCOSCSettings: VRCOSCSettingsForm = {
|
||||
enabled: false,
|
||||
useManualNetwork: false,
|
||||
manualNetwork: {
|
||||
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 { oscValidator } = useOscSettingsValidator();
|
||||
const [status, setStatus] = useState<VRCOSCStatusChangeResponseT | null>(
|
||||
null
|
||||
);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
const { reset, control, watch, handleSubmit } = useForm<VRCOSCSettingsForm>({
|
||||
defaultValues,
|
||||
reValidateMode: 'onChange',
|
||||
mode: 'onChange',
|
||||
resolver: yupResolver(
|
||||
object({
|
||||
vrchat: object({
|
||||
oscSettings: oscValidator,
|
||||
trackers: object({
|
||||
head: boolean().required(),
|
||||
chest: boolean().required(),
|
||||
elbows: boolean().required(),
|
||||
feet: boolean().required(),
|
||||
knees: boolean().required(),
|
||||
hands: boolean().required(),
|
||||
waist: boolean().required(),
|
||||
}),
|
||||
oscqueryEnabled: boolean().required(),
|
||||
}),
|
||||
})
|
||||
),
|
||||
});
|
||||
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(),
|
||||
manualNetwork: 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 settings = new ChangeSettingsRequestT();
|
||||
const req = new ChangeVRCOSCSettingsRequestT();
|
||||
|
||||
if (values.vrchat) {
|
||||
const vrcOsc = new VRCOSCSettingsT();
|
||||
req.enabled = values.enabled;
|
||||
req.manualNetwork = values.useManualNetwork
|
||||
? Object.assign(new VRCOSCNetworkSettingsT(), values.manualNetwork)
|
||||
: null;
|
||||
|
||||
vrcOsc.oscSettings = Object.assign(
|
||||
new OSCSettingsT(),
|
||||
values.vrchat.oscSettings
|
||||
);
|
||||
vrcOsc.trackers = Object.assign(
|
||||
new OSCTrackersSettingT(),
|
||||
values.vrchat.trackers
|
||||
);
|
||||
vrcOsc.oscqueryEnabled = values.vrchat.oscqueryEnabled;
|
||||
|
||||
settings.vrcOsc = vrcOsc;
|
||||
}
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
|
||||
sendRPCPacket(RpcMessage.ChangeVRCOSCSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -118,34 +390,42 @@ export function VRCOSCSettings() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
sendRPCPacket(
|
||||
RpcMessage.VRCOSCSettingsRequest,
|
||||
new VRCOSCSettingsRequestT()
|
||||
);
|
||||
sendRPCPacket(RpcMessage.VRCOSCStatusRequest, new VRCOSCStatusRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
const formData: VRCOSCSettingsForm = defaultValues;
|
||||
if (settings.vrcOsc) {
|
||||
if (settings.vrcOsc.oscSettings) {
|
||||
formData.vrchat.oscSettings.enabled =
|
||||
settings.vrcOsc.oscSettings.enabled;
|
||||
if (settings.vrcOsc.oscSettings.portIn)
|
||||
formData.vrchat.oscSettings.portIn =
|
||||
settings.vrcOsc.oscSettings.portIn;
|
||||
if (settings.vrcOsc.oscSettings.portOut)
|
||||
formData.vrchat.oscSettings.portOut =
|
||||
settings.vrcOsc.oscSettings.portOut;
|
||||
if (settings.vrcOsc.oscSettings.address)
|
||||
formData.vrchat.oscSettings.address =
|
||||
settings.vrcOsc.oscSettings.address.toString();
|
||||
useRPCPacket(
|
||||
RpcMessage.VRCOSCSettingsResponse,
|
||||
(response: VRCOSCSettingsResponseT) => {
|
||||
const formData = defaultVRCOSCSettings;
|
||||
if (response) {
|
||||
formData.enabled = response.enabled;
|
||||
if (response.manualNetwork) {
|
||||
formData.useManualNetwork = true;
|
||||
formData.manualNetwork.portIn = response.manualNetwork.portIn;
|
||||
formData.manualNetwork.portOut =
|
||||
response.manualNetwork.portOut;
|
||||
if (response.manualNetwork.address) {
|
||||
formData.manualNetwork.address = asString(
|
||||
response.manualNetwork.address
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
reset(formData);
|
||||
}
|
||||
|
||||
if (settings.vrcOsc.trackers)
|
||||
formData.vrchat.trackers = settings.vrcOsc.trackers;
|
||||
|
||||
formData.vrchat.oscqueryEnabled = settings.vrcOsc.oscqueryEnabled;
|
||||
|
||||
reset(formData);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
useRPCPacket(
|
||||
RpcMessage.VRCOSCStatusChangeResponse,
|
||||
(response: VRCOSCStatusChangeResponseT) => {
|
||||
setStatus(response);
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageLayout>
|
||||
@@ -165,6 +445,7 @@ export function VRCOSCSettings() {
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-enable')}
|
||||
</Typography>
|
||||
@@ -178,146 +459,119 @@ export function VRCOSCSettings() {
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.oscSettings.enabled"
|
||||
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(
|
||||
'manualNetwork.address',
|
||||
asString(target.address),
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
setValue('manualNetwork.portOut', target.portOut, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-oscqueryEnabled')}
|
||||
{l10n.getString('settings-osc-vrchat-status-network-mode')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
{l10n
|
||||
.getString('settings-osc-vrchat-oscqueryEnabled-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-status-network-mode-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.oscqueryEnabled"
|
||||
name="useManualNetwork"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-oscqueryEnabled-label'
|
||||
'settings-osc-vrchat-status-network-mode-toggle'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-network')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vrchat-network-description-v1')}
|
||||
</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="vrchat.oscSettings.portIn"
|
||||
placeholder="9001"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
<Localized
|
||||
id="settings-osc-vrchat-network-port_out"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="vrchat.oscSettings.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="vrchat.oscSettings.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-vrchat-network-address-placeholder'
|
||||
)}
|
||||
label=""
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-network-trackers')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.chest"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-chest'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.waist"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-hip'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.knees"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-knees'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.feet"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-feet'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.elbows"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-elbows'
|
||||
)}
|
||||
/>
|
||||
</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="manualNetwork.portIn"
|
||||
placeholder="9001"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
<Localized
|
||||
id="settings-osc-vrchat-network-port_out"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="manualNetwork.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="manualNetwork.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-vrchat-network-address-placeholder'
|
||||
)}
|
||||
label=""
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
</form>
|
||||
|
||||
@@ -3,7 +3,6 @@ import { StayAlignedSettingsT } from 'solarxr-protocol';
|
||||
import { SettingsForm } from '@/components/settings/pages/GeneralSettings';
|
||||
import { Button } from '@/components/commons/Button';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcons';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { SettingsPagePaneLayout } from '@/components/settings/SettingsPageLayout';
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
@@ -17,6 +16,7 @@ import {
|
||||
StandingRelaxedPoseModal,
|
||||
} from './StayAlignedPoseModal';
|
||||
import { useState } from 'react';
|
||||
import { HorizontalAlignIcon } from '@/components/commons/icon/HorizontalAlignIcon';
|
||||
|
||||
export type StayAlignedSettingsForm = {
|
||||
enabled: boolean;
|
||||
@@ -177,7 +177,7 @@ export function StayAlignedSettings({
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsPagePaneLayout icon={<WrenchIcon />} id="stayaligned">
|
||||
<SettingsPagePaneLayout icon={<HorizontalAlignIcon />} id="stayaligned">
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-stay_aligned')}
|
||||
</Typography>
|
||||
|
||||
@@ -85,7 +85,6 @@ export function TrackerSettingsPage() {
|
||||
);
|
||||
assignreq.bodyPosition = tracker?.tracker.info?.bodyPart || BodyPart.NONE;
|
||||
assignreq.trackerId = tracker?.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
setSelectRotation(false);
|
||||
};
|
||||
@@ -96,7 +95,6 @@ export function TrackerSettingsPage() {
|
||||
const assignreq = new AssignTrackerRequestT();
|
||||
assignreq.bodyPosition = role;
|
||||
assignreq.trackerId = tracker?.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
setSelectBodypart(false);
|
||||
};
|
||||
@@ -116,7 +114,6 @@ export function TrackerSettingsPage() {
|
||||
|
||||
assignreq.displayName = trackerName ?? null;
|
||||
assignreq.trackerId = tracker?.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
};
|
||||
|
||||
@@ -509,8 +506,7 @@ export function TrackerSettingsPage() {
|
||||
MagnetometerStatus.NOT_SUPPORTED && (
|
||||
<MagnetometerToggleSetting
|
||||
settingType="tracker"
|
||||
trackerNum={tracker.tracker.trackerId?.trackerNum}
|
||||
deviceId={tracker.tracker.trackerId?.deviceId?.id}
|
||||
trackerId={tracker.tracker.trackerId}
|
||||
/>
|
||||
)}
|
||||
<div className="flex flex-col gap-2 w-full mt-3 sentry-mask">
|
||||
|
||||
@@ -186,8 +186,8 @@ function Row({
|
||||
const warning =
|
||||
!!highlightedTrackers?.trackers.find(
|
||||
(t) =>
|
||||
t?.deviceId?.id === tracker.trackerId?.deviceId?.id &&
|
||||
t?.trackerNum === tracker.trackerId?.trackerNum
|
||||
t?.deviceId?.id === tracker.deviceId &&
|
||||
t?.trackerNum === tracker.trackerId
|
||||
) && highlightedTrackers.step;
|
||||
|
||||
return (
|
||||
|
||||
@@ -6,16 +6,13 @@ import {
|
||||
} from '@/hooks/tracking-checklist';
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
EnableSteamVRDriverRequestT,
|
||||
ResetType,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
SteamVRTrackersSettingT,
|
||||
TrackingChecklistPublicNetworksT,
|
||||
TrackingChecklistSteamVRDisconnectedT,
|
||||
TrackingChecklistStepId,
|
||||
BodyPart, ChangeOutputTrackersSettingsRequestT, OutputTrackersSettingsResponseT, OutputTrackersSettingsRequestT,
|
||||
} from 'solarxr-protocol';
|
||||
import { ReactNode, useEffect, useMemo, useState } from 'react';
|
||||
import { CheckIcon } from '@/components/commons/icon/CheckIcon';
|
||||
@@ -31,7 +28,7 @@ import {
|
||||
ArrowRightIcon,
|
||||
} from '@/components/commons/icon/ArrowIcons';
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcons';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcon';
|
||||
import { TrackingChecklistModal } from './TrackingChecklistModal';
|
||||
import { NavLink, useNavigate } from 'react-router-dom';
|
||||
import { useBreakpoint } from '@/hooks/breakpoint';
|
||||
@@ -176,36 +173,33 @@ function SteamVRDisconnected({
|
||||
function SteamVRHandsEnabled() {
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const [steamVrTrackers, setSteamVrTrackers] = useState<Omit<
|
||||
SteamVRTrackersSettingT,
|
||||
ChangeOutputTrackersSettingsRequestT,
|
||||
'pack'
|
||||
> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
sendRPCPacket(RpcMessage.OutputTrackersSettingsRequest, new OutputTrackersSettingsRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
if (settings.steamVrTrackers) {
|
||||
setSteamVrTrackers(settings.steamVrTrackers);
|
||||
useRPCPacket(RpcMessage.OutputTrackersSettingsResponse, (settings: OutputTrackersSettingsResponseT) => {
|
||||
if (settings.trackers) {
|
||||
setSteamVrTrackers(settings);
|
||||
}
|
||||
});
|
||||
|
||||
const disableHandTrackers = () => {
|
||||
const settings = new ChangeSettingsRequestT();
|
||||
settings.steamVrTrackers = new SteamVRTrackersSettingT(
|
||||
steamVrTrackers?.waist,
|
||||
steamVrTrackers?.chest,
|
||||
steamVrTrackers?.automaticTrackerToggle,
|
||||
steamVrTrackers?.leftFoot,
|
||||
steamVrTrackers?.rightFoot,
|
||||
steamVrTrackers?.leftKnee,
|
||||
steamVrTrackers?.rightKnee,
|
||||
steamVrTrackers?.leftElbow,
|
||||
steamVrTrackers?.rightElbow,
|
||||
false,
|
||||
false
|
||||
);
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
|
||||
const req = new ChangeOutputTrackersSettingsRequestT();
|
||||
|
||||
const newTrackers = steamVrTrackers?.trackers.filter(tracker =>
|
||||
tracker != BodyPart.LEFT_HAND && tracker != BodyPart.RIGHT_HAND
|
||||
)
|
||||
if (newTrackers !== undefined) {
|
||||
req.trackers = newTrackers
|
||||
}
|
||||
req.automaticTrackerToggle = steamVrTrackers?.automaticTrackerToggle === true
|
||||
req.sendDerivedVelocity = steamVrTrackers?.sendDerivedVelocity === true
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeOutputTrackersSettingsRequest, req);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -299,7 +293,7 @@ const stepContentLookup: Record<
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex">
|
||||
<ResetButton type={ResetType.Full} />
|
||||
<ResetButton type={ResetType.FULL} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -391,7 +385,7 @@ const stepContentLookup: Record<
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-between sm:items-center gap-1 flex-col sm:flex-row">
|
||||
<ResetButton type={ResetType.Mounting} group="default" />
|
||||
<ResetButton type={ResetType.MOUNTING} group="default" />
|
||||
{step.ignorable && (
|
||||
<Button
|
||||
id="tracking_checklist-ignore"
|
||||
@@ -428,7 +422,7 @@ const stepContentLookup: Record<
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between sm:items-center gap-1 flex-col sm:flex-row">
|
||||
<ResetButton type={ResetType.Mounting} group="feet" />
|
||||
<ResetButton type={ResetType.MOUNTING} group="feet" />
|
||||
{step.ignorable && (
|
||||
<Button
|
||||
id="tracking_checklist-ignore"
|
||||
|
||||
@@ -234,10 +234,7 @@ function IMUVisualizerCanvas({
|
||||
export function IMUVisualizerWidget({ tracker }: { tracker: TrackerDataT }) {
|
||||
const { l10n } = useLocalization();
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const isExtension = useMemo(
|
||||
() => (tracker.trackerId?.trackerNum ?? 0) > 0,
|
||||
[tracker]
|
||||
);
|
||||
const isExtension = false // TODO Do we want to display extensions?
|
||||
|
||||
useEffect(() => {
|
||||
const state = localStorage.getItem('modelPreview');
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { KeyValuesT, MessageT, Payload, Topic } from 'solarxr-protocol';
|
||||
import {
|
||||
OVERLAY_DISPLAY_SETTINGS_TOPIC,
|
||||
PayloadData,
|
||||
usePubSub,
|
||||
} from '@/hooks/pubSub';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
|
||||
export function OverlayWidget() {
|
||||
const { l10n } = useLocalization();
|
||||
const { publish, subscribe, keyValues } = usePubSub();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const { reset, control, handleSubmit, watch } = useForm<{
|
||||
isVisible: boolean;
|
||||
isMirrored: boolean;
|
||||
}>({
|
||||
defaultValues: {
|
||||
isVisible: false,
|
||||
isMirrored: false,
|
||||
},
|
||||
});
|
||||
|
||||
subscribe(
|
||||
OVERLAY_DISPLAY_SETTINGS_TOPIC,
|
||||
(payload: PayloadData, type: Payload) => {
|
||||
setLoading(false);
|
||||
if (type !== Payload.KeyValues) throw new Error('Invalid payload');
|
||||
const obj = keyValues(payload);
|
||||
reset({
|
||||
isMirrored: obj['is_mirrored'] === 'true',
|
||||
isVisible: obj['is_visible'] === 'true',
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const message = new MessageT();
|
||||
message.topic = OVERLAY_DISPLAY_SETTINGS_TOPIC;
|
||||
message.topicType = Topic.TopicId;
|
||||
message.payloadType = Payload.NONE;
|
||||
publish(message);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = watch(() => handleSubmit(onSubmit)());
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
const onSubmit = (val: { isVisible: boolean; isMirrored: boolean }) => {
|
||||
const message = new MessageT();
|
||||
|
||||
message.topic = OVERLAY_DISPLAY_SETTINGS_TOPIC;
|
||||
message.topicType = Topic.TopicId;
|
||||
|
||||
message.payloadType = Payload.KeyValues;
|
||||
const keyValues = new KeyValuesT();
|
||||
keyValues.keys = ['is_mirrored', 'is_visible'];
|
||||
keyValues.values = [`${val.isMirrored}`, `${val.isVisible}`];
|
||||
message.payload = keyValues;
|
||||
|
||||
publish(message);
|
||||
};
|
||||
|
||||
return !loading ? (
|
||||
<form className="bg-background-60 flex flex-col w-full rounded-md px-2">
|
||||
<div className="mt-2 px-1">
|
||||
<Typography>{l10n.getString('widget-overlay')}</Typography>
|
||||
</div>
|
||||
<CheckBox
|
||||
control={control}
|
||||
name="isVisible"
|
||||
variant="toggle"
|
||||
label={l10n.getString('widget-overlay-is_visible_label')}
|
||||
/>
|
||||
<CheckBox
|
||||
control={control}
|
||||
name="isMirrored"
|
||||
variant="toggle"
|
||||
label={l10n.getString('widget-overlay-is_mirrored_label')}
|
||||
/>
|
||||
</form>
|
||||
) : (
|
||||
<></>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import {
|
||||
SkeletonConfigResponseT,
|
||||
SkeletonBone,
|
||||
RpcMessage,
|
||||
SkeletonConfigRequestT,
|
||||
ChangeSkeletonConfigRequestT,
|
||||
ChangeSkeletonProportionsRequestT,
|
||||
SkeletonProportionsRequestT,
|
||||
SkeletonProportionsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
@@ -60,7 +60,7 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
const { useRPCPacket, sendRPCPacket } = useWebsocketAPI();
|
||||
const { setConfig } = useConfig();
|
||||
const [skeleton, setSkeleton] = useState<Omit<
|
||||
SkeletonConfigResponseT,
|
||||
SkeletonProportionsResponseT,
|
||||
'pack'
|
||||
> | null>(null);
|
||||
const bodyPartsGrouped: Label[] = useMemo(() => {
|
||||
@@ -121,12 +121,12 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
];
|
||||
}, [skeleton, type]);
|
||||
|
||||
useRPCPacket(RpcMessage.SkeletonConfigResponse, (data: SkeletonConfigResponseT) => {
|
||||
useRPCPacket(RpcMessage.SkeletonProportionsResponse, (data: SkeletonProportionsResponseT) => {
|
||||
setSkeleton(data);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SkeletonConfigRequest, new SkeletonConfigRequestT());
|
||||
sendRPCPacket(RpcMessage.SkeletonProportionsRequest, new SkeletonProportionsRequestT());
|
||||
}, []);
|
||||
|
||||
return {
|
||||
@@ -144,8 +144,8 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
if (!currentValue) throw 'invalid state - the bone should exists';
|
||||
const currentRatio = currentValue.value / oldGroupTotal;
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSkeletonConfigRequest,
|
||||
new ChangeSkeletonConfigRequestT(part, params.newValue * currentRatio)
|
||||
RpcMessage.ChangeSkeletonProportionsRequest,
|
||||
new ChangeSkeletonProportionsRequestT(part, params.newValue * currentRatio)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -164,8 +164,8 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
newValue = 0;
|
||||
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSkeletonConfigRequest,
|
||||
new ChangeSkeletonConfigRequestT(params.bone, newValue)
|
||||
RpcMessage.ChangeSkeletonProportionsRequest,
|
||||
new ChangeSkeletonProportionsRequestT(params.bone, newValue)
|
||||
);
|
||||
|
||||
// Update percent from other bones ratios so the total stays 100%
|
||||
@@ -177,8 +177,8 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
const currentValue = skeleton.skeletonParts.find(({ bone }) => bone === part);
|
||||
if (!currentValue) throw 'invalid state - the bone should exists';
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSkeletonConfigRequest,
|
||||
new ChangeSkeletonConfigRequestT(
|
||||
RpcMessage.ChangeSkeletonProportionsRequest,
|
||||
new ChangeSkeletonProportionsRequestT(
|
||||
part,
|
||||
currentValue.value - (diffValue / (group.length - 1)) * signDiff
|
||||
)
|
||||
@@ -188,11 +188,11 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
|
||||
if (params.type === 'bone') {
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSkeletonConfigRequest,
|
||||
new ChangeSkeletonConfigRequestT(params.bone, params.newValue)
|
||||
RpcMessage.ChangeSkeletonProportionsRequest,
|
||||
new ChangeSkeletonProportionsRequestT(params.bone, params.newValue)
|
||||
);
|
||||
}
|
||||
sendRPCPacket(RpcMessage.SkeletonConfigRequest, new SkeletonConfigRequestT());
|
||||
sendRPCPacket(RpcMessage.SkeletonProportionsRequest, new SkeletonProportionsRequestT());
|
||||
setConfig({ lastUsedProportions: 'manual' });
|
||||
Sentry.metrics.count('manual_proportions_change', 1, { attributes: params });
|
||||
},
|
||||
|
||||
+13
-12
@@ -11,15 +11,16 @@ import { useLocation } from 'react-router-dom';
|
||||
import { useConfig } from './config';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
import {
|
||||
ChangeResetsSettingsRequestT,
|
||||
ChangeSettingsRequestT,
|
||||
ModelSettingsT,
|
||||
ModelTogglesT,
|
||||
OSCSettingsT,
|
||||
ResetsSettingsT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
SkeletonBone,
|
||||
VRCOSCSettingsRequestT,
|
||||
VRCOSCSettingsT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useManualProportions } from './manual-proportions';
|
||||
@@ -80,6 +81,7 @@ export function useProvideOnboarding() {
|
||||
|
||||
const { state: locatioState } = useLocation();
|
||||
const [settings, setSettings] = useState<SettingsResponseT>();
|
||||
const [vrcOscSettings, setVrcOscSettings] = useState<VRCOSCSettingsT>();
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const { alonePage = false }: { alonePage?: boolean } = (locatioState as any) || {};
|
||||
@@ -90,11 +92,15 @@ export function useProvideOnboarding() {
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
sendRPCPacket(RpcMessage.VRCOSCSettingsRequest, new VRCOSCSettingsRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
setSettings(settings);
|
||||
});
|
||||
useRPCPacket(RpcMessage.VRCOSCSettingsResponse, (settings: VRCOSCSettingsT) => {
|
||||
setVrcOscSettings(settings);
|
||||
});
|
||||
|
||||
const { changeBoneValue } = useManualProportions({
|
||||
type: 'linear',
|
||||
@@ -102,10 +108,8 @@ export function useProvideOnboarding() {
|
||||
|
||||
const onboardingEnded = () => {
|
||||
setConfig({ doneOnboarding: true });
|
||||
if (!settings?.modelSettings || !settings?.vrcOsc) return;
|
||||
const req = new ChangeSettingsRequestT();
|
||||
if (!settings?.modelSettings || !vrcOscSettings) return;
|
||||
const modelSettings = new ModelSettingsT();
|
||||
const oscSettings = new VRCOSCSettingsT();
|
||||
|
||||
const mocap = usage === 'mocap' || usage === 'vtubing';
|
||||
|
||||
@@ -114,16 +118,13 @@ export function useProvideOnboarding() {
|
||||
modelSettings.toggles = toggles;
|
||||
req.modelSettings = modelSettings;
|
||||
|
||||
const resets = Object.assign(new ResetsSettingsT(), settings.resetsSettings);
|
||||
resets.resetHmdPitch = mocapPos === 'forehead';
|
||||
req.resetsSettings = resets;
|
||||
const resetsReq = Object.assign(new ChangeResetsSettingsRequestT(), settings.resetsSettings); // TODO
|
||||
resetsReq.resetHmdPitch = mocapPos === 'forehead';
|
||||
sendRPCPacket(RpcMessage.ChangeResetsSettingsRequest, resetsReq);
|
||||
|
||||
const osc = Object.assign(new OSCSettingsT(), settings.vrcOsc.oscSettings);
|
||||
const osc = Object.assign(new VRCOSCSettingsT(), vrcOscSettings);
|
||||
osc.enabled = vrcOsc ?? false;
|
||||
oscSettings.oscSettings = osc;
|
||||
req.vrcOsc = oscSettings;
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
|
||||
sendRPCPacket(RpcMessage.ChangeVRCOSCSettingsRequest, osc);
|
||||
|
||||
if (mocap) {
|
||||
changeBoneValue({ bone: SkeletonBone.HAND_Z, type: 'bone', newValue: 0 });
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { number, object, boolean, string } from 'yup';
|
||||
|
||||
export type OSCSettings = {
|
||||
enabled: boolean;
|
||||
export type OSCPortsAddress = {
|
||||
portIn: number;
|
||||
portOut: number;
|
||||
address: string;
|
||||
};
|
||||
|
||||
export function useOscSettingsValidator() {
|
||||
export function useOscPortsAddressValidator() {
|
||||
const bannedPorts = [6969, 21110];
|
||||
const { l10n } = useLocalization();
|
||||
|
||||
@@ -17,7 +16,7 @@ export function useOscSettingsValidator() {
|
||||
.required()
|
||||
.test(
|
||||
'ports-dont-match',
|
||||
l10n.getString('settings-osc-common-network-ports_match_error'),
|
||||
l10n.getString('settings-osc-common-network-ports_match_error-v2'),
|
||||
(port, context) => context.parent.portIn != context.parent.portOut
|
||||
)
|
||||
.notOneOf(bannedPorts, (context) =>
|
||||
@@ -27,7 +26,6 @@ export function useOscSettingsValidator() {
|
||||
);
|
||||
|
||||
const oscValidator = object({
|
||||
enabled: boolean().required(),
|
||||
portIn: portValidator,
|
||||
portOut: portValidator,
|
||||
address: string()
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
KeyValuesT,
|
||||
MessageT,
|
||||
PubSubUnion,
|
||||
SubscriptionRequestT,
|
||||
Topic,
|
||||
TopicHandleT,
|
||||
TopicIdT,
|
||||
TopicMappingT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
|
||||
export type PayloadData = MessageT['payload'];
|
||||
export type PayloadType = MessageT['payloadType'];
|
||||
|
||||
export function usePubSub() {
|
||||
const { sendPubSubPacket, usePubSubPacket } = useWebsocketAPI();
|
||||
const [handleTopics, setHandleTopics] = useState<{ [key: number]: TopicIdT }>({});
|
||||
|
||||
const subscribe = (
|
||||
topicId: TopicIdT,
|
||||
callback: (data: PayloadData, type: PayloadType) => void
|
||||
): void => {
|
||||
useEffect(() => {
|
||||
const subRequest = new SubscriptionRequestT();
|
||||
subRequest.topicType = Topic.TopicId;
|
||||
subRequest.topic = topicId;
|
||||
sendPubSubPacket(PubSubUnion.SubscriptionRequest, subRequest);
|
||||
}, [sendPubSubPacket, usePubSubPacket]);
|
||||
|
||||
usePubSubPacket(PubSubUnion.Message, (message: MessageT) => {
|
||||
if (message.topicType == Topic.TopicHandle) {
|
||||
const messageHandleId = message.topic as TopicHandleT;
|
||||
if (handleTopics[messageHandleId.id]) {
|
||||
callback(message.payload, message.payloadType);
|
||||
}
|
||||
}
|
||||
if (message.topicType == Topic.TopicId) {
|
||||
const messageTopicId = message.topic as TopicIdT;
|
||||
if (
|
||||
messageTopicId.appName === topicId.appName &&
|
||||
messageTopicId.organization === topicId.organization &&
|
||||
messageTopicId.topic === topicId.topic
|
||||
) {
|
||||
callback(message.payload, message.payloadType);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
usePubSubPacket(PubSubUnion.TopicMapping, (data: TopicMappingT) => {
|
||||
setHandleTopics((handleTopics) => ({
|
||||
...handleTopics,
|
||||
...(data.handle?.id && data.id ? { [data.handle?.id]: data.id } : {}),
|
||||
}));
|
||||
});
|
||||
|
||||
const publish = (message: MessageT) => {
|
||||
sendPubSubPacket(PubSubUnion.Message, message);
|
||||
};
|
||||
|
||||
return {
|
||||
subscribe,
|
||||
publish,
|
||||
keyValues: (payload: PayloadData): Record<string, string> => {
|
||||
const keyValuesPayload = payload as KeyValuesT;
|
||||
return keyValuesPayload.keys.reduce(
|
||||
(curr, _, index) => ({
|
||||
...curr,
|
||||
[keyValuesPayload.keys[index]]: keyValuesPayload.values[index],
|
||||
}),
|
||||
{}
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const topic = ({ appName, organization, topic }: Omit<TopicIdT, 'pack'>) =>
|
||||
Object.assign(new TopicIdT(), { appName, organization, topic });
|
||||
|
||||
export const OVERLAY_DISPLAY_SETTINGS_TOPIC = topic({
|
||||
appName: 'overlay',
|
||||
organization: 'slimevr.dev',
|
||||
topic: 'display_settings',
|
||||
});
|
||||
@@ -1,16 +1,14 @@
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
ResetsSettingsT,
|
||||
ResetsSettingsResponseT,
|
||||
RpcMessage,
|
||||
SettingsResetRequestT,
|
||||
SettingsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
import { useEffect, useState } from 'react';
|
||||
import {useWebsocketAPI} from './websocket-api';
|
||||
import {useEffect, useState} from 'react';
|
||||
|
||||
export interface ResetSettingsForm {
|
||||
resetMountingFeet: boolean;
|
||||
armsMountingResetMode: number;
|
||||
armsResetMode: number;
|
||||
yawResetSmoothTime: number;
|
||||
saveMountingReset: boolean;
|
||||
resetHmdPitch: boolean;
|
||||
@@ -18,16 +16,16 @@ export interface ResetSettingsForm {
|
||||
|
||||
export const defaultResetSettings = {
|
||||
resetMountingFeet: false,
|
||||
armsMountingResetMode: 0,
|
||||
armsResetMode: 0,
|
||||
yawResetSmoothTime: 0.0,
|
||||
saveMountingReset: false,
|
||||
resetHmdPitch: false,
|
||||
};
|
||||
|
||||
export function loadResetSettings(resetSettingsForm: ResetSettingsForm) {
|
||||
const resetsSettings = new ResetsSettingsT();
|
||||
const resetsSettings = new ResetsSettingsResponseT();
|
||||
resetsSettings.resetMountingFeet = resetSettingsForm.resetMountingFeet;
|
||||
resetsSettings.armsMountingResetMode = resetSettingsForm.armsMountingResetMode;
|
||||
resetsSettings.armsResetMode = resetSettingsForm.armsResetMode;
|
||||
resetsSettings.yawResetSmoothTime = resetSettingsForm.yawResetSmoothTime;
|
||||
resetsSettings.saveMountingReset = resetSettingsForm.saveMountingReset;
|
||||
resetsSettings.resetHmdPitch = resetSettingsForm.resetHmdPitch;
|
||||
@@ -40,19 +38,17 @@ export function useResetSettings() {
|
||||
const [settings, setSettings] = useState<ResetSettingsForm>(defaultResetSettings);
|
||||
|
||||
useEffect(() =>
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsResetRequestT())
|
||||
sendRPCPacket(RpcMessage.ResetsSettingsRequest, new SettingsResetRequestT())
|
||||
);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
if (settings.resetsSettings) setSettings(settings.resetsSettings);
|
||||
useRPCPacket(RpcMessage.ResetsSettingsResponse, (settings: ResetsSettingsResponseT) => {
|
||||
if (settings) setSettings(settings);
|
||||
});
|
||||
|
||||
return {
|
||||
update: (resetSettingsForm: Partial<ResetSettingsForm>) => {
|
||||
const req = new ChangeSettingsRequestT();
|
||||
const res = loadResetSettings({ ...settings, ...resetSettingsForm });
|
||||
req.resetsSettings = res;
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
|
||||
const req = loadResetSettings({...settings, ...resetSettingsForm});
|
||||
sendRPCPacket(RpcMessage.ChangeResetsSettingsRequest, req);
|
||||
},
|
||||
};
|
||||
}
|
||||
+22
-11
@@ -18,8 +18,8 @@ export type ResetBtnStatus = 'idle' | 'counting' | 'finished';
|
||||
|
||||
export type MountingResetGroup = 'default' | 'feet' | 'fingers';
|
||||
export type UseResetOptions =
|
||||
| { type: ResetType.Full | ResetType.Yaw }
|
||||
| { type: ResetType.Mounting; group: MountingResetGroup };
|
||||
| { type: ResetType.FULL | ResetType.YAW }
|
||||
| { type: ResetType.MOUNTING; group: MountingResetGroup };
|
||||
|
||||
export const BODY_PARTS_GROUPS: Record<MountingResetGroup, BodyPart[]> = {
|
||||
default: [],
|
||||
@@ -32,7 +32,7 @@ export function useReset(
|
||||
onReseted?: () => void,
|
||||
onFailed?: () => void
|
||||
) {
|
||||
if (options.type === ResetType.Mounting && !options.group) options.group = 'default';
|
||||
if (options.type === ResetType.MOUNTING && !options.group) options.group = 'default';
|
||||
|
||||
const serverGuards = useAtomValue(serverGuardsAtom);
|
||||
const { currentLocales } = useLocaleConfig();
|
||||
@@ -48,12 +48,23 @@ export function useReset(
|
||||
const req = new ResetRequestT();
|
||||
req.resetType = options.type;
|
||||
req.bodyParts = parts;
|
||||
switch (options.type) {
|
||||
case ResetType.YAW:
|
||||
req.delay = 0;
|
||||
break;
|
||||
case ResetType.FULL:
|
||||
req.delay = 3;
|
||||
break;
|
||||
case ResetType.MOUNTING:
|
||||
req.delay = 3;
|
||||
break;
|
||||
}
|
||||
sendRPCPacket(RpcMessage.ResetRequest, req);
|
||||
|
||||
Sentry.metrics.count('reset_click', 1, {
|
||||
attributes: {
|
||||
resetType: ResetType[options.type],
|
||||
group: options.type === ResetType.Mounting ? options.group : undefined,
|
||||
group: options.type === ResetType.MOUNTING ? options.group : undefined,
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -91,7 +102,7 @@ export function useReset(
|
||||
({ status, resetType, progress, duration, bodyParts }: ResetResponseT) => {
|
||||
if (
|
||||
resetType !== options.type ||
|
||||
(resetType == ResetType.Mounting &&
|
||||
(resetType == ResetType.MOUNTING &&
|
||||
JSON.stringify(parts) !== JSON.stringify(bodyParts))
|
||||
) {
|
||||
onResetCanceled();
|
||||
@@ -113,11 +124,11 @@ export function useReset(
|
||||
|
||||
const name = useMemo(() => {
|
||||
switch (options.type) {
|
||||
case ResetType.Yaw:
|
||||
case ResetType.YAW:
|
||||
return 'reset-yaw';
|
||||
case ResetType.Full:
|
||||
case ResetType.FULL:
|
||||
return 'reset-full';
|
||||
case ResetType.Mounting:
|
||||
case ResetType.MOUNTING:
|
||||
if (options.group !== 'default') return `reset-mounting-${options.group}`;
|
||||
return 'reset-mounting';
|
||||
default:
|
||||
@@ -127,7 +138,7 @@ export function useReset(
|
||||
|
||||
let disabled = status === 'counting';
|
||||
let error = null;
|
||||
if (options.type === ResetType.Mounting && options.group !== 'default') {
|
||||
if (options.type === ResetType.MOUNTING && options.group !== 'default') {
|
||||
const assignedTrackers = useAtomValue(assignedTrackersAtom);
|
||||
|
||||
if (
|
||||
@@ -140,10 +151,10 @@ export function useReset(
|
||||
disabled = true;
|
||||
error = `reset-error-no_${options.group}_tracker`;
|
||||
}
|
||||
} else if (options.type === ResetType.Mounting && !serverGuards?.canDoMounting) {
|
||||
} else if (options.type === ResetType.MOUNTING && !serverGuards?.canDoMountingReset) {
|
||||
disabled = true;
|
||||
error = 'reset-error-mounting-need_full_reset';
|
||||
} else if (options.type === ResetType.Yaw && !serverGuards?.canDoYawReset) {
|
||||
} else if (options.type === ResetType.YAW && !serverGuards?.canDoYawReset) {
|
||||
disabled = true;
|
||||
error = 'reset-error-yaw-need_full_reset';
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
TrackingChecklistStepVisibility,
|
||||
IgnoreTrackingChecklistStepRequestT,
|
||||
RpcMessage,
|
||||
TrackerIdT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
|
||||
@@ -47,7 +46,7 @@ export type TrackingChecklistStep = TrackingChecklistStepT & {
|
||||
};
|
||||
export type highlightedTrackers = {
|
||||
step: TrackingChecklistStep;
|
||||
trackers: Array<TrackerIdT>;
|
||||
trackers: Array<number>;
|
||||
};
|
||||
|
||||
const stepVisibility = ({ visibility, status, firstRequired }: TrackingChecklistStep) =>
|
||||
|
||||
@@ -5,8 +5,6 @@ import {
|
||||
DataFeedMessageHeaderT,
|
||||
MessageBundle,
|
||||
MessageBundleT,
|
||||
PubSubHeaderT,
|
||||
PubSubUnion,
|
||||
RpcMessage,
|
||||
RpcMessageHeaderT,
|
||||
} from 'solarxr-protocol';
|
||||
@@ -24,22 +22,17 @@ export interface WebSocketApi {
|
||||
useDataFeedPacket: <T>(type: DataFeedMessage, callback: (packet: T) => void) => void;
|
||||
sendRPCPacket: (type: RpcMessage, data: RPCPacketType) => void;
|
||||
sendDataFeedPacket: (type: DataFeedMessage, data: DataFeedPacketType) => void;
|
||||
usePubSubPacket: <T>(type: PubSubUnion, callback: (packet: T) => void) => void;
|
||||
sendPubSubPacket: (type: PubSubUnion, data: PubSubPacketType) => void;
|
||||
}
|
||||
|
||||
export const WebSocketApiContext = createContext<WebSocketApi>(undefined as never);
|
||||
|
||||
export type RPCPacketType = RpcMessageHeaderT['message'];
|
||||
export type PubSubPacketType = PubSubHeaderT['u'];
|
||||
export type DataFeedPacketType = DataFeedMessageHeaderT['message'];
|
||||
// export type OutboundPacketType = OutboundPacketT['packet'];
|
||||
|
||||
export function useProvideWebsocketApi(): WebSocketApi {
|
||||
const rpcPacketCounterRef = useRef<number>(0);
|
||||
const webSocketRef = useRef<WebSocket | null>(null);
|
||||
const rpclistenerRef = useRef<EventTarget>(new EventTarget());
|
||||
const pubsublistenerRef = useRef<EventTarget>(new EventTarget());
|
||||
const datafeedlistenerRef = useRef<EventTarget>(new EventTarget());
|
||||
const [isFirstConnection, setFirstConnection] = useState(true);
|
||||
const [timedOut, setTimedOut] = useState(false);
|
||||
@@ -91,14 +84,6 @@ export function useProvideWebsocketApi(): WebSocketApi {
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
message.pubSubMsgs.forEach((pubSubHeader) => {
|
||||
pubsublistenerRef.current?.dispatchEvent(
|
||||
new CustomEvent(PubSubUnion[pubSubHeader.uType], {
|
||||
detail: pubSubHeader.u,
|
||||
})
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const sendRPCPacket = (type: RpcMessage, data: RPCPacketType): void => {
|
||||
@@ -138,22 +123,6 @@ export function useProvideWebsocketApi(): WebSocketApi {
|
||||
webSocketRef.current.send(fbb.asUint8Array());
|
||||
};
|
||||
|
||||
const sendPubSubPacket = (type: PubSubUnion, data: PubSubPacketType): void => {
|
||||
if (webSocketRef?.current?.readyState !== WebSocket.OPEN) return;
|
||||
const fbb = new Builder(1);
|
||||
|
||||
const message = new MessageBundleT();
|
||||
|
||||
const pubSubHeader = new PubSubHeaderT();
|
||||
pubSubHeader.uType = type;
|
||||
pubSubHeader.u = data;
|
||||
|
||||
message.pubSubMsgs = [pubSubHeader];
|
||||
fbb.finish(message.pack(fbb));
|
||||
|
||||
webSocketRef.current.send(fbb.asUint8Array());
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
webSocketRef.current = new WebSocket(`ws://${targetIp}:${targetPort}`);
|
||||
|
||||
@@ -222,20 +191,8 @@ export function useProvideWebsocketApi(): WebSocketApi {
|
||||
};
|
||||
}, [callback, type]);
|
||||
},
|
||||
usePubSubPacket: <T>(type: PubSubUnion, callback: (packet: T) => void) => {
|
||||
useEffect(() => {
|
||||
const onEvent = (event: CustomEventInit) => {
|
||||
callback(event.detail);
|
||||
};
|
||||
pubsublistenerRef.current.addEventListener(PubSubUnion[type], onEvent);
|
||||
return () => {
|
||||
pubsublistenerRef.current.removeEventListener(PubSubUnion[type], onEvent);
|
||||
};
|
||||
}, [callback, type]);
|
||||
},
|
||||
sendRPCPacket,
|
||||
sendDataFeedPacket,
|
||||
sendPubSubPacket,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ const resetSounds: Record<
|
||||
mew: HTMLAudioElement | null;
|
||||
}
|
||||
> = {
|
||||
[ResetType.Full]: {
|
||||
[ResetType.FULL]: {
|
||||
initial: createAudio('/sounds/full-reset/init-full-reset-with-tail.ogg'),
|
||||
tick: [
|
||||
createAudio('/sounds/full-reset/full-click-1.ogg'),
|
||||
@@ -33,13 +33,13 @@ const resetSounds: Record<
|
||||
end: createAudio('/sounds/full-reset/end-full-reset-with-tail.ogg'),
|
||||
mew,
|
||||
},
|
||||
[ResetType.Yaw]: {
|
||||
[ResetType.YAW]: {
|
||||
initial: null,
|
||||
tick: null,
|
||||
end: createAudio('/sounds/yaw-reset/yaw-reset.ogg'),
|
||||
mew: null,
|
||||
},
|
||||
[ResetType.Mounting]: {
|
||||
[ResetType.MOUNTING]: {
|
||||
initial: createAudio('/sounds/mounting-reset/init-mounting-reset-with-tail.ogg'),
|
||||
tick: [
|
||||
createAudio('/sounds/mounting-reset/mount-click-1.ogg'),
|
||||
|
||||
@@ -99,8 +99,8 @@ export const trackerFromIdAtom = ({
|
||||
({ tracker }) =>
|
||||
trackerNum &&
|
||||
deviceId &&
|
||||
tracker?.trackerId?.trackerNum == trackerNum &&
|
||||
tracker?.trackerId?.deviceId?.id == deviceId
|
||||
tracker?.trackerId == trackerNum &&
|
||||
tracker?.deviceId == deviceId
|
||||
)
|
||||
),
|
||||
(a) => a,
|
||||
|
||||
@@ -68,7 +68,7 @@ export function getSentryOrCompute(enabled = false, uuid: string, isSteam: boole
|
||||
});
|
||||
|
||||
if (!newClient) {
|
||||
error('Couldnt initialize Sentry for error logging');
|
||||
error('Couldn\'t initialize Sentry for error logging');
|
||||
} else {
|
||||
log('Initialized the Sentry client');
|
||||
}
|
||||
@@ -77,15 +77,15 @@ export function getSentryOrCompute(enabled = false, uuid: string, isSteam: boole
|
||||
}
|
||||
|
||||
export function updateSentryContext(devices: DeviceDataT[]) {
|
||||
// We filter out the shit we dont want. We dont need rotation data or ip addresses
|
||||
// We filter out what we don't want (rotations and ip addresses).
|
||||
const trackers = (devices || []).map(({ hardwareInfo, trackers, id }) => ({
|
||||
id: id?.id,
|
||||
id: id,
|
||||
hardwareInfo: { ...hardwareInfo, ipAddress: undefined },
|
||||
trackers: trackers.map(({ info, trackerId }) => ({
|
||||
trackers: trackers.map(({ info, trackerId, deviceId }) => ({
|
||||
info,
|
||||
trackerId: {
|
||||
trackerNum: trackerId?.trackerNum,
|
||||
deviceId: trackerId?.deviceId?.id,
|
||||
trackerNum: trackerId,
|
||||
deviceId: deviceId,
|
||||
},
|
||||
})),
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
# SlimeVR Server Architecture
|
||||
|
||||
This document explains how the server is structured, why it's structured that way, and how to extend it correctly.
|
||||
|
||||
---
|
||||
|
||||
## Mental Model
|
||||
|
||||
Every significant part of the server a tracker, a UDP connection, a SolarXR session, a config file is a **module**. Every module is a list of behaviours sharing one context:
|
||||
|
||||

|
||||
|
||||
That's the entire system. Everything else is an application of this pattern.
|
||||
|
||||
---
|
||||
|
||||
## Why This Pattern
|
||||
|
||||
The server handles many concurrent connections, each with independent state that many other components need to observe. A shared mutable object works fine until two coroutines update it at the same time, or you need to know *when* something changed, or you want to add a feature without touching existing code.
|
||||
|
||||
The reducer pattern solves all three:
|
||||
|
||||
- **Thread safety**: `StateFlow.update` is atomic. Concurrent dispatches serialize without locks.
|
||||
- **Observability**: `context.state` is a hot `StateFlow` it always holds the current value and any code can `collect` it and react to changes without being coupled to the producer.
|
||||
- **Extensibility**: adding a feature means adding a `Behaviour` to a list. Nothing else changes.
|
||||
|
||||
The cost is that you cannot mutate state directly. Everything goes through `dispatch`. That constraint is the point.
|
||||
|
||||
---
|
||||
|
||||
## The Context
|
||||
|
||||
`Context<S, A>` (`context/context.kt`) holds the current state as a `StateFlow<S>`, the coroutine scope that defines this module's lifetime, and the behaviour list.
|
||||
|
||||
```kotlin
|
||||
class Context<S, A>(
|
||||
val state: StateFlow<S>,
|
||||
val scope: CoroutineScope,
|
||||
val behaviours: CopyOnWriteArrayList<Behaviour<S, A, *>>,
|
||||
) {
|
||||
fun dispatch(action: A)
|
||||
fun dispatchAll(actions: List<A>)
|
||||
fun <C> observeAll(receiver: C)
|
||||
}
|
||||
```
|
||||
|
||||
`Context.create` takes an initial state and a list of behaviours. On each `dispatch`, it folds every behaviour's `reduce` over the current state in order and publishes the result. Behaviours that don't care about an action return the state unchanged.
|
||||
|
||||
`dispatchAll(actions)` applies a list of actions in one atomic `StateFlow.update`. Use it when you need multiple state changes to be visible as one - intermediate states are never published, so no observer fires between them.
|
||||
|
||||
`observeAll(receiver)` calls `observe(receiver)` on every behaviour in the list. This is how observation is wired after construction - see [Module Lifecycle](#module-lifecycle).
|
||||
|
||||
The `behaviours` list is a `CopyOnWriteArrayList`. This allows adding behaviours after construction, which is needed for modules whose behaviour list depends on runtime context (e.g. `TrackingChecklist` adds step behaviours in `startObserving`).
|
||||
|
||||
---
|
||||
|
||||
## Behaviours
|
||||
|
||||
A behaviour is one feature of a module. It has two methods, both optional:
|
||||
|
||||
```kotlin
|
||||
interface Behaviour<S, A, C> {
|
||||
fun reduce(state: S, action: A): S = state // pure, no side effects
|
||||
fun observe(receiver: C) {} // side effects go here
|
||||
}
|
||||
```
|
||||
|
||||
`reduce` is a pure function - it cannot launch coroutines, call external services, or read from a clock. It just maps `(state, action) → state`.
|
||||
|
||||
`observe` is called once after construction, after the context exists. This is where you launch coroutines, subscribe to flows, register event listeners. All coroutines launched here should use `receiver.context.scope` so they die when the module dies - no manual cleanup, no leaks.
|
||||
|
||||
**Why behaviours instead of methods on the module class?**
|
||||
|
||||
The natural alternative is one class with methods for each feature - ping handling, handshake logic, sensor registration, timeout detection, all in the same file. That works until the class has 20 features and every change has global blast radius. Behaviours make the feature list explicit: you read `create()`, you see exactly what the module does. Adding or removing a feature is one line in that list, touching nothing else.
|
||||
|
||||
**Why `observe` is separate from `reduce`:**
|
||||
|
||||
`reduce` must stay pure so state transitions are testable and predictable. Side effects in `observe` are isolated - a behaviour that logs packets doesn't affect state, a behaviour that saves config doesn't affect packet handling.
|
||||
|
||||
### Scoping Behaviours to Module Lifetime
|
||||
|
||||
Every behaviour's coroutines run inside `receiver.context.scope`. When a UDP connection drops, its scope is cancelled, which cancels every coroutine every behaviour launched for that connection. No teardown code needed anywhere.
|
||||
|
||||
This is why `observe` receives the module (or context) rather than taking a raw `CoroutineScope` parameter - it enforces that behaviours cannot outlive their module.
|
||||
|
||||
### Stateless vs. Stateful Behaviours
|
||||
|
||||
All behaviours are `class`es, instantiated at the call site:
|
||||
|
||||
```kotlin
|
||||
class PacketBehaviour : UDPConnectionBehaviour { ... }
|
||||
|
||||
val behaviours = listOf(PacketBehaviour(), PacketLossBehaviour(), HandshakeBehaviour())
|
||||
```
|
||||
|
||||
Even behaviours with no constructor arguments are `class`es. `object` is banned for behaviours because `observe()` often needs to capture mutable state (timers, counters, flags). An `object` shares that state across every module instance that uses it — a subtle, hard-to-trace bug. Requiring `class` enforces that each module instance gets its own behaviour instance, with its own isolated state. The allocation cost is negligible.
|
||||
|
||||
Behaviours that need external services take them as constructor arguments:
|
||||
|
||||
```kotlin
|
||||
class TrackerConfigBehaviour(
|
||||
private val settings: Settings,
|
||||
private val hardwareId: String,
|
||||
) : TrackerBehaviour { ... }
|
||||
```
|
||||
|
||||
When a behaviour is conditional (depends on a nullable service), use `buildList`:
|
||||
|
||||
```kotlin
|
||||
val behaviours: List<MyBehaviour> = buildList {
|
||||
add(AlwaysPresentBehaviour())
|
||||
optionalService?.let { add(OptionalServiceBehaviour(it)) }
|
||||
}
|
||||
```
|
||||
|
||||
For modules like `SolarXRBridge` where the behaviour list is large and reusable, extract it into a named function on the companion object:
|
||||
|
||||
```kotlin
|
||||
companion object {
|
||||
fun buildBehaviours(appContext: AppContextProvider): List<SolarXRBridgeBehaviour> = buildList {
|
||||
add(DataFeedInitBehaviour(appContext.server, appContext.skeleton))
|
||||
add(FirmwareBehaviour(appContext.server, appContext.firmwareManager))
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This lets tests call `buildBehaviours` with a stub context, or ignore it entirely and construct the module directly with only the behaviours they need.
|
||||
|
||||
### The Receiver Type
|
||||
|
||||
The type parameter `C` controls what `observe` receives. For simple modules where behaviours only need to dispatch or subscribe to state, `C` is the context itself. For modules where behaviours also need to call methods (send bytes, emit events), `C` is the module class:
|
||||
|
||||
```kotlin
|
||||
// behaviours only dispatch/observe state
|
||||
typealias GlobalConfigBehaviour = Behaviour<GlobalConfigState, GlobalConfigActions, GlobalConfigContext>
|
||||
|
||||
// behaviours also call receiver.send(), receiver.packetEvents.on<T>(...)
|
||||
typealias UDPConnectionBehaviour = Behaviour<UDPConnectionState, UDPConnectionActions, UDPConnection>
|
||||
```
|
||||
|
||||
### File Layout
|
||||
|
||||
Behaviours live in a `behaviours.kt` file in the same package as the module, separate from the module class itself:
|
||||
|
||||
```
|
||||
tracker/
|
||||
├── module.kt ← Tracker class, TrackerState, TrackerActions, typealiases
|
||||
├── behaviours.kt ← TrackerBasicBehaviour, TrackerTPSBehaviour, ...
|
||||
└── config.kt ← TrackerConfigBehaviour (its own file - distinct concern)
|
||||
```
|
||||
|
||||
`module.kt` is the standard name for the file containing the module class, state, actions, and typealiases. `behaviours.kt` holds the implementations. For modules with many distinct feature areas, split behaviours by feature instead of one file - `solarxr/` uses this: `datafeed.kt`, `firmware.kt`, `provisioning.kt`, etc. each live alongside `module.kt`.
|
||||
|
||||
---
|
||||
|
||||
## Module Lifecycle
|
||||
|
||||
Every module has a two-step lifecycle: **construction** then **observation wiring**.
|
||||
|
||||
```kotlin
|
||||
// Step 1: create the module (pure construction, no side effects)
|
||||
val manager = FirmwareManager.create(ctx = phase1, scope = scope)
|
||||
|
||||
// Step 2: wire observation (launches coroutines, subscribes to flows)
|
||||
manager.startObserving()
|
||||
```
|
||||
|
||||
`create()` builds the context with its behaviour list and constructs the module. No coroutines are launched, no flows are subscribed. The module is inert.
|
||||
|
||||
`startObserving()` calls `context.observeAll(this)`, which calls `observe(receiver)` on every behaviour. This is where all side effects begin.
|
||||
|
||||
**Why separate construction from observation?**
|
||||
|
||||
Some modules need to exist before all their dependencies are assembled. For example, `TrackingChecklist` is constructed before `AppContext` exists, but its step behaviours depend on `Skeleton` and `VRCConfigManager` which are part of `AppContext`. By deferring observation, the module can be constructed in any order and wired later:
|
||||
|
||||
```kotlin
|
||||
// Constructed early - no AppContext needed yet
|
||||
val trackingChecklist = TrackingChecklist.create(scope = this)
|
||||
|
||||
// AppContext assembled from all modules
|
||||
val appContext = AppContext(server, config, serialServer, skeleton, ..., trackingChecklist)
|
||||
|
||||
// Observation wired now - TrackingChecklist adds its step behaviours using AppContext
|
||||
appContext.startObserving()
|
||||
```
|
||||
|
||||
`AppContext.startObserving()` calls `startObserving()` on every bootstrap module in sequence, and `trackingChecklist.startObserving(appContext)` adds its behaviours to `context.behaviours` before calling `context.observeAll(this)`.
|
||||
|
||||
**Runtime modules** (UDP connections, SolarXR bridges, HID receivers) are created and immediately observed - they have all their dependencies at creation time:
|
||||
|
||||
```kotlin
|
||||
val bridge = SolarXRBridge.create(id = id, appContext = appContext, scope = scope)
|
||||
// startObserving() is called inside create()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Dependency Injection
|
||||
|
||||
The server uses a typed context hierarchy for dependency injection. Contexts are interfaces - modules declare the minimum phase they need in `create()`, which gives compile-time guarantees that their dependencies exist.
|
||||
|
||||
```
|
||||
Phase1ContextProvider
|
||||
└── AppContextProvider
|
||||
```
|
||||
|
||||
**`Phase1ContextProvider`** - the bootstrap phase. Available before `AppContext` is assembled:
|
||||
|
||||
```kotlin
|
||||
interface Phase1ContextProvider {
|
||||
val server: VRServer
|
||||
val config: AppConfig
|
||||
val serialServer: SerialServer
|
||||
}
|
||||
```
|
||||
|
||||
**`AppContextProvider`** - the full application context. Available after all bootstrap modules are constructed:
|
||||
|
||||
```kotlin
|
||||
interface AppContextProvider : Phase1ContextProvider {
|
||||
val skeleton: Skeleton
|
||||
val firmwareManager: FirmwareManager
|
||||
val vrcConfigManager: VRCConfigManager?
|
||||
val provisioningManager: ProvisioningManager
|
||||
val heightCalibrationManager: HeightCalibrationManager
|
||||
val trackingChecklist: TrackingChecklist
|
||||
fun startObserving()
|
||||
}
|
||||
```
|
||||
|
||||
**The rule:** always use `AppContextProvider` unless the module genuinely cannot be constructed after `AppContext` is assembled. In practice, only bootstrap modules (`FirmwareManager`, `Skeleton`, `ProvisioningManager`, `HeightCalibrationManager`) use `Phase1ContextProvider` in `create()`. Runtime modules like `SolarXRBridge` always receive `AppContextProvider`.
|
||||
|
||||
The concrete classes `Phase1Context` and `AppContext` implement these interfaces. Tests implement the interfaces directly with only the fields they need - see [Testing](#testing).
|
||||
|
||||
---
|
||||
|
||||
## Actions
|
||||
|
||||
Actions are `sealed interface`s. This matters because the compiler enforces exhaustive `when` in reducers - you cannot forget to handle a new action type. Named actions also mean you can grep for all places a specific transition can occur.
|
||||
|
||||
```kotlin
|
||||
sealed interface UDPConnectionActions {
|
||||
data class Handshake(val deviceId: Int) : UDPConnectionActions
|
||||
data class LastPacket(val packetNum: Long?, val time: Long) : UDPConnectionActions
|
||||
data object Disconnected : UDPConnectionActions
|
||||
}
|
||||
```
|
||||
|
||||
The choice between a flexible `Update` action and a named action is about who else needs to react:
|
||||
|
||||
- **`Update`** when only the caller cares about the change. It carries a lambda that transforms state directly. No other behaviour pattern-matches it, so there's no coupling.
|
||||
- **Named action** when other behaviours need to react to this specific event. `Handshake` in `UDPConnectionActions` signals to multiple behaviours that a connection is now established; each one matches it independently.
|
||||
|
||||
```kotlin
|
||||
// Nothing else needs to react - use Update
|
||||
tracker.context.dispatch(TrackerActions.Update { copy(tps = newTps) })
|
||||
|
||||
// Multiple behaviours react to this - use a named action
|
||||
connection.context.dispatch(UDPConnectionActions.Handshake(deviceId = id))
|
||||
```
|
||||
|
||||
If you find yourself dispatching an `Update` that other behaviours start matching against, it's time to promote it to a named action.
|
||||
|
||||
---
|
||||
|
||||
## EventDispatcher
|
||||
|
||||
`EventDispatcher<T>` routes events to typed listeners. Each behaviour registers its own listener in `observe`:
|
||||
|
||||
```kotlin
|
||||
receiver.packetEvents.on<SensorInfo> { packet -> ... } // only SensorInfo
|
||||
receiver.packetEvents.onAny { packet -> ... } // every packet
|
||||
```
|
||||
|
||||
**Why not a central `when` block?**
|
||||
|
||||
A central switch means every new packet type requires editing the dispatch hub. With `EventDispatcher`, each behaviour owns its subscription. Adding a new packet type means adding a class to `packets.kt` and a listener in a behaviour - the routing hub never changes.
|
||||
|
||||
It also means behaviours are self-contained: `SensorInfoBehaviour` is the only place that knows what to do with `SensorInfo`. No shared routing code.
|
||||
|
||||
`EventDispatcher` dispatches by the runtime type of the event by default. When events are wrapped (e.g. `PacketEvent<UDPPacket>` where the actual packet is the inner value), pass a `keyOf` lambda to tell the dispatcher which type to route by - otherwise all events would be bucketed under `PacketEvent` regardless of the inner packet type.
|
||||
|
||||
---
|
||||
|
||||
## Coroutine Scope and Lifetime
|
||||
|
||||
Every module receives a `CoroutineScope` at creation. That scope defines when the module lives and dies:
|
||||
|
||||
- Cancelling the scope cancels all coroutines - all behaviours launched inside it
|
||||
- No `close()`, `stop()`, or `dispose()` methods needed anywhere
|
||||
- A disconnected client, a dropped UDP connection, a closed serial port - all cleaned up by scope cancellation
|
||||
|
||||
Blocking I/O goes on `Dispatchers.IO`. State updates and logic stay on the default dispatcher. Never use `runBlocking` inside an observer - it blocks the coroutine thread pool.
|
||||
|
||||
---
|
||||
|
||||
## State vs. Plain Data
|
||||
|
||||
Not everything needs to be in a `StateFlow`. The rule: **put data in state only if other code needs to react to it changing**.
|
||||
|
||||
- `VRServer.handleCounter` is an `AtomicInt` - nothing reacts to it, so a dispatch round-trip would be waste.
|
||||
- `UDPTrackerServer` has no `Context` at all. Its connection map is a `MutableMap` internal to the server loop. Nothing outside reads it.
|
||||
- Tracker config *is* in state because the SolarXR layer and the config autosave both react to body part assignments changing.
|
||||
|
||||
---
|
||||
|
||||
## Cross-Module Communication
|
||||
|
||||
Modules don't call each other directly. A behaviour in one module subscribes to another module's `StateFlow` and dispatches into its own context (or another module's context) when something relevant changes.
|
||||
|
||||
Two common patterns:
|
||||
|
||||
**React to another module's state:**
|
||||
```kotlin
|
||||
// Inside TrackerConfigBehaviour.observe()
|
||||
// When tracker state changes, persist the relevant fields to Settings
|
||||
receiver.context.state
|
||||
.distinctUntilChangedBy { stateToConfig(it) }
|
||||
.drop(1)
|
||||
.onEach { state ->
|
||||
settings.context.dispatch(SettingsActions.UpdateTracker(hardwareId) { stateToConfig(state) })
|
||||
}
|
||||
.launchIn(receiver.context.scope)
|
||||
```
|
||||
|
||||
**Dispatch into VRServer from a connection:**
|
||||
```kotlin
|
||||
// Inside HandshakeBehaviour.observe() - a UDP connection registers a new device
|
||||
receiver.packetEvents.on<Handshake> { event ->
|
||||
val device = Device.create(...)
|
||||
receiver.serverContext.context.dispatch(VRServerActions.NewDevice(deviceId, device))
|
||||
}
|
||||
```
|
||||
|
||||
The key rule: behaviours own the subscription lifetime via `launchIn(receiver.context.scope)`. When the module dies, the subscription stops - no dangling listeners in foreign modules.
|
||||
|
||||
---
|
||||
|
||||
## IPC and Transport
|
||||
|
||||
The server exposes four connection points:
|
||||
|
||||
| Transport | Client | Protocol |
|
||||
|---|---|---|
|
||||
| Unix socket / named pipe `SlimeVRDriver` | OpenVR driver | Protobuf (Wire) |
|
||||
| Unix socket / named pipe `SlimeVRInput` | External feeder | Protobuf (Wire) |
|
||||
| Unix socket / named pipe `SlimeVRRpc` | SolarXR (IPC path) | FlatBuffers |
|
||||
| WebSocket port 21110 | GUI / third-party (SolarXR) | FlatBuffers |
|
||||
|
||||
**Why separate transport from protocol?**
|
||||
|
||||
Platform files (`linux.kt`, `windows.kt`) own reading frames off a socket and produce a `Flow<ByteArray>` + a `send` function. Protocol handlers (`protocol.kt`, `ipc.kt`) are plain `suspend fun`s that take those two things and know nothing about Unix sockets or named pipes.
|
||||
|
||||
The same `handleSolarXRBridge` function runs on Linux sockets, Windows pipes, and WebSocket. The WebSocket adapter in `ws-server.kt` converts Ktor frames to the same `Flow<ByteArray>` + `send` abstraction. The handler never changes.
|
||||
|
||||
**Why events for IPC message routing?**
|
||||
|
||||
Same reason as UDP packets. The SolarXR protocol has dozens of RPC message types. Behaviours that handle firmware updates, skeleton config, data feeds, etc. each register their own listener on the `rpcDispatcher`. Adding a new RPC handler doesn't touch existing ones.
|
||||
|
||||
### Wire Framing (named sockets)
|
||||
|
||||
All three named sockets use the same framing: a **LE u32 length** prefix (including the 4-byte header itself) followed by the raw payload bytes.
|
||||
|
||||
### UDP Packet Pipeline
|
||||
|
||||
The UDP receive loop runs on `Dispatchers.IO`. It reads a datagram, parses the packet type and payload via `readPacket`, wraps the result in a `PacketEvent`, and pushes it into a `Channel<PacketEvent<UDPPacket>>` per connection.
|
||||
|
||||
A dedicated coroutine per connection drains the channel and calls `EventDispatcher.emit`. Pre-handshake packets are filtered at the channel drain step - a single guard in one place, not spread across every behaviour.
|
||||
|
||||
---
|
||||
|
||||
## Config
|
||||
|
||||
Config is not just file I/O - it is a live state machine. The server supports runtime profile switching, so config data lives in a `StateFlow` like everything else. Code that needs to react to config changes (e.g. tracker body part assignment saving to disk) subscribes to the settings state flow.
|
||||
|
||||
The config system has three layers:
|
||||
|
||||
- **`AppConfig`** - global state: which user profile and settings profile are active
|
||||
- **`UserConfig`** - per-user data (body proportions, etc.)
|
||||
- **`Settings`** - per-profile settings (tracker assignments, port, VRC warnings); persists to disk
|
||||
|
||||
Each is a full module with its own `Context`, behaviours, and JSON autosave. Migrations live in the module's `parseAndMigrate` function - add a `version < N` branch there.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
The module pattern is designed to be testable at each layer independently.
|
||||
|
||||
### Testing reducers
|
||||
|
||||
Create a context directly with the behaviours you want to test. No module class, no scope tricks:
|
||||
|
||||
```kotlin
|
||||
val context = Context.create(
|
||||
initialState = FirmwareManagerState(jobs = mapOf()),
|
||||
scope = this,
|
||||
behaviours = listOf(FirmwareManagerBaseBehaviour()),
|
||||
)
|
||||
context.dispatch(FirmwareManagerActions.UpdateJob(...))
|
||||
assertEquals(FirmwareUpdateStatus.UPLOADING, context.state.value.jobs["COM1"]?.status)
|
||||
```
|
||||
|
||||
### Testing observe behaviour
|
||||
|
||||
Construct the module directly - bypassing `create()` - with only the behaviours relevant to the test. This avoids constructing unrelated dependencies:
|
||||
|
||||
```kotlin
|
||||
val serialServer = buildTestSerialServer(backgroundScope)
|
||||
val context = Context.create(
|
||||
initialState = ProvisioningManager.INITIAL_STATE,
|
||||
scope = backgroundScope,
|
||||
behaviours = listOf(ProvisioningManagerBaseBehaviour()),
|
||||
)
|
||||
val manager = ProvisioningManager(context = context, serialServer = serialServer, scope = backgroundScope)
|
||||
manager.startObserving()
|
||||
|
||||
manager.startProvisioning(buildTestVrServer(backgroundScope), "wifi", "pass", null)
|
||||
```
|
||||
|
||||
For modules that need an `AppContextProvider` (e.g. `SolarXRBridge`), extend `TestAppContext` and override only what the test uses. Every other field defaults to `error("not used in test")`:
|
||||
|
||||
```kotlin
|
||||
val server = buildTestVrServer(backgroundScope)
|
||||
val skeleton = buildTestSkeleton(backgroundScope)
|
||||
val appContext = object : TestAppContext() {
|
||||
override val server = server
|
||||
override val skeleton = skeleton
|
||||
}
|
||||
val context = Context.create(
|
||||
initialState = SolarXRBridgeState(dataFeedConfigs = listOf()),
|
||||
scope = backgroundScope,
|
||||
behaviours = listOf(DataFeedInitBehaviour(server, skeleton)),
|
||||
)
|
||||
val bridge = SolarXRBridge(id = 1, context = context, appContext = appContext,
|
||||
dataFeedDispatcher = EventDispatcher(), rpcDispatcher = EventDispatcher())
|
||||
bridge.startObserving()
|
||||
```
|
||||
|
||||
`TestAppContext` lives in `TestServer.kt`. When a new module is added to `AppContextProvider`, add a default stub there - all existing tests automatically get the default without changes.
|
||||
|
||||
**The pattern:** only initialize what the test exercises. If a behaviour accesses a field that isn't overridden, it throws - that's intentional. It keeps tests focused and stubs minimal.
|
||||
|
||||
### Test helpers (`TestServer.kt`)
|
||||
|
||||
`buildTestVrServer`, `buildTestSerialServer`, `buildTestUserConfig`, and `buildTestSkeleton` are available for constructing real lightweight instances of common dependencies.
|
||||
|
||||
---
|
||||
|
||||
## What Goes Where
|
||||
|
||||
| Location | Purpose |
|
||||
|---|---|
|
||||
| `server/core` | Protocol-agnostic business logic |
|
||||
| `server/desktop` | Platform entry point, IPC wiring, HID, serial flash |
|
||||
| `context/context.kt` | `Context` and `Behaviour` primitives - no domain logic here |
|
||||
| `udp/` | UDP wire protocol: connection state, packets, behaviours, server loop |
|
||||
| `hid/` | HID tracker receiver: registration, rotation, battery, status |
|
||||
| `solarxr/` | `SolarXRBridge` + per-feature behaviour files (one per RPC area) |
|
||||
| `config/` | 3-tier config: `AppConfig`, `UserConfig`, `Settings` |
|
||||
| `firmware/` | OTA and serial flash; independent of UDP tracker protocol |
|
||||
| `trackingchecklist/` | Checklist steps as behaviours observing server/tracker/VRC state |
|
||||
| `skeleton/` | Skeleton solving, proportions, bone geometry |
|
||||
| `vrchat/` | VRChat config monitoring and recommended-value computation |
|
||||
|
||||
---
|
||||
|
||||
## Extending the Server
|
||||
|
||||
### Adding a New Module
|
||||
|
||||
1. **Define state and actions** in `module.kt`:
|
||||
```kotlin
|
||||
data class MyState(val connected: Boolean)
|
||||
|
||||
sealed interface MyActions {
|
||||
data object Connected : MyActions
|
||||
data object Disconnected : MyActions
|
||||
}
|
||||
|
||||
typealias MyContext = Context<MyState, MyActions>
|
||||
typealias MyBehaviour = Behaviour<MyState, MyActions, MyModule>
|
||||
```
|
||||
|
||||
2. **Define the module class** with a `create()` factory and a `startObserving()` method:
|
||||
```kotlin
|
||||
class MyModule(val context: MyContext, val server: VRServer) {
|
||||
fun startObserving() = context.observeAll(this)
|
||||
|
||||
companion object {
|
||||
fun create(ctx: Phase1ContextProvider, scope: CoroutineScope): MyModule {
|
||||
val context = Context.create(
|
||||
initialState = MyState(false),
|
||||
scope = scope,
|
||||
behaviours = listOf(MyCoreBehaviour()),
|
||||
)
|
||||
return MyModule(context, ctx.server)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. **Register in `AppContext`** and call `startObserving()` inside `AppContext.startObserving()`.
|
||||
|
||||
4. **Write behaviours** in `behaviours.kt` (or per-feature files for large modules).
|
||||
|
||||
### Adding a Behaviour to an Existing Module
|
||||
|
||||
Add it to the `behaviours` list in `create()`. The behaviour's `reduce` and `observe` are automatically wired when `startObserving()` is called. Nothing else changes.
|
||||
|
||||
### Adding a New UDP Packet Type
|
||||
|
||||
1. Add the packet class and its `read` function in `udp/packets.kt`
|
||||
2. Add an entry to the `PacketType` enum and a branch in `readPacket()`
|
||||
3. Register a listener in a behaviour's `observe`:
|
||||
```kotlin
|
||||
receiver.packetEvents.on<MyPacket> { event ->
|
||||
receiver.context.dispatch(...)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Style Conventions
|
||||
|
||||
- **Prefer plain functions over classes.** A single-method interface should almost always be a function type (`() -> Unit`, `suspend (ByteArray) -> Unit`). When in doubt, write a function.
|
||||
- **Behaviours are always `class`, never `object`.** Even behaviours with no constructor arguments. `observe()` frequently captures mutable state (timers, counters, flags), and a singleton `object` would share that state across every module instance — a subtle, cross-connection bug. Instantiate every behaviour at the call site: `listOf(PacketBehaviour(), PingBehaviour())`.
|
||||
- **Prefer plain functions over extension functions.** Only use extensions when the receiver type is genuinely the primary subject.
|
||||
- **State data classes are all `val`.** Mutable fields in a state class are a design mistake - use `var` in a plain class if you need local mutability, never in state.
|
||||
- **Use `sealed interface` for actions**, not `sealed class` - no constructor overhead.
|
||||
- **Module creation lives in `companion object { fun create(...) }`.**
|
||||
- **Module observation wiring lives in `startObserving()`**, called via `context.observeAll(this)`.
|
||||
- **Never expose `MutableStateFlow` directly.** Expose `StateFlow` via `context.state`.
|
||||
@@ -12,21 +12,20 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
import java.util.Base64
|
||||
|
||||
plugins {
|
||||
kotlin("android")
|
||||
kotlin("plugin.serialization")
|
||||
id("com.github.gmazzo.buildconfig")
|
||||
|
||||
id("com.android.application") version "8.13.2"
|
||||
id("com.android.application") version "9.2.1"
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain {
|
||||
languageVersion.set(JavaLanguageVersion.of(17))
|
||||
languageVersion.set(JavaLanguageVersion.of(24))
|
||||
}
|
||||
}
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion.set(JavaLanguageVersion.of(17))
|
||||
languageVersion.set(JavaLanguageVersion.of(24))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +81,7 @@ val deleteTempKeyStore = tasks.register<Delete>("deleteTempKeyStore") {
|
||||
|
||||
tasks.withType<KotlinCompile> {
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_17)
|
||||
jvmTarget.set(JvmTarget.JVM_24)
|
||||
freeCompilerArgs.set(listOf("-Xvalue-classes"))
|
||||
}
|
||||
}
|
||||
@@ -100,14 +99,13 @@ tasks.withType<Javadoc> {
|
||||
|
||||
repositories {
|
||||
google()
|
||||
maven(url = "https://jitpack.io")
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":server:core"))
|
||||
|
||||
implementation("commons-cli:commons-cli:1.11.0")
|
||||
implementation("org.apache.commons:commons-lang3:3.20.0")
|
||||
|
||||
// Android stuff
|
||||
implementation("androidx.appcompat:appcompat:1.7.1")
|
||||
implementation("androidx.core:core-ktx:1.17.0")
|
||||
@@ -117,21 +115,21 @@ dependencies {
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
|
||||
|
||||
// Serial
|
||||
// Serial + firmware flashing
|
||||
implementation("com.github.mik3y:usb-serial-for-android:3.7.0")
|
||||
implementation("com.github.loucass003:EspflashKotlin:v0.11.0")
|
||||
|
||||
// Logging
|
||||
implementation("io.klogging:klogging:0.11.7")
|
||||
|
||||
// WebSocket server + coroutines
|
||||
val ktorVersion = "3.4.1"
|
||||
implementation("io.ktor:ktor-server-cio:$ktorVersion")
|
||||
implementation("io.ktor:ktor-server-websockets:$ktorVersion")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||
}
|
||||
|
||||
// The android block is where you configure all your Android-specific build options.
|
||||
extra.apply {
|
||||
val tagCount = providers.exec {
|
||||
commandLine("git", "--no-pager", "tag", "-l")
|
||||
}.standardOutput.asText.get().trim().split('\n').size
|
||||
val description = providers.exec {
|
||||
commandLine("git", "describe", "--tags", "--abbrev=8", "--always")
|
||||
}.standardOutput.asText.get().trim()
|
||||
set("gitVersionCode", tagCount)
|
||||
set("gitVersionName", description)
|
||||
}
|
||||
android {
|
||||
// The app's namespace. Used primarily to access app resources.
|
||||
|
||||
@@ -165,12 +163,16 @@ android {
|
||||
|
||||
// adds an offset of the version code as we might do apk releases in the middle of actual
|
||||
// releases if we failed on bundling or stuff
|
||||
val versionCodeOffset = 5
|
||||
// Defines the version number of your app.
|
||||
versionCode = (extra["gitVersionCode"] as? Int)?.plus(versionCodeOffset) ?: 0
|
||||
val versionCodeOffset = 4
|
||||
|
||||
// Defines a user-friendly version name for your app.
|
||||
versionName = extra["gitVersionName"] as? String ?: "v0.0.0"
|
||||
// Defines the version number of your app.
|
||||
versionCode = providers.exec {
|
||||
commandLine("git", "--no-pager", "tag", "-l")
|
||||
}.standardOutput.asText.get().trim().split('\n').size +
|
||||
versionCodeOffset
|
||||
versionName = providers.exec {
|
||||
commandLine("git", "describe", "--tags", "--abbrev=8", "--always")
|
||||
}.standardOutput.asText.get().trim()
|
||||
|
||||
logger.lifecycle("i: Configured for SlimeVR Android version \"$versionName\" ($versionCode).")
|
||||
|
||||
@@ -222,7 +224,7 @@ android {
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
sourceCompatibility = JavaVersion.VERSION_24
|
||||
targetCompatibility = JavaVersion.VERSION_24
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,11 @@
|
||||
<uses-feature android:name="android.hardware.usb.host" android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||
|
||||
|
||||
@@ -1,15 +1,53 @@
|
||||
package dev.slimevr.android
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.*
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.PowerManager
|
||||
import androidx.core.app.NotificationChannelCompat
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import io.eiren.util.logging.LogManager
|
||||
import dev.slimevr.AppContext
|
||||
import dev.slimevr.FeatureFlags
|
||||
import dev.slimevr.Phase1Context
|
||||
import dev.slimevr.VRServer
|
||||
import dev.slimevr.android.config.AndroidConfigStorage
|
||||
import dev.slimevr.android.hid.createAndroidHIDManager
|
||||
import dev.slimevr.android.ipc.createAndroidSolarXRWebsocketServer
|
||||
import dev.slimevr.android.serial.AndroidFirmwareFlasher
|
||||
import dev.slimevr.android.serial.createAndroidSerialServer
|
||||
import dev.slimevr.android.udp.resolveAndroidUdpAddress
|
||||
import dev.slimevr.android.vrchat.resolveAndroidOscQueryAddress
|
||||
import dev.slimevr.bvh.BVHManager
|
||||
import dev.slimevr.config.AppConfig
|
||||
import dev.slimevr.firmware.FirmwareManager
|
||||
import dev.slimevr.heightcalibration.HeightCalibrationManager
|
||||
import dev.slimevr.networkprofile.NetworkProfileManager
|
||||
import dev.slimevr.provisioning.ProvisioningManager
|
||||
import dev.slimevr.resets.ResetsManager
|
||||
import dev.slimevr.skeleton.Skeleton
|
||||
import dev.slimevr.trackingchecklist.TrackingChecklist
|
||||
import dev.slimevr.udp.UdpServer
|
||||
import dev.slimevr.util.safeLaunch
|
||||
import dev.slimevr.vmc.VMCManager
|
||||
import dev.slimevr.vrcosc.VRCOSCManager
|
||||
import io.klogging.noCoLogger
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.cancel
|
||||
|
||||
private val logger = noCoLogger("ForegroundService")
|
||||
|
||||
private const val ACTION_STOP = "dev.slimevr.android.STOP_SERVER"
|
||||
const val ACTION_FINISH_APP = "dev.slimevr.android.FINISH_APP"
|
||||
|
||||
/**
|
||||
* ForegroundService helps to keep the SlimeVR Server on Android from being killed.
|
||||
@@ -22,27 +60,37 @@ import io.eiren.util.logging.LogManager
|
||||
* Tested with VRChat on Quest 3 in high population worlds with all avatars on
|
||||
* for over an hour with no shut down of the SlimeVR server. Without this service,
|
||||
* the server would often be shutdown unexpectedly.
|
||||
*
|
||||
* Notes:
|
||||
* Luckily this does not show anything visual over the running app.
|
||||
* The notification only shows in the alert panel and cannot be dismissed.
|
||||
* On Quest there's no way to manually kill the Slime Server, so you have to restart the device.
|
||||
*/
|
||||
class ForegroundService : Service() {
|
||||
private val CHANNEL_ID = "SlimeVrForegroundServiceChannel"
|
||||
private val NOTIFICATION_ID = 100
|
||||
|
||||
private var serviceScope: CoroutineScope? = null
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
private var multicastLock: WifiManager.MulticastLock? = null
|
||||
private var wifiLock: WifiManager.WifiLock? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
setupAndroidLogging()
|
||||
createNotificationChannel()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
|
||||
serviceScope?.cancel()
|
||||
serviceScope = null
|
||||
sendBroadcast(Intent(ACTION_FINISH_APP).setPackage(packageName))
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
try {
|
||||
val notification = createNotification()
|
||||
ServiceCompat.startForeground(
|
||||
this,
|
||||
NOTIFICATION_ID, // Cannot be 0
|
||||
NOTIFICATION_ID,
|
||||
notification,
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
|
||||
@@ -54,22 +102,114 @@ class ForegroundService : Service() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
|
||||
e is ForegroundServiceStartNotAllowedException
|
||||
) {
|
||||
LogManager.severe("Tried to start foreground service when not allowed:", e)
|
||||
logger.error(e, "Tried to start foreground service when not allowed")
|
||||
}
|
||||
// ...
|
||||
}
|
||||
/*
|
||||
* Currently being a foreground process should be enough to keep the server running.
|
||||
* If it turns out to not be enough then the next option would be to return sticky here
|
||||
* which would also require moving server initialization from the MainActivity to here
|
||||
* so the server is restarted when the activity is. You can tell the process is restarted
|
||||
* if the intent variable is null.
|
||||
*/
|
||||
|
||||
if (serviceScope == null) {
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
serviceScope = scope
|
||||
scope.safeLaunch { startServer(scope) }
|
||||
}
|
||||
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
serviceScope?.cancel()
|
||||
serviceScope = null
|
||||
wakeLock?.release()
|
||||
wakeLock = null
|
||||
multicastLock?.release()
|
||||
multicastLock = null
|
||||
wifiLock?.release()
|
||||
wifiLock = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private suspend fun startServer(scope: CoroutineScope) {
|
||||
val storage = AndroidConfigStorage(filesDir)
|
||||
val config = AppConfig.create(scope = scope, storage = storage)
|
||||
val server = VRServer.create(scope = scope)
|
||||
val serialServer = createAndroidSerialServer(context = this, scope = scope)
|
||||
|
||||
val phase1 = Phase1Context(server = server, config = config, serialServer = serialServer)
|
||||
|
||||
val firmwareManager = FirmwareManager.create(ctx = phase1, scope = scope, flasher = AndroidFirmwareFlasher)
|
||||
val networkProfileManager = NetworkProfileManager.create(scope = scope, isSupported = false)
|
||||
val skeleton = Skeleton.create(scope = scope, ctx = phase1)
|
||||
val provisioningManager = ProvisioningManager.create(ctx = phase1, scope = scope)
|
||||
val heightCalibrationManager = HeightCalibrationManager.create(ctx = phase1, scope = scope)
|
||||
val trackingChecklist = TrackingChecklist.create(scope = scope)
|
||||
val udpServer = UdpServer.create(scope = scope, addressResolver = ::resolveAndroidUdpAddress)
|
||||
val bvhManager = BVHManager.create(skeleton = skeleton, storage = storage, scope = scope)
|
||||
val vmcManager = VMCManager.create(skeleton = skeleton, ctx = phase1, scope = scope)
|
||||
val vrcOscManager = VRCOSCManager.create(
|
||||
ctx = phase1,
|
||||
scope = scope,
|
||||
oscQueryAddress = resolveAndroidOscQueryAddress(),
|
||||
)
|
||||
val resetsManager = ResetsManager.create(server = server, scope = scope)
|
||||
|
||||
val appContext = AppContext(
|
||||
server = server,
|
||||
config = config,
|
||||
serialServer = serialServer,
|
||||
featureFlags = FeatureFlags(supportsSteamVR = false),
|
||||
skeleton = skeleton,
|
||||
firmwareManager = firmwareManager,
|
||||
vrcConfigManager = null,
|
||||
networkProfileManager = networkProfileManager,
|
||||
provisioningManager = provisioningManager,
|
||||
heightCalibrationManager = heightCalibrationManager,
|
||||
trackingChecklist = trackingChecklist,
|
||||
udpServer = udpServer,
|
||||
bvhManager = bvhManager,
|
||||
vmcManager = vmcManager,
|
||||
vrcOscManager = vrcOscManager,
|
||||
resetsManager = resetsManager,
|
||||
)
|
||||
|
||||
acquireLocks()
|
||||
|
||||
try {
|
||||
appContext.startObserving()
|
||||
|
||||
scope.safeLaunch { createAndroidHIDManager(context = this@ForegroundService, appContext = appContext, scope = this) }
|
||||
scope.safeLaunch { createAndroidSolarXRWebsocketServer(appContext) }
|
||||
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
appContext.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("WakelockTimeout")
|
||||
private fun acquireLocks() {
|
||||
val power = getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "slimevr:server")
|
||||
.apply { setReferenceCounted(false) }
|
||||
.also { it.acquire() }
|
||||
|
||||
val wifi = getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
multicastLock = wifi.createMulticastLock("slimevr-multicast-lock")
|
||||
.apply { setReferenceCounted(true) }
|
||||
.also { it.acquire() }
|
||||
@Suppress("DEPRECATION")
|
||||
wifiLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "slimevr-wifi-lock")
|
||||
.apply { setReferenceCounted(false) }
|
||||
.also { it.acquire() }
|
||||
}
|
||||
|
||||
private fun stopPendingIntent(): PendingIntent = PendingIntent.getService(
|
||||
this,
|
||||
0,
|
||||
Intent(this, ForegroundService::class.java).apply { action = ACTION_STOP },
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
val serviceChannel = NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManager.IMPORTANCE_LOW)
|
||||
.setName("SlimeVR Foreground Service Channel")
|
||||
@@ -79,9 +219,20 @@ class ForegroundService : Service() {
|
||||
.createNotificationChannel(serviceChannel)
|
||||
}
|
||||
|
||||
private fun openAppPendingIntent(): PendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent(this, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
|
||||
},
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun createNotification(): Notification = NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setContentTitle("SlimeVR Server Running")
|
||||
.setContentText("This notification helps keep the server alive")
|
||||
.setSmallIcon(R.drawable.ic_launcher_foreground)
|
||||
.setContentIntent(openAppPendingIntent())
|
||||
.addAction(0, getString(R.string.stop_server), stopPendingIntent())
|
||||
.build()
|
||||
}
|
||||
@@ -2,65 +2,9 @@
|
||||
|
||||
package dev.slimevr.android
|
||||
|
||||
import android.content.Context
|
||||
import android.net.wifi.WifiManager
|
||||
import android.content.Intent
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import dev.slimevr.Keybinding
|
||||
import dev.slimevr.VRServer
|
||||
import dev.slimevr.android.serial.AndroidSerialHandler
|
||||
import dev.slimevr.android.tracking.trackers.hid.AndroidHIDManager
|
||||
import dev.slimevr.config.ConfigManager
|
||||
import dev.slimevr.tracking.trackers.Tracker
|
||||
import io.eiren.util.logging.LogManager
|
||||
import java.io.File
|
||||
import kotlin.concurrent.thread
|
||||
import kotlin.system.exitProcess
|
||||
|
||||
lateinit var vrServer: VRServer
|
||||
private set
|
||||
val vrServerInitialized: Boolean
|
||||
get() = ::vrServer.isInitialized
|
||||
|
||||
fun startVRServer(activity: AppCompatActivity) {
|
||||
thread(start = true, name = "Main VRServer Thread") {
|
||||
try {
|
||||
LogManager.initialize(activity.filesDir)
|
||||
} catch (e1: java.lang.Exception) {
|
||||
e1.printStackTrace()
|
||||
}
|
||||
|
||||
try {
|
||||
val configPath = File(activity.filesDir, "vrconfig.yml").absolutePath
|
||||
val configManager = ConfigManager(configPath)
|
||||
configManager.loadConfig()
|
||||
|
||||
vrServer = VRServer(
|
||||
configManager = configManager,
|
||||
serialHandlerProvider = { _ -> AndroidSerialHandler(activity) },
|
||||
acquireMulticastLock = {
|
||||
val wifi = activity.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
val lock = wifi.createMulticastLock("slimevr-jmdns-multicast-lock")
|
||||
lock.setReferenceCounted(true)
|
||||
lock.acquire()
|
||||
},
|
||||
)
|
||||
vrServer.start()
|
||||
|
||||
// Start service for USB HID trackers
|
||||
val androidHidManager = AndroidHIDManager(
|
||||
"Sensors HID service",
|
||||
{ tracker: Tracker -> vrServer.registerTracker(tracker) },
|
||||
activity,
|
||||
)
|
||||
androidHidManager.start()
|
||||
|
||||
Keybinding(vrServer)
|
||||
vrServer.join()
|
||||
LogManager.closeLogger()
|
||||
exitProcess(0)
|
||||
} catch (e: Throwable) {
|
||||
e.printStackTrace()
|
||||
exitProcess(1)
|
||||
}
|
||||
}
|
||||
activity.startForegroundService(Intent(activity, ForegroundService::class.java))
|
||||
}
|
||||
@@ -1,18 +1,24 @@
|
||||
package dev.slimevr.android
|
||||
|
||||
import android.Manifest
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import io.eiren.util.logging.LogManager
|
||||
import androidx.core.content.ContextCompat
|
||||
import java.io.IOException
|
||||
import java.net.URLConnection
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
class AndroidJsObject {
|
||||
@JavascriptInterface
|
||||
@@ -20,36 +26,38 @@ class AndroidJsObject {
|
||||
}
|
||||
|
||||
class MainActivity : AppCompatActivity() {
|
||||
private val requestNotificationPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||
startVRServer(this)
|
||||
}
|
||||
|
||||
private val finishReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) = finishAndRemoveTask()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_main)
|
||||
|
||||
// Initialize logger (doesn't re-initialize if already run)
|
||||
try {
|
||||
LogManager.initialize(filesDir)
|
||||
} catch (e1: java.lang.Exception) {
|
||||
e1.printStackTrace()
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
finishReceiver,
|
||||
IntentFilter(ACTION_FINISH_APP),
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
} else {
|
||||
startVRServer(this)
|
||||
}
|
||||
|
||||
initLock.withLock {
|
||||
// Start the server if it isn't already running
|
||||
if (!vrServerInitialized) {
|
||||
LogManager.info("[MainActivity] VRServer isn't running yet, starting it...")
|
||||
startVRServer(this)
|
||||
} else {
|
||||
LogManager.info("[MainActivity] VRServer is already running, skipping initialization.")
|
||||
}
|
||||
}
|
||||
|
||||
// Load the web GUI web page
|
||||
LogManager.info("[MainActivity] Initializing GUI WebView...")
|
||||
Log.i(TAG, "Initializing GUI WebView...")
|
||||
val guiWebView = findViewById<WebView>(R.id.guiWebView)
|
||||
|
||||
// ## Configure for web GUI ##
|
||||
// Enable debug mode
|
||||
WebView.setWebContentsDebuggingEnabled(true)
|
||||
|
||||
// Handle path resolution
|
||||
guiWebView.webViewClient = object : WebViewClient() {
|
||||
override fun shouldInterceptRequest(
|
||||
view: WebView,
|
||||
@@ -78,30 +86,26 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
// Set required features
|
||||
guiWebView.settings.javaScriptEnabled = true
|
||||
guiWebView.settings.domStorageEnabled = true
|
||||
|
||||
// TODO: Let code know it is in android, should be gone when we start using tauri
|
||||
guiWebView.addJavascriptInterface(AndroidJsObject(), "__ANDROID__")
|
||||
|
||||
// Try fixing zoom usability
|
||||
guiWebView.settings.setSupportZoom(true)
|
||||
guiWebView.settings.useWideViewPort = true
|
||||
guiWebView.settings.loadWithOverviewMode = true
|
||||
guiWebView.invokeZoomPicker()
|
||||
|
||||
// Load GUI page
|
||||
guiWebView.loadUrl("https://slimevr.gui/")
|
||||
LogManager.info("[MainActivity] GUI WebView has been initialized and loaded.")
|
||||
Log.i(TAG, "GUI WebView initialized.")
|
||||
}
|
||||
|
||||
// Start a foreground service to notify the user the SlimeVR Server is running
|
||||
// This also helps prevent Android from ejecting the process unexpectedly
|
||||
val serviceIntent = Intent(this, ForegroundService::class.java)
|
||||
startForegroundService(serviceIntent)
|
||||
override fun onDestroy() {
|
||||
unregisterReceiver(finishReceiver)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
val initLock = ReentrantLock()
|
||||
private const val TAG = "MainActivity"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package dev.slimevr.android.config
|
||||
|
||||
import dev.slimevr.config.ConfigStorage
|
||||
import dev.slimevr.config.TextFileHandle
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
class AndroidConfigStorage(private val root: File) : ConfigStorage {
|
||||
override suspend fun read(path: String): String? = withContext(Dispatchers.IO) {
|
||||
val file = resolve(path)
|
||||
if (file.exists()) file.readText() else null
|
||||
}
|
||||
|
||||
override suspend fun write(path: String, content: String) = withContext(Dispatchers.IO) {
|
||||
val file = resolve(path)
|
||||
file.parentFile?.mkdirs()
|
||||
val tmp = File(file.parent, "${file.name}.tmp")
|
||||
tmp.writeText(content)
|
||||
Files.move(tmp.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
|
||||
Unit
|
||||
}
|
||||
|
||||
override suspend fun backup(path: String) = withContext(Dispatchers.IO) {
|
||||
val file = resolve(path)
|
||||
if (!file.exists()) return@withContext
|
||||
val bakTmp = File(file.parent, "${file.name}.bak.tmp")
|
||||
file.copyTo(bakTmp, overwrite = true)
|
||||
Files.move(
|
||||
bakTmp.toPath(),
|
||||
File(file.parent, "${file.name}.bak").toPath(),
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING,
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun exists(path: String): Boolean = withContext(Dispatchers.IO) {
|
||||
resolve(path).exists()
|
||||
}
|
||||
|
||||
override suspend fun ensureDirectory(path: String): Boolean = withContext(Dispatchers.IO) {
|
||||
val directory = resolve(path)
|
||||
directory.isDirectory || directory.mkdirs()
|
||||
}
|
||||
|
||||
override suspend fun openTextFile(path: String): TextFileHandle = withContext(Dispatchers.IO) {
|
||||
val file = resolve(path)
|
||||
file.parentFile?.mkdirs()
|
||||
AndroidRandomAccessTextFileHandle(RandomAccessFile(file, "rw").also { handle -> handle.setLength(0L) })
|
||||
}
|
||||
|
||||
override fun displayPath(path: String): String = resolve(path).absolutePath
|
||||
|
||||
private fun resolve(path: String): File {
|
||||
val requested = File(path)
|
||||
return if (requested.isAbsolute) requested else File(root, path)
|
||||
}
|
||||
}
|
||||
|
||||
private class AndroidRandomAccessTextFileHandle(
|
||||
private val file: RandomAccessFile,
|
||||
) : TextFileHandle {
|
||||
override suspend fun write(text: String) = withContext(Dispatchers.IO) {
|
||||
file.write(text.encodeToByteArray())
|
||||
}
|
||||
|
||||
override suspend fun flush() = withContext(Dispatchers.IO) {
|
||||
file.fd.sync()
|
||||
}
|
||||
|
||||
override suspend fun position(): Long = withContext(Dispatchers.IO) {
|
||||
file.filePointer
|
||||
}
|
||||
|
||||
override suspend fun seek(position: Long) = withContext(Dispatchers.IO) {
|
||||
file.seek(position)
|
||||
}
|
||||
|
||||
override suspend fun close() = withContext(Dispatchers.IO) {
|
||||
file.fd.sync()
|
||||
file.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package dev.slimevr.android.hid
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.hardware.usb.UsbConstants
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbEndpoint
|
||||
import android.hardware.usb.UsbInterface
|
||||
import android.hardware.usb.UsbManager
|
||||
import androidx.core.content.ContextCompat
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.AppLogger
|
||||
import dev.slimevr.device.DeviceActions
|
||||
import dev.slimevr.hid.HIDReceiver
|
||||
import dev.slimevr.hid.isCompatibleHidDevice
|
||||
import dev.slimevr.hid.parseHIDPackets
|
||||
import dev.slimevr.util.safeLaunch
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import solarxr_protocol.datatypes.TrackerStatus
|
||||
|
||||
private const val ACTION_USB_HID_PERMISSION = "dev.slimevr.android.USB_HID_PERMISSION"
|
||||
private const val HID_POLL_INTERVAL_MS = 3000L
|
||||
|
||||
private fun findHidInputEndpoint(device: UsbDevice): Pair<UsbInterface, UsbEndpoint>? {
|
||||
for (ifaceIdx in 0 until device.interfaceCount) {
|
||||
val iface = device.getInterface(ifaceIdx)
|
||||
if (iface.interfaceClass != UsbConstants.USB_CLASS_HID) continue
|
||||
for (epIdx in 0 until iface.endpointCount) {
|
||||
val endpoint = iface.getEndpoint(epIdx)
|
||||
if (endpoint.type == UsbConstants.USB_ENDPOINT_XFER_INT &&
|
||||
endpoint.direction == UsbConstants.USB_DIR_IN
|
||||
) {
|
||||
return iface to endpoint
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private data class ActiveReceiver(val job: Job, val receiver: HIDReceiver)
|
||||
|
||||
fun createAndroidHIDManager(context: Context, appContext: AppContextProvider, scope: CoroutineScope) {
|
||||
val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
val wakeSignal = Channel<Unit>(Channel.CONFLATED)
|
||||
val permissionRequested = mutableSetOf<String>()
|
||||
val active = mutableMapOf<String, ActiveReceiver>()
|
||||
|
||||
val permissionIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
0,
|
||||
Intent(ACTION_USB_HID_PERMISSION).apply { setPackage(context.packageName) },
|
||||
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
val usbReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(ctx: Context, intent: Intent) {
|
||||
wakeSignal.trySend(Unit)
|
||||
}
|
||||
}
|
||||
|
||||
val intentFilter = IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED).apply {
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
addAction(ACTION_USB_HID_PERMISSION)
|
||||
}
|
||||
ContextCompat.registerReceiver(context, usbReceiver, intentFilter, ContextCompat.RECEIVER_NOT_EXPORTED)
|
||||
|
||||
scope.safeLaunch {
|
||||
while (isActive) {
|
||||
val found = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
usbManager.deviceList.values
|
||||
.filter { device -> isCompatibleHidDevice(device.vendorId, device.productId) }
|
||||
.associate { device -> device.deviceName to device }
|
||||
} catch (e: Exception) {
|
||||
AppLogger.hid.error(e, "HID enumeration failed")
|
||||
emptyMap()
|
||||
}
|
||||
}
|
||||
|
||||
for ((deviceName, device) in found) {
|
||||
if (!usbManager.hasPermission(device) && deviceName !in permissionRequested) {
|
||||
AppLogger.hid.info("Requesting USB HID permission for $deviceName")
|
||||
usbManager.requestPermission(device, permissionIntent)
|
||||
permissionRequested.add(deviceName)
|
||||
}
|
||||
}
|
||||
|
||||
val authorized = found.filter { (_, device) -> usbManager.hasPermission(device) }
|
||||
|
||||
val toRemove = (active.keys - authorized.keys) +
|
||||
active.entries.filter { (_, entry) -> !entry.job.isActive }.map { (key, _) -> key }
|
||||
for (deviceName in toRemove) {
|
||||
val entry = active.remove(deviceName) ?: continue
|
||||
entry.job.cancel()
|
||||
entry.job.join()
|
||||
permissionRequested.remove(deviceName)
|
||||
AppLogger.hid.info("HID device removed: $deviceName")
|
||||
}
|
||||
|
||||
for ((deviceName, device) in authorized) {
|
||||
if (deviceName in active) continue
|
||||
permissionRequested.remove(deviceName)
|
||||
|
||||
val hidEndpoint = findHidInputEndpoint(device)
|
||||
if (hidEndpoint == null) {
|
||||
AppLogger.hid.warn("No HID input endpoint found for $deviceName")
|
||||
continue
|
||||
}
|
||||
val (iface, endpoint) = hidEndpoint
|
||||
|
||||
val connection = withContext(Dispatchers.IO) { usbManager.openDevice(device) }
|
||||
if (connection == null) {
|
||||
AppLogger.hid.warn("Failed to open HID device $deviceName")
|
||||
continue
|
||||
}
|
||||
|
||||
connection.claimInterface(iface, true)
|
||||
|
||||
val serial = device.serialNumber ?: deviceName
|
||||
AppLogger.hid.info("HID device detected: $serial")
|
||||
|
||||
val deviceJob = Job(scope.coroutineContext[Job])
|
||||
val deviceScope = CoroutineScope(scope.coroutineContext + deviceJob)
|
||||
|
||||
val receiver = HIDReceiver.create(
|
||||
serialNumber = serial,
|
||||
appContext = appContext,
|
||||
scope = deviceScope,
|
||||
)
|
||||
|
||||
deviceScope.safeLaunch {
|
||||
try {
|
||||
val buffer = ByteArray(64)
|
||||
while (isActive) {
|
||||
val read = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
connection.bulkTransfer(endpoint, buffer, buffer.size, 0)
|
||||
} catch (_: Exception) {
|
||||
-1
|
||||
}
|
||||
}
|
||||
when {
|
||||
read < 0 -> return@safeLaunch
|
||||
read > 0 -> parseHIDPackets(buffer.copyOf(read)).forEach { packet -> receiver.packetEvents.emit(packet) }
|
||||
else -> delay(1)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
withContext(NonCancellable + Dispatchers.IO) {
|
||||
connection.releaseInterface(iface)
|
||||
connection.close()
|
||||
}
|
||||
withContext(NonCancellable) {
|
||||
for (record in receiver.context.state.value.trackers.values) {
|
||||
appContext.server.getDevice(record.deviceId)?.context?.dispatch(
|
||||
DeviceActions.Update { copy(status = TrackerStatus.DISCONNECTED) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
deviceJob.complete()
|
||||
|
||||
active[deviceName] = ActiveReceiver(deviceJob, receiver)
|
||||
}
|
||||
|
||||
permissionRequested.retainAll(found.keys)
|
||||
withTimeoutOrNull(HID_POLL_INTERVAL_MS) { wakeSignal.receive() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package dev.slimevr.android.ipc
|
||||
|
||||
import com.google.flatbuffers.FlatBufferBuilder
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.AppLogger
|
||||
import dev.slimevr.VRServerActions
|
||||
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferReader
|
||||
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferWriter
|
||||
import dev.slimevr.solarxr.SolarXRBridge
|
||||
import dev.slimevr.solarxr.onSolarXRMessage
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.server.cio.CIO
|
||||
import io.ktor.server.engine.embeddedServer
|
||||
import io.ktor.server.routing.routing
|
||||
import io.ktor.server.websocket.WebSockets
|
||||
import io.ktor.server.websocket.webSocket
|
||||
import io.ktor.util.moveToByteArray
|
||||
import io.ktor.websocket.Frame
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import solarxr_protocol.MessageBundle
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
const val SOLARXR_PORT = 21110
|
||||
|
||||
suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider) {
|
||||
val engine = embeddedServer(CIO, port = SOLARXR_PORT) {
|
||||
install(WebSockets)
|
||||
|
||||
routing {
|
||||
webSocket {
|
||||
AppLogger.ipc.info("New connection")
|
||||
coroutineScope {
|
||||
val bridge = SolarXRBridge.create(
|
||||
id = appContext.server.nextHandle(),
|
||||
appContext = appContext,
|
||||
scope = this,
|
||||
)
|
||||
|
||||
appContext.server.context.dispatch(VRServerActions.SolarXRConnected(bridge))
|
||||
|
||||
bridge.outbound.on<MessageBundle> { bundle ->
|
||||
val fbb = FlatBufferBuilder(256)
|
||||
fbb.finish(bundle.encode(JvmFlatBufferWriter(fbb)))
|
||||
send(Frame.Binary(fin = true, data = fbb.dataBuffer().moveToByteArray()))
|
||||
}
|
||||
|
||||
try {
|
||||
flow {
|
||||
for (frame in incoming) {
|
||||
when (frame) {
|
||||
is Frame.Binary -> emit(frame.data)
|
||||
is Frame.Close -> AppLogger.ipc.info("Connection closed")
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}.collect { bytes ->
|
||||
val reader = JvmFlatBufferReader(ByteBuffer.wrap(bytes))
|
||||
onSolarXRMessage(MessageBundle.decode(reader, reader.getInt(0)), bridge)
|
||||
}
|
||||
} finally {
|
||||
bridge.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
engine.start(wait = false)
|
||||
try {
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dev.slimevr.android
|
||||
|
||||
import io.klogging.Level
|
||||
import io.klogging.config.loggingConfiguration
|
||||
import io.klogging.sending.ANDROID
|
||||
|
||||
fun setupAndroidLogging() {
|
||||
loggingConfiguration {
|
||||
sink("android", ANDROID)
|
||||
logging {
|
||||
fromMinLevel(Level.DEBUG) {
|
||||
toSink("android")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
package dev.slimevr.android.serial
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.hardware.usb.UsbManager
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.hoho.android.usbserial.driver.UsbSerialDriver
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort
|
||||
import com.hoho.android.usbserial.driver.UsbSerialProber
|
||||
import com.hoho.android.usbserial.util.SerialInputOutputManager
|
||||
import dev.slimevr.serial.SerialHandler
|
||||
import dev.slimevr.serial.SerialListener
|
||||
import dev.slimevr.tracking.trackers.hid.HIDCommon
|
||||
import io.eiren.util.logging.LogManager
|
||||
import java.io.IOException
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.stream.Stream
|
||||
import kotlin.streams.asSequence
|
||||
import kotlin.streams.asStream
|
||||
import dev.slimevr.serial.SerialPort as SlimeSerialPort
|
||||
|
||||
class SerialPortWrapper(val port: UsbSerialPort) : SlimeSerialPort() {
|
||||
override val portLocation: String
|
||||
get() = port.device.deviceName
|
||||
override val descriptivePortName: String
|
||||
get() = "${port.device.productName} (${port.device.deviceName})"
|
||||
|
||||
override val vendorId: Int
|
||||
get() = port.device.vendorId
|
||||
|
||||
override val productId: Int
|
||||
get() = port.device.productId
|
||||
}
|
||||
|
||||
class AndroidSerialHandler(val activity: AppCompatActivity) :
|
||||
SerialHandler(),
|
||||
SerialInputOutputManager.Listener {
|
||||
|
||||
private var usbIoManager: SerialInputOutputManager? = null
|
||||
|
||||
private val listeners: MutableList<SerialListener> = CopyOnWriteArrayList()
|
||||
private var lastKnownPorts = setOf<SerialPortWrapper>()
|
||||
private val manager = activity.getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
private var currentPort: SerialPortWrapper? = null
|
||||
private var requestingPermission: String = ""
|
||||
private var readBuffer: StringBuilder = StringBuilder(1024)
|
||||
|
||||
override val isConnected: Boolean
|
||||
get() = currentPort?.port?.isOpen ?: false
|
||||
|
||||
override val knownPorts: Stream<SerialPortWrapper>
|
||||
get() = getPorts()
|
||||
.asSequence()
|
||||
.map { SerialPortWrapper(it.ports[0]) }
|
||||
.filter { isKnownBoard(it) || HIDCommon.matchesAny(it.vendorId, it.productId) }
|
||||
.asStream()
|
||||
|
||||
val usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
UsbManager.ACTION_USB_DEVICE_ATTACHED, UsbManager.ACTION_USB_DEVICE_DETACHED -> {
|
||||
// Use device from `UsbManager.EXTRA_DEVICE` if this is a problem
|
||||
detectNewPorts()
|
||||
}
|
||||
|
||||
ACTION_USB_PERMISSION -> {
|
||||
// TODO: We can probably receive this event in the server to avoid
|
||||
// polling, but for now we can just ignore it. (Note: This event is
|
||||
// not currently registered, so it will never fire.)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
val intentFilter = IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED)
|
||||
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
|
||||
// Listen for USB device attach/detach
|
||||
ContextCompat.registerReceiver(
|
||||
activity,
|
||||
usbReceiver,
|
||||
intentFilter,
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
|
||||
// Detect initial serial ports
|
||||
detectNewPorts()
|
||||
}
|
||||
|
||||
private fun getPorts(): List<UsbSerialDriver> = UsbSerialProber.getDefaultProber().findAllDrivers(manager)
|
||||
|
||||
private fun onNewDevice(port: SerialPortWrapper) {
|
||||
// If we missed clearing this on disconnect/close, clear it on discovery
|
||||
if (requestingPermission == port.portLocation) {
|
||||
requestingPermission = ""
|
||||
}
|
||||
|
||||
LogManager.info("[SerialHandler] Device added: ${port.descriptivePortName}")
|
||||
listeners.forEach { it.onNewSerialDevice(port) }
|
||||
}
|
||||
|
||||
private fun onDeviceDel(port: SerialPortWrapper) {
|
||||
// Remove permission request on disconnect so reconnecting re-requests
|
||||
if (requestingPermission == port.portLocation) {
|
||||
requestingPermission = ""
|
||||
}
|
||||
|
||||
// If we're currently using this port, close it
|
||||
currentPort?.portLocation.let { currentPortLocation ->
|
||||
if (currentPortLocation == port.portLocation) {
|
||||
closeSerial()
|
||||
}
|
||||
}
|
||||
|
||||
// If this port is still open for whatever reason, close it
|
||||
if (port.port.isOpen) {
|
||||
port.port.close()
|
||||
}
|
||||
|
||||
LogManager.info("[SerialHandler] Device removed: ${port.descriptivePortName}")
|
||||
listeners.forEach { it.onSerialDeviceDeleted(port) }
|
||||
}
|
||||
|
||||
private fun detectNewPorts() {
|
||||
val addDifferences = knownPorts.asSequence() - lastKnownPorts
|
||||
val delDifferences = lastKnownPorts - knownPorts.asSequence().toSet()
|
||||
lastKnownPorts = knownPorts.asSequence().toSet()
|
||||
addDifferences.forEach { onNewDevice(it) }
|
||||
delDifferences.forEach { onDeviceDel(it) }
|
||||
}
|
||||
|
||||
override fun addListener(channel: SerialListener) {
|
||||
listeners.add(channel)
|
||||
}
|
||||
|
||||
override fun removeListener(channel: SerialListener) {
|
||||
listeners.removeIf { channel === it }
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun openSerial(portLocation: String?, auto: Boolean, autoIncludeHid: Boolean): Boolean {
|
||||
LogManager.info("[SerialHandler] Trying to open: $portLocation, auto: $auto")
|
||||
lastKnownPorts = knownPorts.asSequence().toSet()
|
||||
val newPort = lastKnownPorts.find {
|
||||
(!auto && it.portLocation == portLocation) || (auto && isKnownBoard(it)) || (auto && autoIncludeHid && HIDCommon.matchesAny(it.vendorId, it.productId))
|
||||
}
|
||||
|
||||
if (newPort == null) {
|
||||
LogManager.info(
|
||||
"[SerialHandler] No serial ports found to connect to (${lastKnownPorts.size}) total ports",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
if (isConnected) {
|
||||
val port = currentPort!!
|
||||
if (newPort != port) {
|
||||
LogManager.info(
|
||||
"[SerialHandler] Closing current serial port " +
|
||||
port.descriptivePortName,
|
||||
)
|
||||
closeSerial()
|
||||
} else {
|
||||
LogManager.info("[SerialHandler] Reusing already open port")
|
||||
listeners.forEach { it.onSerialConnected(port) }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
LogManager.info(
|
||||
"[SerialHandler] Trying to connect to new serial port " +
|
||||
newPort.descriptivePortName,
|
||||
)
|
||||
|
||||
if (!manager.hasPermission(newPort.port.device)) {
|
||||
val flags = PendingIntent.FLAG_IMMUTABLE
|
||||
val usbPermissionIntent = PendingIntent.getBroadcast(
|
||||
activity,
|
||||
0,
|
||||
Intent(ACTION_USB_PERMISSION),
|
||||
flags,
|
||||
)
|
||||
if (requestingPermission != newPort.portLocation) {
|
||||
LogManager.info("[SerialHandler] Requesting permission for ${newPort.portLocation}")
|
||||
manager.requestPermission(newPort.port.device, usbPermissionIntent)
|
||||
requestingPermission = newPort.portLocation
|
||||
} else {
|
||||
LogManager.info("[SerialHandler] Already requested permission for ${newPort.portLocation}, skipping")
|
||||
}
|
||||
LogManager.warning(
|
||||
"[SerialHandler] Can't open serial port ${newPort.descriptivePortName}, invalid permissions",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
// If we have permission, we aren't requesting anymore
|
||||
requestingPermission = ""
|
||||
|
||||
val connection = manager.openDevice(newPort.port.device)
|
||||
if (connection == null) {
|
||||
LogManager.warning(
|
||||
"[SerialHandler] Can't open serial port ${newPort.descriptivePortName}, connection failed",
|
||||
)
|
||||
return false
|
||||
}
|
||||
newPort.port.open(connection)
|
||||
newPort.port.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE)
|
||||
usbIoManager = SerialInputOutputManager(newPort.port, this).apply {
|
||||
start()
|
||||
}
|
||||
listeners.forEach { it.onSerialConnected(newPort) }
|
||||
currentPort = newPort
|
||||
LogManager.info("[SerialHandler] Serial port ${newPort.descriptivePortName} is open")
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun writeSerial(serialText: String, print: Boolean = false) {
|
||||
try {
|
||||
currentPort?.port?.write("${serialText}\n".toByteArray(), 0)
|
||||
if (print) {
|
||||
addLog("-> $serialText\n")
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
addLog("[!] Serial error: ${e.message}\n")
|
||||
LogManager.warning("[SerialHandler] Serial port write error", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun rebootRequest() {
|
||||
writeSerial("REBOOT")
|
||||
}
|
||||
|
||||
override fun factoryResetRequest() {
|
||||
writeSerial("FRST")
|
||||
}
|
||||
|
||||
override fun infoRequest() {
|
||||
writeSerial("GET INFO")
|
||||
}
|
||||
|
||||
override fun wifiScanRequest() {
|
||||
writeSerial("GET WIFISCAN")
|
||||
}
|
||||
|
||||
override fun customCommandRequest(command: String) {
|
||||
writeSerial(command)
|
||||
}
|
||||
|
||||
override fun closeSerial() {
|
||||
try {
|
||||
if (isConnected) {
|
||||
currentPort?.port?.close()
|
||||
}
|
||||
listeners.forEach { it.onSerialDisconnected() }
|
||||
LogManager.info(
|
||||
"[SerialHandler] Port ${currentPort?.descriptivePortName} closed okay",
|
||||
)
|
||||
usbIoManager?.stop()
|
||||
usbIoManager = null
|
||||
currentPort = null
|
||||
requestingPermission = ""
|
||||
readBuffer.clear()
|
||||
} catch (e: Exception) {
|
||||
LogManager.warning(
|
||||
"[SerialHandler] Error closing port ${currentPort?.descriptivePortName}",
|
||||
e,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun write(buff: ByteArray) {
|
||||
currentPort?.port?.write(buff, 0)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun setWifi(ssid: String, passwd: String) {
|
||||
writeSerial("SET WIFI \"${ssid}\" \"${passwd}\"")
|
||||
addLog("-> SET WIFI \"$ssid\" \"${passwd.replace(".".toRegex(), "*")}\"\n")
|
||||
}
|
||||
|
||||
override fun getCurrentPort(): SlimeSerialPort? = this.currentPort
|
||||
|
||||
private fun addLog(str: String, server: Boolean = true) {
|
||||
LogManager.info("[Serial] $str")
|
||||
listeners.forEach { it.onSerialLog(str, server) }
|
||||
}
|
||||
|
||||
override fun onNewData(data: ByteArray?) {
|
||||
if (data != null) {
|
||||
// Collect serial in a buffer until newline (or character limit)
|
||||
// This is somewhat of a workaround for Android serial buffer being smaller
|
||||
// than on desktop, so we don't read full lines and it causes parsing issues
|
||||
readBuffer.append(StandardCharsets.UTF_8.decode(ByteBuffer.wrap(data)))
|
||||
|
||||
if (readBuffer.contains('\n') || readBuffer.length >= 1024) {
|
||||
addLog(readBuffer.toString(), false)
|
||||
readBuffer.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRunError(e: java.lang.Exception?) {}
|
||||
|
||||
companion object {
|
||||
private const val ACTION_USB_PERMISSION = "dev.slimevr.USB_PERMISSION"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package dev.slimevr.android.serial
|
||||
|
||||
import android.hardware.usb.UsbManager
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort
|
||||
import com.hoho.android.usbserial.driver.UsbSerialProber
|
||||
import dev.llelievr.espflashkotlin.Flasher
|
||||
import dev.llelievr.espflashkotlin.FlasherSerialInterface
|
||||
import dev.llelievr.espflashkotlin.FlashingProgressListener
|
||||
import dev.slimevr.firmware.DownloadedFirmwarePart
|
||||
import dev.slimevr.firmware.FirmwareFlasher
|
||||
import dev.slimevr.serial.FlashingHandler
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class AndroidFlashingHandler(private val usbManager: UsbManager) : FlashingHandler {
|
||||
private var port: UsbSerialPort? = null
|
||||
private var readTimeout: Int = 1000
|
||||
private val pendingBytes = ArrayDeque<Byte>()
|
||||
|
||||
override fun openSerial(portObj: Any) {
|
||||
val portLocation = portObj as? String ?: error("expected port location string")
|
||||
val driver = UsbSerialProber.getDefaultProber()
|
||||
.findAllDrivers(usbManager)
|
||||
.find { driver -> driver.device.deviceName == portLocation }
|
||||
?: error("Unable to find serial port $portLocation")
|
||||
|
||||
val connection = usbManager.openDevice(driver.device)
|
||||
?: error("Unable to open USB device for $portLocation")
|
||||
|
||||
val usbPort = driver.ports[0]
|
||||
usbPort.open(connection)
|
||||
usbPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
|
||||
this.port = usbPort
|
||||
}
|
||||
|
||||
override fun closeSerial() {
|
||||
port?.close()
|
||||
port = null
|
||||
pendingBytes.clear()
|
||||
}
|
||||
|
||||
override fun write(data: ByteArray) {
|
||||
val p = port ?: error("no port to write")
|
||||
p.write(data, readTimeout)
|
||||
}
|
||||
|
||||
override fun read(length: Int): ByteArray {
|
||||
val p = port ?: error("no port to read")
|
||||
val result = ByteArray(length)
|
||||
var offset = 0
|
||||
|
||||
while (offset < length && pendingBytes.isNotEmpty()) {
|
||||
result[offset++] = pendingBytes.removeFirst()
|
||||
}
|
||||
|
||||
if (offset < length) {
|
||||
val remaining = ByteArray(length - offset)
|
||||
val read = p.read(remaining, readTimeout)
|
||||
remaining.copyInto(result, offset, 0, read)
|
||||
offset += read
|
||||
}
|
||||
|
||||
return result.copyOf(offset)
|
||||
}
|
||||
|
||||
override fun setDTR(value: Boolean) {
|
||||
val p = port ?: error("no port to set DTR")
|
||||
p.setDTR(value)
|
||||
}
|
||||
|
||||
override fun setRTS(value: Boolean) {
|
||||
val p = port ?: error("no port to set RTS")
|
||||
p.setRTS(value)
|
||||
}
|
||||
|
||||
override fun changeBaud(baud: Int) {
|
||||
val p = port ?: error("no port to change baud")
|
||||
p.setParameters(baud, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
|
||||
}
|
||||
|
||||
override fun setReadTimeout(timeout: Long) {
|
||||
readTimeout = timeout.toInt().coerceAtLeast(1)
|
||||
}
|
||||
|
||||
override fun availableBytes(): Int {
|
||||
val p = port ?: return 0
|
||||
val peekBuffer = ByteArray(256)
|
||||
val count = try {
|
||||
p.read(peekBuffer, 0)
|
||||
} catch (_: Exception) {
|
||||
0
|
||||
}
|
||||
for (i in 0 until count) pendingBytes.addLast(peekBuffer[i])
|
||||
return pendingBytes.size
|
||||
}
|
||||
|
||||
override fun flushIOBuffers() {
|
||||
val p = port ?: error("no port to flush")
|
||||
pendingBytes.clear()
|
||||
p.purgeHwBuffers(true, true)
|
||||
}
|
||||
}
|
||||
|
||||
object AndroidFirmwareFlasher : FirmwareFlasher {
|
||||
override suspend fun flash(
|
||||
portLocation: String,
|
||||
handler: FlashingHandler,
|
||||
parts: List<DownloadedFirmwarePart>,
|
||||
onProgress: (Int) -> Unit,
|
||||
) {
|
||||
val flasher = Flasher(
|
||||
object : FlasherSerialInterface {
|
||||
override fun openSerial(port: Any) = handler.openSerial(port)
|
||||
override fun closeSerial() = handler.closeSerial()
|
||||
override fun write(data: ByteArray) = handler.write(data)
|
||||
override fun read(length: Int) = handler.read(length)
|
||||
override fun setDTR(value: Boolean) = handler.setDTR(value)
|
||||
override fun setRTS(value: Boolean) = handler.setRTS(value)
|
||||
override fun changeBaud(baud: Int) = handler.changeBaud(baud)
|
||||
override fun setReadTimeout(timeout: Long) = handler.setReadTimeout(timeout)
|
||||
override fun availableBytes() = handler.availableBytes()
|
||||
override fun flushIOBuffers() = handler.flushIOBuffers()
|
||||
},
|
||||
)
|
||||
for (part in parts) {
|
||||
flasher.addBin(part.data, part.offset)
|
||||
}
|
||||
flasher.addProgressListener(
|
||||
object : FlashingProgressListener {
|
||||
override fun progress(progress: Float) {
|
||||
onProgress((progress * 100).toInt())
|
||||
}
|
||||
},
|
||||
)
|
||||
withContext(Dispatchers.IO) { flasher.flash(portLocation) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package dev.slimevr.android.serial
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.hardware.usb.UsbManager
|
||||
import android.util.Log
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort
|
||||
import com.hoho.android.usbserial.driver.UsbSerialProber
|
||||
import com.hoho.android.usbserial.util.SerialInputOutputManager
|
||||
import dev.slimevr.AppLogger
|
||||
import dev.slimevr.serial.SerialPortHandle
|
||||
import dev.slimevr.serial.SerialPortInfo
|
||||
import dev.slimevr.serial.SerialServer
|
||||
import dev.slimevr.serial.isKnownSerialBoard
|
||||
import dev.slimevr.util.safeLaunch
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
private const val TAG = "SerialServer"
|
||||
|
||||
private const val ACTION_USB_SERIAL_PERMISSION = "dev.slimevr.android.USB_SERIAL_PERMISSION"
|
||||
private const val POLL_INTERVAL_MS = 3000L
|
||||
|
||||
private fun openAndroidPort(
|
||||
portLocation: String,
|
||||
usbManager: UsbManager,
|
||||
scope: CoroutineScope,
|
||||
onDataReceived: suspend (String, String) -> Unit,
|
||||
onPortDisconnected: suspend (String) -> Unit,
|
||||
): SerialPortHandle? {
|
||||
val driver = UsbSerialProber.getDefaultProber()
|
||||
.findAllDrivers(usbManager)
|
||||
.find { driver -> driver.device.deviceName == portLocation }
|
||||
?: return null
|
||||
|
||||
if (!usbManager.hasPermission(driver.device)) return null
|
||||
|
||||
val connection = usbManager.openDevice(driver.device) ?: return null
|
||||
val port = driver.ports[0]
|
||||
|
||||
try {
|
||||
port.open(connection)
|
||||
port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
|
||||
port.dtr = false
|
||||
port.rts = false
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to open Android serial port $portLocation", e)
|
||||
try {
|
||||
connection.close()
|
||||
} catch (_: Exception) {}
|
||||
return null
|
||||
}
|
||||
|
||||
val readBuffer = StringBuilder(1024)
|
||||
|
||||
val ioManager = SerialInputOutputManager(
|
||||
port,
|
||||
object : SerialInputOutputManager.Listener {
|
||||
override fun onNewData(data: ByteArray) {
|
||||
readBuffer.append(data.toString(Charsets.UTF_8))
|
||||
var newlineIdx = readBuffer.indexOf("\n")
|
||||
while (newlineIdx >= 0) {
|
||||
val line = readBuffer.substring(0, newlineIdx).trimEnd()
|
||||
readBuffer.delete(0, newlineIdx + 1)
|
||||
scope.safeLaunch { onDataReceived(portLocation, line) }
|
||||
newlineIdx = readBuffer.indexOf("\n")
|
||||
}
|
||||
if (readBuffer.length >= 1024) readBuffer.clear()
|
||||
}
|
||||
|
||||
override fun onRunError(e: Exception) {
|
||||
scope.safeLaunch { onPortDisconnected(portLocation) }
|
||||
}
|
||||
},
|
||||
)
|
||||
ioManager.start()
|
||||
|
||||
return SerialPortHandle(
|
||||
portLocation = portLocation,
|
||||
descriptivePortName = "${driver.device.productName ?: portLocation} ($portLocation)",
|
||||
writeCommand = { text -> port.write("$text\n".toByteArray(), 0) },
|
||||
close = {
|
||||
ioManager.stop()
|
||||
try {
|
||||
port.close()
|
||||
} catch (_: Exception) {}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun runAndroidSerialPoller(
|
||||
context: Context,
|
||||
usbManager: UsbManager,
|
||||
server: SerialServer,
|
||||
wakeSignal: Channel<Unit>,
|
||||
) {
|
||||
val permissionRequested = mutableSetOf<String>()
|
||||
var lastKnown: Set<String> = emptySet()
|
||||
val permissionIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
0,
|
||||
Intent(ACTION_USB_SERIAL_PERMISSION).apply { setPackage(context.packageName) },
|
||||
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
val current = withContext(Dispatchers.IO) {
|
||||
UsbSerialProber.getDefaultProber()
|
||||
.findAllDrivers(usbManager)
|
||||
.filter { driver -> isKnownSerialBoard(driver.device.vendorId, driver.device.productId) }
|
||||
.associateBy { driver -> driver.device.deviceName }
|
||||
}
|
||||
|
||||
for ((deviceName, driver) in current) {
|
||||
if (!usbManager.hasPermission(driver.device) && deviceName !in permissionRequested) {
|
||||
AppLogger.serial.info("Requesting USB serial permission for $deviceName")
|
||||
usbManager.requestPermission(driver.device, permissionIntent)
|
||||
permissionRequested.add(deviceName)
|
||||
}
|
||||
}
|
||||
|
||||
val authorized = current.filter { (_, driver) -> usbManager.hasPermission(driver.device) }
|
||||
|
||||
val added = authorized.keys - lastKnown
|
||||
val removed = lastKnown - authorized.keys
|
||||
|
||||
for (loc in added) {
|
||||
val driver = authorized.getValue(loc)
|
||||
permissionRequested.remove(loc)
|
||||
server.onPortDetected(
|
||||
SerialPortInfo(
|
||||
portLocation = loc,
|
||||
descriptivePortName = "${driver.device.productName ?: loc} ($loc)",
|
||||
vendorId = driver.device.vendorId,
|
||||
productId = driver.device.productId,
|
||||
),
|
||||
)
|
||||
}
|
||||
for (loc in removed) {
|
||||
server.onPortLost(loc)
|
||||
}
|
||||
|
||||
lastKnown = authorized.keys
|
||||
permissionRequested.retainAll(current.keys)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.serial.error(e, "Error polling Android serial ports")
|
||||
}
|
||||
|
||||
withTimeoutOrNull(POLL_INTERVAL_MS) { wakeSignal.receive() }
|
||||
}
|
||||
}
|
||||
|
||||
fun createAndroidSerialServer(context: Context, scope: CoroutineScope): SerialServer {
|
||||
val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
val wakeSignal = Channel<Unit>(Channel.CONFLATED)
|
||||
|
||||
val usbReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(ctx: Context, intent: Intent) {
|
||||
wakeSignal.trySend(Unit)
|
||||
}
|
||||
}
|
||||
|
||||
val intentFilter = IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED).apply {
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
addAction(ACTION_USB_SERIAL_PERMISSION)
|
||||
}
|
||||
ContextCompat.registerReceiver(context, usbReceiver, intentFilter, ContextCompat.RECEIVER_NOT_EXPORTED)
|
||||
|
||||
val server = SerialServer.create(
|
||||
openPort = { portLocation, onDataReceived, onPortDisconnected ->
|
||||
openAndroidPort(portLocation, usbManager, scope, onDataReceived, onPortDisconnected)
|
||||
},
|
||||
openFlashingPort = { AndroidFlashingHandler(usbManager) },
|
||||
scope = scope,
|
||||
)
|
||||
|
||||
scope.safeLaunch { runAndroidSerialPoller(context, usbManager, server, wakeSignal) }
|
||||
|
||||
return server
|
||||
}
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
package dev.slimevr.android.tracking.trackers.hid
|
||||
|
||||
import android.hardware.usb.UsbConstants
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbDeviceConnection
|
||||
import android.hardware.usb.UsbEndpoint
|
||||
import android.hardware.usb.UsbInterface
|
||||
import android.hardware.usb.UsbManager
|
||||
import java.io.Closeable
|
||||
|
||||
/**
|
||||
* A wrapper over Android's [UsbDevice] for HID devices.
|
||||
*/
|
||||
class AndroidHIDDevice(hidDevice: UsbDevice, usbManager: UsbManager) : Closeable {
|
||||
|
||||
val deviceName = hidDevice.deviceName
|
||||
val serialNumber = hidDevice.serialNumber
|
||||
val manufacturerName = hidDevice.manufacturerName
|
||||
val productName = hidDevice.productName
|
||||
|
||||
val hidInterface: UsbInterface
|
||||
|
||||
val endpointIn: UsbEndpoint
|
||||
val endpointOut: UsbEndpoint?
|
||||
|
||||
val deviceConnection: UsbDeviceConnection
|
||||
|
||||
init {
|
||||
hidInterface = findHidInterface(hidDevice)!!
|
||||
|
||||
val (endpointIn, endpointOut) = findHidIO(hidInterface)
|
||||
this.endpointIn = endpointIn!!
|
||||
this.endpointOut = endpointOut
|
||||
|
||||
deviceConnection = usbManager.openDevice(hidDevice)!!
|
||||
|
||||
deviceConnection.claimInterface(hidInterface, true)
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
deviceConnection.releaseInterface(hidInterface)
|
||||
deviceConnection.close()
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Find the HID interface.
|
||||
*
|
||||
* @return
|
||||
* Return the HID interface if found, otherwise null.
|
||||
*/
|
||||
private fun findHidInterface(usbDevice: UsbDevice): UsbInterface? {
|
||||
val interfaceCount: Int = usbDevice.interfaceCount
|
||||
|
||||
for (interfaceIndex in 0 until interfaceCount) {
|
||||
val usbInterface = usbDevice.getInterface(interfaceIndex)
|
||||
|
||||
if (usbInterface.interfaceClass == UsbConstants.USB_CLASS_HID) {
|
||||
return usbInterface
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the HID endpoints.
|
||||
*
|
||||
* @return
|
||||
* Return the HID endpoints if found, otherwise null.
|
||||
*/
|
||||
private fun findHidIO(usbInterface: UsbInterface): Pair<UsbEndpoint?, UsbEndpoint?> {
|
||||
val endpointCount: Int = usbInterface.endpointCount
|
||||
|
||||
var usbEndpointIn: UsbEndpoint? = null
|
||||
var usbEndpointOut: UsbEndpoint? = null
|
||||
|
||||
for (endpointIndex in 0 until endpointCount) {
|
||||
val usbEndpoint = usbInterface.getEndpoint(endpointIndex)
|
||||
|
||||
if (usbEndpoint.type == UsbConstants.USB_ENDPOINT_XFER_INT) {
|
||||
if (usbEndpoint.direction == UsbConstants.USB_DIR_OUT) {
|
||||
usbEndpointOut = usbEndpoint
|
||||
} else {
|
||||
usbEndpointIn = usbEndpoint
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Pair(usbEndpointIn, usbEndpointOut)
|
||||
}
|
||||
}
|
||||
}
|
||||
-256
@@ -1,256 +0,0 @@
|
||||
package dev.slimevr.android.tracking.trackers.hid
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbManager
|
||||
import androidx.core.content.ContextCompat
|
||||
import dev.slimevr.VRServer
|
||||
import dev.slimevr.config.config
|
||||
import dev.slimevr.tracking.trackers.Device
|
||||
import dev.slimevr.tracking.trackers.Tracker
|
||||
import dev.slimevr.tracking.trackers.TrackerStatus
|
||||
import dev.slimevr.tracking.trackers.hid.HIDCommon
|
||||
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.PACKET_SIZE
|
||||
import dev.slimevr.tracking.trackers.hid.HIDDevice
|
||||
import io.eiren.util.logging.LogManager
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.function.Consumer
|
||||
|
||||
const val ACTION_USB_PERMISSION = "dev.slimevr.USB_PERMISSION"
|
||||
|
||||
/**
|
||||
* Handles Android USB Host HID dongles and receives tracker data from them.
|
||||
*/
|
||||
class AndroidHIDManager(
|
||||
name: String,
|
||||
private val trackersConsumer: Consumer<Tracker>,
|
||||
private val context: Context,
|
||||
) : Thread(name) {
|
||||
private val devices: MutableList<HIDDevice> = mutableListOf()
|
||||
private val devicesBySerial: MutableMap<String, MutableList<Int>> = HashMap()
|
||||
private val devicesByHID: MutableMap<UsbDevice, MutableList<Int>> = HashMap()
|
||||
private val connByHID: MutableMap<UsbDevice, AndroidHIDDevice> = HashMap()
|
||||
private val lastDataByHID: MutableMap<UsbDevice, Int> = HashMap()
|
||||
private val usbManager: UsbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
|
||||
val usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
|
||||
(intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice?)?.let {
|
||||
checkConfigureDevice(it, requestPermission = true)
|
||||
}
|
||||
}
|
||||
|
||||
UsbManager.ACTION_USB_DEVICE_DETACHED -> {
|
||||
(intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice?)?.let {
|
||||
removeDevice(it)
|
||||
}
|
||||
}
|
||||
|
||||
ACTION_USB_PERMISSION -> {
|
||||
deviceEnumerate(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun proceedWithDeviceConfiguration(hidDevice: UsbDevice) {
|
||||
// This is the original logic from checkConfigureDevice after permission is confirmed
|
||||
LogManager.info("[TrackerServer] USB Permission granted for ${hidDevice.deviceName}. Proceeding with configuration.")
|
||||
|
||||
// Close any existing connection (do we still have one?)
|
||||
this.connByHID[hidDevice]?.close()
|
||||
// Open new HID connection with USB device
|
||||
this.connByHID[hidDevice] = AndroidHIDDevice(hidDevice, usbManager)
|
||||
|
||||
val serial = hidDevice.serialNumber ?: "Unknown USB Device ${hidDevice.deviceId}"
|
||||
this.devicesBySerial[serial]?.let {
|
||||
this.devicesByHID[hidDevice] = it
|
||||
this.lastDataByHID[hidDevice] = 0
|
||||
synchronized(this.devices) {
|
||||
for (id in it) {
|
||||
val device = this.devices[id]
|
||||
for (value in device.trackers.values) {
|
||||
if (value.status == TrackerStatus.DISCONNECTED) value.status = TrackerStatus.OK
|
||||
}
|
||||
}
|
||||
}
|
||||
LogManager.info("[TrackerServer] Linked HID device reattached: $serial")
|
||||
return
|
||||
}
|
||||
|
||||
val list: MutableList<Int> = mutableListOf()
|
||||
this.devicesBySerial[serial] = list
|
||||
this.devicesByHID[hidDevice] = list
|
||||
this.lastDataByHID[hidDevice] = 0 // initialize last data received
|
||||
LogManager.info("[TrackerServer] (Probably) Compatible HID device detected: $serial")
|
||||
}
|
||||
|
||||
fun checkConfigureDevice(usbDevice: UsbDevice, requestPermission: Boolean = false) {
|
||||
if (HIDCommon.matchesAny(usbDevice.vendorId, usbDevice.productId)) {
|
||||
if (usbManager.hasPermission(usbDevice)) {
|
||||
LogManager.info("[TrackerServer] Already have permission for ${usbDevice.deviceName}")
|
||||
proceedWithDeviceConfiguration(usbDevice)
|
||||
} else if (requestPermission) {
|
||||
LogManager.info("[TrackerServer] Requesting permission for ${usbDevice.deviceName}")
|
||||
val permissionIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
0,
|
||||
Intent(ACTION_USB_PERMISSION).apply { setPackage(context.packageName) }, // Explicitly set package
|
||||
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
usbManager.requestPermission(usbDevice, permissionIntent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun removeDevice(hidDevice: UsbDevice) {
|
||||
this.devicesByHID[hidDevice]?.let {
|
||||
synchronized(this.devices) {
|
||||
for (id in it) {
|
||||
val device = this.devices[id]
|
||||
for (value in device.trackers.values) {
|
||||
if (value.status == TrackerStatus.OK) {
|
||||
value.status =
|
||||
TrackerStatus.DISCONNECTED
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.devicesByHID.remove(hidDevice)
|
||||
|
||||
val oldConn = this.connByHID.remove(hidDevice)
|
||||
val serial = oldConn?.serialNumber ?: "Unknown"
|
||||
oldConn?.close()
|
||||
|
||||
LogManager.info("[TrackerServer] Linked HID device removed: $serial")
|
||||
}
|
||||
}
|
||||
|
||||
private fun dataRead() {
|
||||
synchronized(devicesByHID) {
|
||||
var devicesPresent = false
|
||||
var devicesDataReceived = false
|
||||
val q = intArrayOf(0, 0, 0, 0)
|
||||
val a = intArrayOf(0, 0, 0)
|
||||
val m = intArrayOf(0, 0, 0)
|
||||
for ((hidDevice, deviceList) in devicesByHID) {
|
||||
val dataReceived = ByteArray(64)
|
||||
val conn = connByHID[hidDevice]!!
|
||||
val dataRead = conn.deviceConnection.bulkTransfer(conn.endpointIn, dataReceived, dataReceived.size, 0)
|
||||
|
||||
// LogManager.info("[TrackerServer] HID data read ($dataRead bytes): ${dataReceived.contentToString()}")
|
||||
|
||||
devicesPresent = true // Even if the device has no data
|
||||
if (dataRead > 0) {
|
||||
// Process data
|
||||
// The data is always received as 64 bytes, this check no longer works
|
||||
if (dataRead % PACKET_SIZE != 0) {
|
||||
LogManager.info("[TrackerServer] Malformed HID packet, ignoring")
|
||||
continue // Don't continue with this data
|
||||
}
|
||||
devicesDataReceived = true // Data is received and is valid (not malformed)
|
||||
lastDataByHID[hidDevice] = 0 // reset last data received
|
||||
val packetCount = dataRead / PACKET_SIZE
|
||||
var i = 0
|
||||
while (i < packetCount * PACKET_SIZE) {
|
||||
// Common packet data
|
||||
val packetType = dataReceived[i].toUByte().toInt()
|
||||
val id = dataReceived[i + 1].toUByte().toInt()
|
||||
val deviceId = id
|
||||
|
||||
// Register device
|
||||
if (packetType == 255) { // device register packet from receiver
|
||||
val buffer = ByteBuffer.wrap(dataReceived, i + 2, 8)
|
||||
buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN)
|
||||
val addr = buffer.getLong() and 0xFFFFFFFFFFFF
|
||||
val deviceName = String.format("%012X", addr)
|
||||
HIDCommon.deviceIdLookup(devices, hidDevice.serialNumber, deviceId, deviceName, deviceList) // register device
|
||||
// server wants tracker to be unique, so use combination of hid serial and full id
|
||||
i += PACKET_SIZE
|
||||
continue
|
||||
}
|
||||
|
||||
val device: HIDDevice? = HIDCommon.deviceIdLookup(devices, hidDevice.serialNumber, deviceId, null, deviceList)
|
||||
if (device == null) { // not registered yet
|
||||
i += PACKET_SIZE
|
||||
continue
|
||||
}
|
||||
|
||||
HIDCommon.processPacket(dataReceived, i, packetType, device, q, a, m, trackersConsumer)
|
||||
i += PACKET_SIZE
|
||||
}
|
||||
// LogManager.info("[TrackerServer] HID received $packetCount tracker packets")
|
||||
} else {
|
||||
lastDataByHID[hidDevice] = lastDataByHID.getOrDefault(hidDevice, 0) + 1 // increment last data received
|
||||
}
|
||||
}
|
||||
if (!devicesPresent) {
|
||||
sleep(10) // No hid device, "empty loop" so sleep to save the poor cpu
|
||||
} else if (!devicesDataReceived) {
|
||||
sleep(1) // read has no timeout, no data also causes an "empty loop"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun deviceEnumerate(requestPermission: Boolean = false) {
|
||||
val trackersOverHID: Boolean = VRServer.instance.configManager.vrConfig.hidConfig.trackersOverHID
|
||||
val hidDeviceList: MutableList<UsbDevice> = usbManager.deviceList.values.filter {
|
||||
HIDCommon.matchesReceiver(it.vendorId, it.productId) || (trackersOverHID && HIDCommon.matchesTracker(it.vendorId, it.productId))
|
||||
}.toMutableList()
|
||||
synchronized(devicesByHID) {
|
||||
// Work on devicesByHid and add/remove as necessary
|
||||
val removeList: MutableList<UsbDevice> = devicesByHID.keys.toMutableList()
|
||||
removeList.removeAll(hidDeviceList)
|
||||
for (device in removeList) {
|
||||
removeDevice(device)
|
||||
}
|
||||
|
||||
hidDeviceList.removeAll(devicesByHID.keys) // addList
|
||||
for (device in hidDeviceList) {
|
||||
// This will handle permission check/request
|
||||
checkConfigureDevice(device, requestPermission)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun run() {
|
||||
val intentFilter = IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED)
|
||||
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
intentFilter.addAction(ACTION_USB_PERMISSION)
|
||||
|
||||
// Listen for USB device attach/detach
|
||||
ContextCompat.registerReceiver(
|
||||
context,
|
||||
usbReceiver,
|
||||
intentFilter,
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
|
||||
// Enumerate existing devices
|
||||
deviceEnumerate(true)
|
||||
|
||||
// Data read loop
|
||||
while (true) {
|
||||
try {
|
||||
sleep(0) // Possible performance impact
|
||||
} catch (e: InterruptedException) {
|
||||
currentThread().interrupt()
|
||||
break
|
||||
}
|
||||
dataRead() // not in try catch?
|
||||
}
|
||||
}
|
||||
|
||||
fun getDevices(): List<Device> = devices
|
||||
|
||||
companion object {
|
||||
private const val resetSourceName = "TrackerServer"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package dev.slimevr.android.udp
|
||||
|
||||
import io.ktor.network.sockets.InetSocketAddress
|
||||
import io.ktor.network.sockets.toJavaAddress
|
||||
|
||||
fun resolveAndroidUdpAddress(addr: InetSocketAddress): String = (addr.toJavaAddress() as java.net.InetSocketAddress).hostString
|
||||
@@ -0,0 +1,20 @@
|
||||
package dev.slimevr.android.vrchat
|
||||
|
||||
import java.net.InetAddress
|
||||
import java.net.NetworkInterface
|
||||
import java.util.Collections
|
||||
|
||||
fun resolveAndroidOscQueryAddress(): String = try {
|
||||
val candidates = Collections.list(NetworkInterface.getNetworkInterfaces())
|
||||
.asSequence()
|
||||
.filter { iface -> iface.isUp && !iface.isLoopback && !iface.isVirtual }
|
||||
.flatMap { iface -> Collections.list(iface.inetAddresses).asSequence() }
|
||||
.filter { address -> !address.isLoopbackAddress && !address.hostAddress!!.contains(':') }
|
||||
.toList()
|
||||
|
||||
val siteLocal = candidates.firstOrNull { address -> address.isSiteLocalAddress }
|
||||
(siteLocal ?: candidates.firstOrNull())?.hostAddress
|
||||
?: InetAddress.getLoopbackAddress().hostAddress
|
||||
} catch (_: Exception) {
|
||||
InetAddress.getLoopbackAddress().hostAddress
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
<resources>
|
||||
<string name="app_name">SlimeVR</string>
|
||||
<string name="stop_server">Stop Server</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,123 @@
|
||||
digraph module_architecture {
|
||||
rankdir=TB
|
||||
splines=false
|
||||
nodesep=0.8
|
||||
ranksep=0.8
|
||||
forcelabels=true
|
||||
fontname="monospace"
|
||||
node [fontname="monospace", fontsize=11, style="filled,rounded", shape=box, margin="0.3,0.2"]
|
||||
edge [fontname="monospace", fontsize=10]
|
||||
|
||||
ext [
|
||||
label="external events\n(packets · messages)"
|
||||
shape=ellipse fillcolor="#dae8fc" color="#6c8ebf"
|
||||
]
|
||||
|
||||
subgraph cluster_A {
|
||||
label="Module A"
|
||||
style="rounded" bgcolor="#fafafa" color="#999999" penwidth=1.5
|
||||
|
||||
subgraph cluster_A_beh {
|
||||
label="Behaviours"
|
||||
style="dashed" color="#aaaaaa" bgcolor="#fffff8"
|
||||
|
||||
bA1 [label="BehaviourA1\n────────────────────\nobserve(receiver)\n subscribes to flows\n calls dispatch()\n────────────────────\nreduce(state, action)\n pure: State -> State"
|
||||
fillcolor="#fff9db" color="#d6ae00"]
|
||||
|
||||
bA2 [label="BehaviourA2\n────────────────────\nobserve(receiver)\n ...\n────────────────────\nreduce(state, action)\n ..."
|
||||
fillcolor="#fff9db" color="#d6ae00"]
|
||||
|
||||
bAmore [label="···\n────────────────────\nobserve(receiver)\n ...\n────────────────────\nreduce(state, action)\n ..."
|
||||
fillcolor="#fff9db" color="#d6ae00"]
|
||||
}
|
||||
|
||||
foldA [
|
||||
label="reduce fold\n──────────────────────────────────\nstate = BehaviourA1.reduce(state, a)\nstate = BehaviourA2.reduce(state, a)\nstate = ···"
|
||||
fillcolor="#d5e8d4" color="#82b366"
|
||||
]
|
||||
|
||||
sfA [
|
||||
label="StateFlow<StateA>"
|
||||
shape=cylinder fillcolor="#dae8fc" color="#6c8ebf"
|
||||
]
|
||||
|
||||
}
|
||||
|
||||
subgraph cluster_B {
|
||||
label="Module B"
|
||||
style="rounded" bgcolor="#fafafa" color="#999999" penwidth=1.5
|
||||
|
||||
subgraph cluster_B_beh {
|
||||
label="Behaviours"
|
||||
style="dashed" color="#aaaaaa" bgcolor="#fffff8"
|
||||
|
||||
bBmore [label="···\n────────────────────\nobserve(receiver)\n ...\n────────────────────\nreduce(state, action)\n ..."
|
||||
fillcolor="#fff9db" color="#d6ae00"]
|
||||
}
|
||||
|
||||
foldB [
|
||||
label="reduce fold"
|
||||
fillcolor="#d5e8d4" color="#82b366"
|
||||
]
|
||||
|
||||
sfB [
|
||||
label="StateFlow<StateB>"
|
||||
shape=cylinder fillcolor="#dae8fc" color="#6c8ebf"
|
||||
]
|
||||
}
|
||||
|
||||
subgraph cluster_C {
|
||||
label="Module C"
|
||||
style="rounded" bgcolor="#fafafa" color="#999999" penwidth=1.5
|
||||
|
||||
subgraph cluster_C_beh {
|
||||
label="Behaviours"
|
||||
style="dashed" color="#aaaaaa" bgcolor="#fffff8"
|
||||
|
||||
bCmore [label="···\n────────────────────\nobserve(receiver)\n ...\n────────────────────\nreduce(state, action)\n ..."
|
||||
fillcolor="#fff9db" color="#d6ae00"]
|
||||
}
|
||||
|
||||
foldC [
|
||||
label="reduce fold"
|
||||
fillcolor="#d5e8d4" color="#82b366"
|
||||
]
|
||||
|
||||
sfC [
|
||||
label="StateFlow<StateC>"
|
||||
shape=cylinder fillcolor="#dae8fc" color="#6c8ebf"
|
||||
]
|
||||
|
||||
}
|
||||
|
||||
// ext -> all modules
|
||||
ext -> bA1 [color="#6c8ebf" fontcolor="#6c8ebf" weight=1]
|
||||
ext -> bA2 [color="#6c8ebf" weight=1]
|
||||
ext -> bAmore [color="#6c8ebf" weight=1]
|
||||
ext -> bBmore [color="#6c8ebf" weight=1]
|
||||
ext -> bCmore [color="#6c8ebf" weight=1]
|
||||
|
||||
// Module A internal flow
|
||||
bA1 -> foldA [xlabel="dispatch(action)" color="#d6ae00" fontcolor="#d6ae00"]
|
||||
bA2 -> foldA [xlabel="dispatch(action)" color="#d6ae00" fontcolor="#d6ae00"]
|
||||
bAmore -> foldA [xlabel="dispatch(action)" color="#d6ae00" fontcolor="#d6ae00"]
|
||||
foldA -> sfA [xlabel="new state" color="#82b366" fontcolor="#82b366"]
|
||||
|
||||
// Module B internal flow
|
||||
bBmore -> foldB [xlabel="dispatch(action)" color="#d6ae00" fontcolor="#d6ae00"]
|
||||
foldB -> sfB [color="#82b366"]
|
||||
|
||||
// Module C internal flow
|
||||
bCmore -> foldC [xlabel="dispatch(action)" color="#d6ae00" fontcolor="#d6ae00"]
|
||||
foldC -> sfC [color="#82b366"]
|
||||
// Within-module feedback (gray)
|
||||
bA1 -> sfA [xlabel="collect()" dir=back style=dashed color="#888888" fontcolor="#888888" constraint=true]
|
||||
bBmore -> sfB [xlabel="collect()" dir=back style=dashed color="#888888" fontcolor="#888888" constraint=true]
|
||||
bCmore -> sfC [xlabel="collect()" dir=back style=dashed color="#888888" fontcolor="#888888" constraint=true]
|
||||
|
||||
|
||||
// Cross-module: routed via waypoints at rank 4 — exits downward, travels below all modules
|
||||
bBmore -> sfA [xlabel="collect()" dir=back style=dashed color="#FF0000" fontcolor="#FF0000" constraint=false]
|
||||
bCmore -> sfA [xlabel="collect()" dir=back style=dashed color="#FF0000" fontcolor="#FF0000" constraint=false]
|
||||
bCmore -> sfB [xlabel="collect()" dir=back style=dashed color="#FF0000" fontcolor="#FF0000" constraint=false]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 142 KiB |
@@ -0,0 +1,280 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
|
||||
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<!-- Generated by graphviz version 12.2.1 (0)
|
||||
-->
|
||||
<!-- Title: module_architecture Pages: 1 -->
|
||||
<svg width="1218pt" height="585pt"
|
||||
viewBox="0.00 0.00 1218.00 584.68" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 580.68)">
|
||||
<title>module_architecture</title>
|
||||
<polygon fill="white" stroke="none" points="-4,4 -4,-580.68 1214,-580.68 1214,4 -4,4"/>
|
||||
<g id="clust1" class="cluster">
|
||||
<title>cluster_A</title>
|
||||
<path fill="#fafafa" stroke="#999999" stroke-width="1.5" d="M20,-8C20,-8 705,-8 705,-8 711,-8 717,-14 717,-20 717,-20 717,-477.76 717,-477.76 717,-483.76 711,-489.76 705,-489.76 705,-489.76 20,-489.76 20,-489.76 14,-489.76 8,-483.76 8,-477.76 8,-477.76 8,-20 8,-20 8,-14 14,-8 20,-8"/>
|
||||
<text text-anchor="middle" x="362.5" y="-472.46" font-family="monospace" font-size="14.00">Module A</text>
|
||||
</g>
|
||||
<g id="clust2" class="cluster">
|
||||
<title>cluster_A_beh</title>
|
||||
<polygon fill="#fffff8" stroke="#aaaaaa" stroke-width="1.5" stroke-dasharray="5,2" points="16,-278.46 16,-456.51 709,-456.51 709,-278.46 16,-278.46"/>
|
||||
<text text-anchor="middle" x="362.5" y="-439.21" font-family="monospace" font-size="14.00">Behaviours</text>
|
||||
</g>
|
||||
<g id="clust3" class="cluster">
|
||||
<title>cluster_B</title>
|
||||
<path fill="#fafafa" stroke="#999999" stroke-width="1.5" d="M755,-8C755,-8 947,-8 947,-8 953,-8 959,-14 959,-20 959,-20 959,-471.01 959,-471.01 959,-477.01 953,-483.01 947,-483.01 947,-483.01 755,-483.01 755,-483.01 749,-483.01 743,-477.01 743,-471.01 743,-471.01 743,-20 743,-20 743,-14 749,-8 755,-8"/>
|
||||
<text text-anchor="middle" x="851" y="-465.71" font-family="monospace" font-size="14.00">Module B</text>
|
||||
</g>
|
||||
<g id="clust4" class="cluster">
|
||||
<title>cluster_B_beh</title>
|
||||
<polygon fill="#fffff8" stroke="#aaaaaa" stroke-width="1.5" stroke-dasharray="5,2" points="751,-285.21 751,-449.76 951,-449.76 951,-285.21 751,-285.21"/>
|
||||
<text text-anchor="middle" x="851" y="-432.46" font-family="monospace" font-size="14.00">Behaviours</text>
|
||||
</g>
|
||||
<g id="clust5" class="cluster">
|
||||
<title>cluster_C</title>
|
||||
<path fill="#fafafa" stroke="#999999" stroke-width="1.5" d="M998,-8C998,-8 1190,-8 1190,-8 1196,-8 1202,-14 1202,-20 1202,-20 1202,-471.01 1202,-471.01 1202,-477.01 1196,-483.01 1190,-483.01 1190,-483.01 998,-483.01 998,-483.01 992,-483.01 986,-477.01 986,-471.01 986,-471.01 986,-20 986,-20 986,-14 992,-8 998,-8"/>
|
||||
<text text-anchor="middle" x="1094" y="-465.71" font-family="monospace" font-size="14.00">Module C</text>
|
||||
</g>
|
||||
<g id="clust6" class="cluster">
|
||||
<title>cluster_C_beh</title>
|
||||
<polygon fill="#fffff8" stroke="#aaaaaa" stroke-width="1.5" stroke-dasharray="5,2" points="994,-285.21 994,-449.76 1194,-449.76 1194,-285.21 994,-285.21"/>
|
||||
<text text-anchor="middle" x="1094" y="-432.46" font-family="monospace" font-size="14.00">Behaviours</text>
|
||||
</g>
|
||||
<!-- ext -->
|
||||
<g id="node1" class="node">
|
||||
<title>ext</title>
|
||||
<ellipse fill="#dae8fc" stroke="#6c8ebf" cx="605" cy="-537.22" rx="126.01" ry="39.46"/>
|
||||
<text text-anchor="middle" x="605" y="-540.27" font-family="monospace" font-size="11.00">external events</text>
|
||||
<text text-anchor="middle" x="605" y="-526.77" font-family="monospace" font-size="11.00">(packets · messages)</text>
|
||||
</g>
|
||||
<!-- bA1 -->
|
||||
<g id="node2" class="node">
|
||||
<title>bA1</title>
|
||||
<path fill="#fff9db" stroke="#d6ae00" d="M688.85,-423.26C688.85,-423.26 521.15,-423.26 521.15,-423.26 515.15,-423.26 509.15,-417.26 509.15,-411.26 509.15,-411.26 509.15,-298.46 509.15,-298.46 509.15,-292.46 515.15,-286.46 521.15,-286.46 521.15,-286.46 688.85,-286.46 688.85,-286.46 694.85,-286.46 700.85,-292.46 700.85,-298.46 700.85,-298.46 700.85,-411.26 700.85,-411.26 700.85,-417.26 694.85,-423.26 688.85,-423.26"/>
|
||||
<text text-anchor="middle" x="605" y="-398.41" font-family="monospace" font-size="11.00">BehaviourA1</text>
|
||||
<text text-anchor="middle" x="605" y="-384.91" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="605" y="-371.41" font-family="monospace" font-size="11.00">observe(receiver)</text>
|
||||
<text text-anchor="middle" x="605" y="-357.91" font-family="monospace" font-size="11.00">  subscribes to flows</text>
|
||||
<text text-anchor="middle" x="605" y="-344.41" font-family="monospace" font-size="11.00">  calls dispatch()</text>
|
||||
<text text-anchor="middle" x="605" y="-330.91" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="605" y="-317.41" font-family="monospace" font-size="11.00">reduce(state, action)</text>
|
||||
<text text-anchor="middle" x="605" y="-303.91" font-family="monospace" font-size="11.00">  pure: State -> State</text>
|
||||
</g>
|
||||
<!-- ext->bA1 -->
|
||||
<g id="edge1" class="edge">
|
||||
<title>ext->bA1</title>
|
||||
<path fill="none" stroke="#6c8ebf" d="M605,-497.53C605,-479.19 605,-456.59 605,-434.87"/>
|
||||
<polygon fill="#6c8ebf" stroke="#6c8ebf" points="608.5,-435.13 605,-425.13 601.5,-435.13 608.5,-435.13"/>
|
||||
</g>
|
||||
<!-- bA2 -->
|
||||
<g id="node3" class="node">
|
||||
<title>bA2</title>
|
||||
<path fill="#fff9db" stroke="#d6ae00" d="M196.47,-416.51C196.47,-416.51 35.53,-416.51 35.53,-416.51 29.53,-416.51 23.53,-410.51 23.53,-404.51 23.53,-404.51 23.53,-305.21 23.53,-305.21 23.53,-299.21 29.53,-293.21 35.53,-293.21 35.53,-293.21 196.47,-293.21 196.47,-293.21 202.47,-293.21 208.47,-299.21 208.47,-305.21 208.47,-305.21 208.47,-404.51 208.47,-404.51 208.47,-410.51 202.47,-416.51 196.47,-416.51"/>
|
||||
<text text-anchor="middle" x="116" y="-391.66" font-family="monospace" font-size="11.00">BehaviourA2</text>
|
||||
<text text-anchor="middle" x="116" y="-378.16" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="116" y="-364.66" font-family="monospace" font-size="11.00">observe(receiver)</text>
|
||||
<text text-anchor="middle" x="116" y="-351.16" font-family="monospace" font-size="11.00">  ...</text>
|
||||
<text text-anchor="middle" x="116" y="-337.66" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="116" y="-324.16" font-family="monospace" font-size="11.00">reduce(state, action)</text>
|
||||
<text text-anchor="middle" x="116" y="-310.66" font-family="monospace" font-size="11.00">  ...</text>
|
||||
</g>
|
||||
<!-- ext->bA2 -->
|
||||
<g id="edge2" class="edge">
|
||||
<title>ext->bA2</title>
|
||||
<path fill="none" stroke="#6c8ebf" d="M524.53,-506.54C441.07,-475.76 310.31,-427.53 219.28,-393.96"/>
|
||||
<polygon fill="#6c8ebf" stroke="#6c8ebf" points="220.67,-390.74 210.08,-390.56 218.25,-397.31 220.67,-390.74"/>
|
||||
</g>
|
||||
<!-- bAmore -->
|
||||
<g id="node4" class="node">
|
||||
<title>bAmore</title>
|
||||
<path fill="#fff9db" stroke="#d6ae00" d="M439.48,-416.51C439.48,-416.51 278.52,-416.51 278.52,-416.51 272.52,-416.51 266.52,-410.51 266.52,-404.51 266.52,-404.51 266.52,-305.21 266.52,-305.21 266.52,-299.21 272.52,-293.21 278.52,-293.21 278.52,-293.21 439.48,-293.21 439.48,-293.21 445.48,-293.21 451.48,-299.21 451.48,-305.21 451.48,-305.21 451.48,-404.51 451.48,-404.51 451.48,-410.51 445.48,-416.51 439.48,-416.51"/>
|
||||
<text text-anchor="middle" x="359" y="-391.66" font-family="monospace" font-size="11.00">···</text>
|
||||
<text text-anchor="middle" x="359" y="-378.16" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="359" y="-364.66" font-family="monospace" font-size="11.00">observe(receiver)</text>
|
||||
<text text-anchor="middle" x="359" y="-351.16" font-family="monospace" font-size="11.00">  ...</text>
|
||||
<text text-anchor="middle" x="359" y="-337.66" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="359" y="-324.16" font-family="monospace" font-size="11.00">reduce(state, action)</text>
|
||||
<text text-anchor="middle" x="359" y="-310.66" font-family="monospace" font-size="11.00">  ...</text>
|
||||
</g>
|
||||
<!-- ext->bAmore -->
|
||||
<g id="edge3" class="edge">
|
||||
<title>ext->bAmore</title>
|
||||
<path fill="none" stroke="#6c8ebf" d="M556.1,-500.37C526.14,-478.4 486.81,-449.57 451.18,-423.44"/>
|
||||
<polygon fill="#6c8ebf" stroke="#6c8ebf" points="453.56,-420.85 443.42,-417.76 449.42,-426.49 453.56,-420.85"/>
|
||||
</g>
|
||||
<!-- bBmore -->
|
||||
<g id="node7" class="node">
|
||||
<title>bBmore</title>
|
||||
<path fill="#fff9db" stroke="#d6ae00" d="M931.48,-416.51C931.48,-416.51 770.52,-416.51 770.52,-416.51 764.52,-416.51 758.52,-410.51 758.52,-404.51 758.52,-404.51 758.52,-305.21 758.52,-305.21 758.52,-299.21 764.52,-293.21 770.52,-293.21 770.52,-293.21 931.48,-293.21 931.48,-293.21 937.48,-293.21 943.48,-299.21 943.48,-305.21 943.48,-305.21 943.48,-404.51 943.48,-404.51 943.48,-410.51 937.48,-416.51 931.48,-416.51"/>
|
||||
<text text-anchor="middle" x="851" y="-391.66" font-family="monospace" font-size="11.00">···</text>
|
||||
<text text-anchor="middle" x="851" y="-378.16" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="851" y="-364.66" font-family="monospace" font-size="11.00">observe(receiver)</text>
|
||||
<text text-anchor="middle" x="851" y="-351.16" font-family="monospace" font-size="11.00">  ...</text>
|
||||
<text text-anchor="middle" x="851" y="-337.66" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="851" y="-324.16" font-family="monospace" font-size="11.00">reduce(state, action)</text>
|
||||
<text text-anchor="middle" x="851" y="-310.66" font-family="monospace" font-size="11.00">  ...</text>
|
||||
</g>
|
||||
<!-- ext->bBmore -->
|
||||
<g id="edge4" class="edge">
|
||||
<title>ext->bBmore</title>
|
||||
<path fill="none" stroke="#6c8ebf" d="M653.9,-500.37C683.86,-478.4 723.19,-449.57 758.82,-423.44"/>
|
||||
<polygon fill="#6c8ebf" stroke="#6c8ebf" points="760.58,-426.49 766.58,-417.76 756.44,-420.85 760.58,-426.49"/>
|
||||
</g>
|
||||
<!-- bCmore -->
|
||||
<g id="node10" class="node">
|
||||
<title>bCmore</title>
|
||||
<path fill="#fff9db" stroke="#d6ae00" d="M1174.47,-416.51C1174.47,-416.51 1013.52,-416.51 1013.52,-416.51 1007.52,-416.51 1001.52,-410.51 1001.52,-404.51 1001.52,-404.51 1001.52,-305.21 1001.52,-305.21 1001.52,-299.21 1007.52,-293.21 1013.52,-293.21 1013.52,-293.21 1174.47,-293.21 1174.47,-293.21 1180.47,-293.21 1186.47,-299.21 1186.47,-305.21 1186.47,-305.21 1186.47,-404.51 1186.47,-404.51 1186.47,-410.51 1180.47,-416.51 1174.47,-416.51"/>
|
||||
<text text-anchor="middle" x="1094" y="-391.66" font-family="monospace" font-size="11.00">···</text>
|
||||
<text text-anchor="middle" x="1094" y="-378.16" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="1094" y="-364.66" font-family="monospace" font-size="11.00">observe(receiver)</text>
|
||||
<text text-anchor="middle" x="1094" y="-351.16" font-family="monospace" font-size="11.00">  ...</text>
|
||||
<text text-anchor="middle" x="1094" y="-337.66" font-family="monospace" font-size="11.00">────────────────────</text>
|
||||
<text text-anchor="middle" x="1094" y="-324.16" font-family="monospace" font-size="11.00">reduce(state, action)</text>
|
||||
<text text-anchor="middle" x="1094" y="-310.66" font-family="monospace" font-size="11.00">  ...</text>
|
||||
</g>
|
||||
<!-- ext->bCmore -->
|
||||
<g id="edge5" class="edge">
|
||||
<title>ext->bCmore</title>
|
||||
<path fill="none" stroke="#6c8ebf" d="M685.47,-506.54C768.93,-475.76 899.69,-427.53 990.72,-393.96"/>
|
||||
<polygon fill="#6c8ebf" stroke="#6c8ebf" points="991.75,-397.31 999.92,-390.56 989.33,-390.74 991.75,-397.31"/>
|
||||
</g>
|
||||
<!-- foldA -->
|
||||
<g id="node5" class="node">
|
||||
<title>foldA</title>
|
||||
<path fill="#d5e8d4" stroke="#82b366" d="M501.1,-228.46C501.1,-228.46 238.9,-228.46 238.9,-228.46 232.9,-228.46 226.9,-222.46 226.9,-216.46 226.9,-216.46 226.9,-144.16 226.9,-144.16 226.9,-138.16 232.9,-132.16 238.9,-132.16 238.9,-132.16 501.1,-132.16 501.1,-132.16 507.1,-132.16 513.1,-138.16 513.1,-144.16 513.1,-144.16 513.1,-216.46 513.1,-216.46 513.1,-222.46 507.1,-228.46 501.1,-228.46"/>
|
||||
<text text-anchor="middle" x="370" y="-203.61" font-family="monospace" font-size="11.00">reduce fold</text>
|
||||
<text text-anchor="middle" x="370" y="-190.11" font-family="monospace" font-size="11.00">──────────────────────────────────</text>
|
||||
<text text-anchor="middle" x="370" y="-176.61" font-family="monospace" font-size="11.00">state = BehaviourA1.reduce(state, a)</text>
|
||||
<text text-anchor="middle" x="370" y="-163.11" font-family="monospace" font-size="11.00">state = BehaviourA2.reduce(state, a)</text>
|
||||
<text text-anchor="middle" x="370" y="-149.61" font-family="monospace" font-size="11.00">state = ···</text>
|
||||
</g>
|
||||
<!-- bA1->foldA -->
|
||||
<g id="edge6" class="edge">
|
||||
<title>bA1->foldA</title>
|
||||
<path fill="none" stroke="#d6ae00" d="M512.8,-286.16C489.96,-269.39 465.78,-251.64 443.94,-235.6"/>
|
||||
<polygon fill="#d6ae00" stroke="#d6ae00" points="446.08,-232.83 435.95,-229.74 441.94,-238.48 446.08,-232.83"/>
|
||||
<text text-anchor="middle" x="430.37" y="-264.13" font-family="monospace" font-size="10.00" fill="#d6ae00">dispatch(action)</text>
|
||||
</g>
|
||||
<!-- sfA -->
|
||||
<g id="node6" class="node">
|
||||
<title>sfA</title>
|
||||
<path fill="#dae8fc" stroke="#6c8ebf" d="M560.98,-68.88C560.98,-71.79 525.58,-74.16 482,-74.16 438.42,-74.16 403.02,-71.79 403.02,-68.88 403.02,-68.88 403.02,-21.29 403.02,-21.29 403.02,-18.37 438.42,-16 482,-16 525.58,-16 560.98,-18.37 560.98,-21.29 560.98,-21.29 560.98,-68.88 560.98,-68.88"/>
|
||||
<path fill="none" stroke="#6c8ebf" d="M560.98,-68.88C560.98,-65.96 525.58,-63.59 482,-63.59 438.42,-63.59 403.02,-65.96 403.02,-68.88"/>
|
||||
<text text-anchor="middle" x="482" y="-41.38" font-family="monospace" font-size="11.00">StateFlow<StateA></text>
|
||||
</g>
|
||||
<!-- bA1->sfA -->
|
||||
<g id="edge14" class="edge">
|
||||
<title>bA1->sfA</title>
|
||||
<path fill="none" stroke="#888888" stroke-dasharray="5,2" d="M573.6,-275.78C547.5,-210.06 511.81,-120.16 493.65,-74.42"/>
|
||||
<polygon fill="#888888" stroke="#888888" points="570.2,-276.7 577.14,-284.71 576.71,-274.12 570.2,-276.7"/>
|
||||
<text text-anchor="middle" x="560.62" y="-178.35" font-family="monospace" font-size="10.00" fill="#888888">collect()</text>
|
||||
</g>
|
||||
<!-- bA2->foldA -->
|
||||
<g id="edge7" class="edge">
|
||||
<title>bA2->foldA</title>
|
||||
<path fill="none" stroke="#d6ae00" d="M205.91,-292.78C233.61,-273.97 263.89,-253.39 290.82,-235.1"/>
|
||||
<polygon fill="#d6ae00" stroke="#d6ae00" points="292.64,-238.1 298.94,-229.59 288.7,-232.31 292.64,-238.1"/>
|
||||
<text text-anchor="middle" x="200.36" y="-267.19" font-family="monospace" font-size="10.00" fill="#d6ae00">dispatch(action)</text>
|
||||
</g>
|
||||
<!-- bAmore->foldA -->
|
||||
<g id="edge8" class="edge">
|
||||
<title>bAmore->foldA</title>
|
||||
<path fill="none" stroke="#d6ae00" d="M362.88,-293.03C363.97,-275.92 365.15,-257.35 366.24,-240.35"/>
|
||||
<polygon fill="#d6ae00" stroke="#d6ae00" points="369.73,-240.58 366.87,-230.38 362.74,-240.13 369.73,-240.58"/>
|
||||
<text text-anchor="middle" x="316.56" y="-269.94" font-family="monospace" font-size="10.00" fill="#d6ae00">dispatch(action)</text>
|
||||
</g>
|
||||
<!-- foldA->sfA -->
|
||||
<g id="edge9" class="edge">
|
||||
<title>foldA->sfA</title>
|
||||
<path fill="none" stroke="#82b366" d="M409.8,-131.97C423.36,-115.83 438.31,-98.05 451.07,-82.88"/>
|
||||
<polygon fill="#82b366" stroke="#82b366" points="453.57,-85.34 457.33,-75.43 448.21,-80.83 453.57,-85.34"/>
|
||||
<text text-anchor="middle" x="403.44" y="-110.67" font-family="monospace" font-size="10.00" fill="#82b366">new state</text>
|
||||
</g>
|
||||
<!-- bBmore->sfA -->
|
||||
<g id="edge17" class="edge">
|
||||
<title>bBmore->sfA</title>
|
||||
<path fill="none" stroke="#ff0000" stroke-dasharray="5,2" d="M768.74,-285.81C689.86,-219.59 574.55,-122.78 517.16,-74.6"/>
|
||||
<polygon fill="#ff0000" stroke="#ff0000" points="766.15,-288.2 776.06,-291.95 770.65,-282.83 766.15,-288.2"/>
|
||||
<text text-anchor="middle" x="615.95" y="-183.45" font-family="monospace" font-size="10.00" fill="#ff0000">collect()</text>
|
||||
</g>
|
||||
<!-- foldB -->
|
||||
<g id="node8" class="node">
|
||||
<title>foldB</title>
|
||||
<path fill="#d5e8d4" stroke="#82b366" d="M859.73,-201.46C859.73,-201.46 766.27,-201.46 766.27,-201.46 760.27,-201.46 754.27,-195.46 754.27,-189.46 754.27,-189.46 754.27,-171.16 754.27,-171.16 754.27,-165.16 760.27,-159.16 766.27,-159.16 766.27,-159.16 859.73,-159.16 859.73,-159.16 865.73,-159.16 871.73,-165.16 871.73,-171.16 871.73,-171.16 871.73,-189.46 871.73,-189.46 871.73,-195.46 865.73,-201.46 859.73,-201.46"/>
|
||||
<text text-anchor="middle" x="813" y="-176.61" font-family="monospace" font-size="11.00">reduce fold</text>
|
||||
</g>
|
||||
<!-- bBmore->foldB -->
|
||||
<g id="edge10" class="edge">
|
||||
<title>bBmore->foldB</title>
|
||||
<path fill="none" stroke="#d6ae00" d="M837.6,-293.03C831.66,-266.05 824.92,-235.43 820,-213.08"/>
|
||||
<polygon fill="#d6ae00" stroke="#d6ae00" points="823.43,-212.39 817.86,-203.37 816.59,-213.89 823.43,-212.39"/>
|
||||
<text text-anchor="middle" x="780.8" y="-256.3" font-family="monospace" font-size="10.00" fill="#d6ae00">dispatch(action)</text>
|
||||
</g>
|
||||
<!-- sfB -->
|
||||
<g id="node9" class="node">
|
||||
<title>sfB</title>
|
||||
<path fill="#dae8fc" stroke="#6c8ebf" d="M921.98,-68.88C921.98,-71.79 886.58,-74.16 843,-74.16 799.42,-74.16 764.02,-71.79 764.02,-68.88 764.02,-68.88 764.02,-21.29 764.02,-21.29 764.02,-18.37 799.42,-16 843,-16 886.58,-16 921.98,-18.37 921.98,-21.29 921.98,-21.29 921.98,-68.88 921.98,-68.88"/>
|
||||
<path fill="none" stroke="#6c8ebf" d="M921.98,-68.88C921.98,-65.96 886.58,-63.59 843,-63.59 799.42,-63.59 764.02,-65.96 764.02,-68.88"/>
|
||||
<text text-anchor="middle" x="843" y="-41.38" font-family="monospace" font-size="11.00">StateFlow<StateB></text>
|
||||
</g>
|
||||
<!-- bBmore->sfB -->
|
||||
<g id="edge15" class="edge">
|
||||
<title>bBmore->sfB</title>
|
||||
<path fill="none" stroke="#888888" stroke-dasharray="5,2" d="M849.11,-281.75C847.41,-215.69 844.98,-121.8 843.76,-74.6"/>
|
||||
<polygon fill="#888888" stroke="#888888" points="845.6,-281.5 849.36,-291.41 852.6,-281.32 845.6,-281.5"/>
|
||||
<text text-anchor="middle" x="873.44" y="-181.42" font-family="monospace" font-size="10.00" fill="#888888">collect()</text>
|
||||
</g>
|
||||
<!-- foldB->sfB -->
|
||||
<g id="edge11" class="edge">
|
||||
<title>foldB->sfB</title>
|
||||
<path fill="none" stroke="#82b366" d="M817.62,-158.79C822.02,-139.25 828.75,-109.35 834.18,-85.25"/>
|
||||
<polygon fill="#82b366" stroke="#82b366" points="837.53,-86.3 836.31,-75.78 830.7,-84.77 837.53,-86.3"/>
|
||||
</g>
|
||||
<!-- bCmore->sfA -->
|
||||
<g id="edge18" class="edge">
|
||||
<title>bCmore->sfA</title>
|
||||
<path fill="none" stroke="#ff0000" stroke-dasharray="5,2" d="M991.07,-302.76C860.97,-236.91 641.61,-125.87 538.61,-73.74"/>
|
||||
<polygon fill="#ff0000" stroke="#ff0000" points="989.2,-305.74 999.7,-307.13 992.36,-299.49 989.2,-305.74"/>
|
||||
<text text-anchor="middle" x="737.84" y="-191.5" font-family="monospace" font-size="10.00" fill="#ff0000">collect()</text>
|
||||
</g>
|
||||
<!-- bCmore->sfB -->
|
||||
<g id="edge19" class="edge">
|
||||
<title>bCmore->sfB</title>
|
||||
<path fill="none" stroke="#ff0000" stroke-dasharray="5,2" d="M1036.74,-284.19C983.12,-218.02 905.64,-122.39 866.92,-74.6"/>
|
||||
<polygon fill="#ff0000" stroke="#ff0000" points="1033.84,-286.18 1042.86,-291.74 1039.28,-281.77 1033.84,-286.18"/>
|
||||
<text text-anchor="middle" x="965.33" y="-169.89" font-family="monospace" font-size="10.00" fill="#ff0000">collect()</text>
|
||||
</g>
|
||||
<!-- foldC -->
|
||||
<g id="node11" class="node">
|
||||
<title>foldC</title>
|
||||
<path fill="#d5e8d4" stroke="#82b366" d="M1109.72,-201.46C1109.72,-201.46 1016.27,-201.46 1016.27,-201.46 1010.27,-201.46 1004.27,-195.46 1004.27,-189.46 1004.27,-189.46 1004.27,-171.16 1004.27,-171.16 1004.27,-165.16 1010.27,-159.16 1016.27,-159.16 1016.27,-159.16 1109.72,-159.16 1109.72,-159.16 1115.72,-159.16 1121.72,-165.16 1121.72,-171.16 1121.72,-171.16 1121.72,-189.46 1121.72,-189.46 1121.72,-195.46 1115.72,-201.46 1109.72,-201.46"/>
|
||||
<text text-anchor="middle" x="1063" y="-176.61" font-family="monospace" font-size="11.00">reduce fold</text>
|
||||
</g>
|
||||
<!-- bCmore->foldC -->
|
||||
<g id="edge12" class="edge">
|
||||
<title>bCmore->foldC</title>
|
||||
<path fill="none" stroke="#d6ae00" d="M1083.07,-293.03C1078.22,-266.05 1072.72,-235.43 1068.71,-213.08"/>
|
||||
<polygon fill="#d6ae00" stroke="#d6ae00" points="1072.18,-212.61 1066.97,-203.39 1065.29,-213.85 1072.18,-212.61"/>
|
||||
<text text-anchor="middle" x="1027.89" y="-256.3" font-family="monospace" font-size="10.00" fill="#d6ae00">dispatch(action)</text>
|
||||
</g>
|
||||
<!-- sfC -->
|
||||
<g id="node12" class="node">
|
||||
<title>sfC</title>
|
||||
<path fill="#dae8fc" stroke="#6c8ebf" d="M1172.97,-68.88C1172.97,-71.79 1137.58,-74.16 1094,-74.16 1050.42,-74.16 1015.02,-71.79 1015.02,-68.88 1015.02,-68.88 1015.02,-21.29 1015.02,-21.29 1015.02,-18.37 1050.42,-16 1094,-16 1137.58,-16 1172.97,-18.37 1172.97,-21.29 1172.97,-21.29 1172.97,-68.88 1172.97,-68.88"/>
|
||||
<path fill="none" stroke="#6c8ebf" d="M1172.97,-68.88C1172.97,-65.96 1137.58,-63.59 1094,-63.59 1050.42,-63.59 1015.02,-65.96 1015.02,-68.88"/>
|
||||
<text text-anchor="middle" x="1094" y="-41.38" font-family="monospace" font-size="11.00">StateFlow<StateC></text>
|
||||
</g>
|
||||
<!-- bCmore->sfC -->
|
||||
<g id="edge16" class="edge">
|
||||
<title>bCmore->sfC</title>
|
||||
<path fill="none" stroke="#888888" stroke-dasharray="5,2" d="M1094,-281.75C1094,-215.69 1094,-121.8 1094,-74.6"/>
|
||||
<polygon fill="#888888" stroke="#888888" points="1090.5,-281.4 1094,-291.4 1097.5,-281.4 1090.5,-281.4"/>
|
||||
<text text-anchor="middle" x="1121" y="-181.42" font-family="monospace" font-size="10.00" fill="#888888">collect()</text>
|
||||
</g>
|
||||
<!-- foldC->sfC -->
|
||||
<g id="edge13" class="edge">
|
||||
<title>foldC->sfC</title>
|
||||
<path fill="none" stroke="#82b366" d="M1067.78,-158.79C1072.32,-139.25 1079.28,-109.35 1084.89,-85.25"/>
|
||||
<polygon fill="#82b366" stroke="#82b366" points="1088.23,-86.31 1087.09,-75.78 1081.42,-84.72 1088.23,-86.31"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 22 KiB |
@@ -1,5 +1,12 @@
|
||||
plugins {
|
||||
id("com.diffplug.spotless")
|
||||
id("io.gitlab.arturbosch.detekt") version "1.23.6"
|
||||
}
|
||||
|
||||
detekt {
|
||||
buildUponDefaultConfig = false
|
||||
config.setFrom(files("${rootProject.projectDir}/server/detekt.yml"))
|
||||
source.setFrom(files("core/src", "desktop/src"))
|
||||
}
|
||||
|
||||
allprojects {
|
||||
@@ -42,6 +49,7 @@ configure<com.diffplug.gradle.spotless.SpotlessExtension> {
|
||||
",dev.slimevr.tracking.trackers.*,dev.slimevr.desktop.platform.ProtobufMessages.*" +
|
||||
",solarxr_protocol.rpc.*,kotlinx.coroutines.*,com.illposed.osc.*,android.app.*",
|
||||
"ij_kotlin_allow_trailing_comma" to true,
|
||||
"ktlint_standard_filename" to "disabled",
|
||||
)
|
||||
val ktlintVersion = "1.8.0"
|
||||
kotlinGradle {
|
||||
|
||||
@@ -5,42 +5,9 @@
|
||||
* For more details take a look at the Java Libraries chapter in the Gradle
|
||||
* User Manual available at https://docs.gradle.org/6.3/userguide/java_library_plugin.html
|
||||
*/
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
|
||||
plugins {
|
||||
kotlin("jvm")
|
||||
kotlin("multiplatform")
|
||||
kotlin("plugin.serialization")
|
||||
`java-library`
|
||||
}
|
||||
|
||||
// FIXME: Please replace these to Java 11 as that's what they actually are
|
||||
kotlin {
|
||||
jvmToolchain {
|
||||
languageVersion.set(JavaLanguageVersion.of(17))
|
||||
}
|
||||
}
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion.set(JavaLanguageVersion.of(17))
|
||||
}
|
||||
}
|
||||
tasks.withType<KotlinCompile> {
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_17)
|
||||
freeCompilerArgs.set(listOf("-Xvalue-classes"))
|
||||
}
|
||||
}
|
||||
|
||||
// Set compiler to use UTF-8
|
||||
tasks.withType<JavaCompile> {
|
||||
options.encoding = "UTF-8"
|
||||
}
|
||||
tasks.withType<Test> {
|
||||
systemProperty("file.encoding", "UTF-8")
|
||||
}
|
||||
tasks.withType<Javadoc> {
|
||||
options.encoding = "UTF-8"
|
||||
}
|
||||
|
||||
tasks.withType<Jar> {
|
||||
@@ -57,51 +24,53 @@ allprojects {
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":solarxr-protocol"))
|
||||
kotlin {
|
||||
jvmToolchain(24)
|
||||
jvm()
|
||||
|
||||
// This dependency is used internally,
|
||||
// and not exposed to consumers on their own compile classpath.
|
||||
implementation("com.google.flatbuffers:flatbuffers-java:22.10.26")
|
||||
implementation("commons-cli:commons-cli:1.11.0")
|
||||
implementation("com.fasterxml.jackson.core:jackson-databind:2.21.0")
|
||||
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.0")
|
||||
sourceSets {
|
||||
val commonMain = getByName("commonMain") {
|
||||
kotlin.srcDir("src/main/java")
|
||||
dependencies {
|
||||
api(project(":solarxr-protocol:generated"))
|
||||
api("com.google.flatbuffers:flatbuffers-java:22.10.26")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0")
|
||||
implementation("com.mayakapps.kache:kache:2.1.1")
|
||||
implementation("io.klogging:klogging:0.11.7")
|
||||
implementation("com.appstractive:dns-sd-kt:1.1.0")
|
||||
|
||||
implementation("com.github.jonpeterson:jackson-module-model-versioning:1.2.2")
|
||||
implementation("org.apache.commons:commons-math3:3.6.1")
|
||||
implementation("org.apache.commons:commons-lang3:3.20.0")
|
||||
implementation("org.apache.commons:commons-collections4:4.5.0")
|
||||
val ktorVersion = "3.4.1"
|
||||
implementation("io.ktor:ktor-client-core:$ktorVersion")
|
||||
implementation("io.ktor:ktor-client-cio:$ktorVersion")
|
||||
implementation("io.ktor:ktor-server-core:$ktorVersion")
|
||||
implementation("io.ktor:ktor-server-cio:$ktorVersion")
|
||||
implementation("io.ktor:ktor-network:$ktorVersion")
|
||||
implementation("io.ktor:ktor-utils:$ktorVersion")
|
||||
|
||||
implementation("com.illposed.osc:javaosc-core:0.8")
|
||||
implementation("org.java-websocket:Java-WebSocket:1.+")
|
||||
implementation("com.melloware:jintellitype:1.+")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0")
|
||||
// Allow the use of reflection
|
||||
implementation(kotlin("reflect"))
|
||||
|
||||
// 2.1.1 - of kache cause OSCQuery to fail on android.
|
||||
// Same goes for upgrading coroutines. kache prob upgrade coroutines too.
|
||||
// proceed with caution if you plan on upgrading that library
|
||||
implementation("com.mayakapps.kache:kache:2.1.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.1")
|
||||
|
||||
api("com.github.loucass003:EspflashKotlin:v0.11.0")
|
||||
|
||||
// Allow the use of reflection
|
||||
implementation(kotlin("reflect"))
|
||||
|
||||
// Jitpack
|
||||
implementation("com.github.SlimeVR:oscquery-kt:566a0cba58")
|
||||
|
||||
// For SteamVR driver detection
|
||||
implementation("io.ktor:ktor-client-core:2.3.13")
|
||||
implementation("io.ktor:ktor-client-cio:2.3.13")
|
||||
|
||||
testImplementation(kotlin("test"))
|
||||
// Use JUnit test framework
|
||||
testImplementation(platform("org.junit:junit-bom:6.0.2"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter")
|
||||
testImplementation("org.junit.platform:junit-platform-launcher")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0")
|
||||
}
|
||||
}
|
||||
val commonTest = getByName("commonTest") {
|
||||
kotlin.srcDir("src/test/java")
|
||||
dependencies {
|
||||
implementation(kotlin("test"))
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
tasks.withType<JavaCompile> {
|
||||
options.encoding = "UTF-8"
|
||||
}
|
||||
tasks.withType<Test> {
|
||||
systemProperty("file.encoding", "UTF-8")
|
||||
useJUnitPlatform()
|
||||
}
|
||||
tasks.withType<Javadoc> {
|
||||
options.encoding = "UTF-8"
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2009-2012 jMonkeyEngine
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
package com.jme3.system;
|
||||
|
||||
/**
|
||||
* <code>NanoTimer</code> is a System.nanoTime implementation of
|
||||
* <code>Timer</code>. This is primarily useful for headless applications
|
||||
* running on a server.
|
||||
*
|
||||
* @author Matthew D. Hicks
|
||||
*/
|
||||
public class NanoTimer extends Timer {
|
||||
|
||||
private static final long TIMER_RESOLUTION = 1000000000L;
|
||||
private static final float INVERSE_TIMER_RESOLUTION = 1f / TIMER_RESOLUTION;
|
||||
|
||||
private long startTime;
|
||||
private long previousTime;
|
||||
private float tpf;
|
||||
private float fps;
|
||||
private long currentTime;
|
||||
|
||||
public NanoTimer() {
|
||||
startTime = System.nanoTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the time in seconds. The timer starts at 0.0 seconds.
|
||||
*
|
||||
* @return the current time in seconds
|
||||
*/
|
||||
|
||||
protected long getTimeInternal() {
|
||||
return System.nanoTime() - startTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTimeInSeconds() {
|
||||
return getTime() * INVERSE_TIMER_RESOLUTION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getTime() {
|
||||
return currentTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getResolution() {
|
||||
return TIMER_RESOLUTION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getFrameRate() {
|
||||
return fps;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTimePerFrame() {
|
||||
return tpf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update() {
|
||||
currentTime = getTimeInternal();
|
||||
tpf = (currentTime - previousTime) * (1.0f / TIMER_RESOLUTION);
|
||||
fps = 1.0f / tpf;
|
||||
previousTime = getTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
startTime = System.nanoTime();
|
||||
currentTime = getTimeInternal();
|
||||
previousTime = getTime();
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2009-2012 jMonkeyEngine
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software
|
||||
* without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
package com.jme3.system;
|
||||
|
||||
/**
|
||||
* <code>Timer</code> is the base class for a high resolution timer. It is
|
||||
* created from getTimer("display system")
|
||||
*
|
||||
* @author Mark Powell
|
||||
* @version $Id: Timer.java,v 1.18 2007/03/09 10:19:34 rherlitz Exp $
|
||||
*/
|
||||
public abstract class Timer {
|
||||
|
||||
/**
|
||||
* Returns the current time in ticks. A tick is an arbitrary measure of time
|
||||
* defined by the timer implementation. The number of ticks per second is
|
||||
* given by <code>getResolution()</code>. The timer starts at 0 ticks.
|
||||
*
|
||||
* @return a long value representing the current time
|
||||
*/
|
||||
public abstract long getTime();
|
||||
|
||||
/**
|
||||
* Returns the time in seconds. The timer starts at 0.0 seconds.
|
||||
*
|
||||
* @return the current time in seconds
|
||||
*/
|
||||
public float getTimeInSeconds() {
|
||||
return getTime() / (float) getResolution();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the resolution of the timer.
|
||||
*
|
||||
* @return the number of timer ticks per second
|
||||
*/
|
||||
public abstract long getResolution();
|
||||
|
||||
/**
|
||||
* Returns the "calls per second". If this is called every frame, then it
|
||||
* will return the "frames per second".
|
||||
*
|
||||
* @return The "calls per second".
|
||||
*/
|
||||
public abstract float getFrameRate();
|
||||
|
||||
/**
|
||||
* Returns the time, in seconds, between the last call and the current one.
|
||||
*
|
||||
* @return Time between this call and the last one.
|
||||
*/
|
||||
public abstract float getTimePerFrame();
|
||||
|
||||
/**
|
||||
* <code>update</code> recalculates the frame rate based on the previous
|
||||
* call to update. It is assumed that update is called each frame.
|
||||
*/
|
||||
public abstract void update();
|
||||
|
||||
/**
|
||||
* Reset the timer to 0. Clear any tpf history.
|
||||
*/
|
||||
public abstract void reset();
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package dev.slimevr
|
||||
|
||||
data class FeatureFlags(
|
||||
var steam: Boolean = false,
|
||||
var skipCheckUdev: Boolean = true,
|
||||
)
|
||||
@@ -1,96 +0,0 @@
|
||||
package dev.slimevr
|
||||
|
||||
import com.melloware.jintellitype.HotkeyListener
|
||||
import com.melloware.jintellitype.JIntellitype
|
||||
import dev.slimevr.config.KeybindingsConfig
|
||||
import dev.slimevr.tracking.trackers.TrackerUtils
|
||||
import io.eiren.util.OperatingSystem
|
||||
import io.eiren.util.OperatingSystem.Companion.currentPlatform
|
||||
import io.eiren.util.ann.AWTThread
|
||||
import io.eiren.util.logging.LogManager
|
||||
|
||||
class Keybinding @AWTThread constructor(val server: VRServer) : HotkeyListener {
|
||||
val config: KeybindingsConfig = server.configManager.vrConfig.keybindings
|
||||
|
||||
init {
|
||||
if (currentPlatform != OperatingSystem.WINDOWS) {
|
||||
LogManager
|
||||
.info(
|
||||
"[Keybinding] Currently only supported on Windows. Keybindings will be disabled.",
|
||||
)
|
||||
} else {
|
||||
try {
|
||||
if (JIntellitype.getInstance() != null) {
|
||||
JIntellitype.getInstance().addHotKeyListener(this)
|
||||
|
||||
val fullResetBinding = config.fullResetBinding
|
||||
JIntellitype.getInstance()
|
||||
.registerHotKey(FULL_RESET, fullResetBinding)
|
||||
LogManager.info("[Keybinding] Bound full reset to $fullResetBinding")
|
||||
|
||||
val yawResetBinding = config.yawResetBinding
|
||||
JIntellitype.getInstance()
|
||||
.registerHotKey(YAW_RESET, yawResetBinding)
|
||||
LogManager.info("[Keybinding] Bound yaw reset to $yawResetBinding")
|
||||
|
||||
val mountingResetBinding = config.mountingResetBinding
|
||||
JIntellitype.getInstance()
|
||||
.registerHotKey(MOUNTING_RESET, mountingResetBinding)
|
||||
LogManager.info("[Keybinding] Bound reset mounting to $mountingResetBinding")
|
||||
|
||||
val feetMountingResetBinding = config.feetMountingResetBinding
|
||||
JIntellitype.getInstance()
|
||||
.registerHotKey(FEET_MOUNTING_RESET, feetMountingResetBinding)
|
||||
LogManager.info("[Keybinding] Bound feet reset mounting to $feetMountingResetBinding")
|
||||
|
||||
val pauseTrackingBinding = config.pauseTrackingBinding
|
||||
JIntellitype.getInstance()
|
||||
.registerHotKey(PAUSE_TRACKING, pauseTrackingBinding)
|
||||
LogManager.info("[Keybinding] Bound pause tracking to $pauseTrackingBinding")
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
LogManager
|
||||
.warning(
|
||||
"[Keybinding] JIntellitype initialization failed. Keybindings will be disabled. Try restarting your computer.",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@AWTThread
|
||||
override fun onHotKey(identifier: Int) {
|
||||
when (identifier) {
|
||||
FULL_RESET -> server.scheduleResetTrackersFull(RESET_SOURCE_NAME, config.fullResetDelay)
|
||||
|
||||
YAW_RESET -> server.scheduleResetTrackersYaw(RESET_SOURCE_NAME, config.yawResetDelay)
|
||||
|
||||
MOUNTING_RESET -> server.scheduleResetTrackersMounting(
|
||||
RESET_SOURCE_NAME,
|
||||
config.mountingResetDelay,
|
||||
)
|
||||
|
||||
FEET_MOUNTING_RESET -> server.scheduleResetTrackersMounting(
|
||||
RESET_SOURCE_NAME,
|
||||
config.feetMountingResetDelay,
|
||||
TrackerUtils.feetsBodyParts,
|
||||
)
|
||||
|
||||
PAUSE_TRACKING ->
|
||||
server
|
||||
.scheduleTogglePauseTracking(
|
||||
RESET_SOURCE_NAME,
|
||||
config.pauseTrackingDelay,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val RESET_SOURCE_NAME = "Keybinding"
|
||||
|
||||
private const val FULL_RESET = 1
|
||||
private const val YAW_RESET = 2
|
||||
private const val MOUNTING_RESET = 3
|
||||
private const val FEET_MOUNTING_RESET = 4
|
||||
private const val PAUSE_TRACKING = 5
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package dev.slimevr
|
||||
|
||||
data class NetworkInfo(
|
||||
val name: String?,
|
||||
val description: String?,
|
||||
val category: NetworkCategory?,
|
||||
val connectivity: Set<ConnectivityFlags>?,
|
||||
val connected: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* @see <a href="https://learn.microsoft.com/en-us/windows/win32/api/netlistmgr/ne-netlistmgr-nlm_network_category">NLM_NETWORK_CATEGORY enumeration (netlistmgr.h)</a>
|
||||
*/
|
||||
enum class NetworkCategory(val value: Int) {
|
||||
PUBLIC(0),
|
||||
PRIVATE(1),
|
||||
DOMAIN_AUTHENTICATED(2),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun fromInt(value: Int) = entries.find { it.value == value }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see <a href="https://learn.microsoft.com/en-us/windows/win32/api/netlistmgr/ne-netlistmgr-nlm_connectivity">NLM_CONNECTIVITY enumeration (netlistmgr.h)</a>
|
||||
*/
|
||||
enum class ConnectivityFlags(val value: Int) {
|
||||
DISCONNECTED(0),
|
||||
IPV4_NOTRAFFIC(0x1),
|
||||
IPV6_NOTRAFFIC(0x2),
|
||||
IPV4_SUBNET(0x10),
|
||||
IPV4_LOCALNETWORK(0x20),
|
||||
IPV4_INTERNET(0x40),
|
||||
IPV6_SUBNET(0x100),
|
||||
IPV6_LOCALNETWORK(0x200),
|
||||
IPV6_INTERNET(0x400),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun fromInt(value: Int): Set<ConnectivityFlags> = if (value == 0) {
|
||||
setOf(DISCONNECTED)
|
||||
} else {
|
||||
entries.filter { it != DISCONNECTED && (value and it.value) != 0 }.toSet()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
abstract class NetworkProfileChecker {
|
||||
abstract val isSupported: Boolean
|
||||
abstract val publicNetworks: List<NetworkInfo>
|
||||
}
|
||||
|
||||
class StubNetworkProfileChecker : NetworkProfileChecker() {
|
||||
override val isSupported: Boolean
|
||||
get() = false
|
||||
override val publicNetworks: List<NetworkInfo>
|
||||
get() = listOf()
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package dev.slimevr;
|
||||
|
||||
public enum NetworkProtocol {
|
||||
OWO_LEGACY,
|
||||
SLIMEVR_RAW,
|
||||
SLIMEVR_FLATBUFFER,
|
||||
SLIMEVR_WEBSOCKET
|
||||
}
|
||||
@@ -1,502 +0,0 @@
|
||||
package dev.slimevr
|
||||
|
||||
import com.jme3.system.NanoTimer
|
||||
import dev.slimevr.autobone.AutoBoneHandler
|
||||
import dev.slimevr.bridge.Bridge
|
||||
import dev.slimevr.bridge.ISteamVRBridge
|
||||
import dev.slimevr.config.ConfigManager
|
||||
import dev.slimevr.firmware.FirmwareUpdateHandler
|
||||
import dev.slimevr.firmware.SerialFlashingHandler
|
||||
import dev.slimevr.games.vrchat.VRCConfigHandler
|
||||
import dev.slimevr.games.vrchat.VRCConfigHandlerStub
|
||||
import dev.slimevr.games.vrchat.VRChatConfigManager
|
||||
import dev.slimevr.guards.ServerGuards
|
||||
import dev.slimevr.osc.OSCHandler
|
||||
import dev.slimevr.osc.OSCRouter
|
||||
import dev.slimevr.osc.VMCHandler
|
||||
import dev.slimevr.osc.VRCOSCHandler
|
||||
import dev.slimevr.posestreamer.BVHRecorder
|
||||
import dev.slimevr.protocol.ProtocolAPI
|
||||
import dev.slimevr.protocol.rpc.TransactionInfo
|
||||
import dev.slimevr.protocol.rpc.settings.RPCSettingsHandler
|
||||
import dev.slimevr.reset.ResetHandler
|
||||
import dev.slimevr.reset.ResetTimerManager
|
||||
import dev.slimevr.reset.resetTimer
|
||||
import dev.slimevr.serial.ProvisioningHandler
|
||||
import dev.slimevr.serial.SerialHandler
|
||||
import dev.slimevr.serial.SerialHandlerStub
|
||||
import dev.slimevr.setup.HandshakeHandler
|
||||
import dev.slimevr.setup.TapSetupHandler
|
||||
import dev.slimevr.status.StatusSystem
|
||||
import dev.slimevr.tracking.processor.HumanPoseManager
|
||||
import dev.slimevr.tracking.processor.skeleton.HumanSkeleton
|
||||
import dev.slimevr.tracking.trackers.*
|
||||
import dev.slimevr.tracking.trackers.udp.TrackersUDPServer
|
||||
import dev.slimevr.trackingchecklist.TrackingChecklistManager
|
||||
import dev.slimevr.util.ann.VRServerThread
|
||||
import dev.slimevr.websocketapi.WebSocketVRBridge
|
||||
import io.eiren.util.Process
|
||||
import io.eiren.util.ann.ThreadSafe
|
||||
import io.eiren.util.ann.ThreadSecure
|
||||
import io.eiren.util.collections.FastList
|
||||
import io.eiren.util.logging.LogManager
|
||||
import solarxr_protocol.datatypes.TrackerIdT
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
import java.util.*
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.function.Consumer
|
||||
import kotlin.collections.ArrayList
|
||||
import kotlin.concurrent.schedule
|
||||
|
||||
typealias BridgeProvider = (
|
||||
server: VRServer,
|
||||
computedTrackers: List<Tracker>,
|
||||
) -> Sequence<Bridge>
|
||||
|
||||
const val SLIMEVR_IDENTIFIER = "dev.slimevr.SlimeVR"
|
||||
|
||||
class VRServer @JvmOverloads constructor(
|
||||
bridgeProvider: BridgeProvider = { _, _ -> sequence {} },
|
||||
featureFlagsProvider: (VRServer) -> FeatureFlags = { _ -> FeatureFlags() },
|
||||
serialHandlerProvider: (VRServer) -> SerialHandler = { _ -> SerialHandlerStub() },
|
||||
flashingHandlerProvider: (VRServer) -> SerialFlashingHandler? = { _ -> null },
|
||||
vrcConfigHandlerProvider: (VRServer) -> VRCConfigHandler = { _ -> VRCConfigHandlerStub() },
|
||||
networkProfileProvider: (VRServer) -> NetworkProfileChecker = { _ -> StubNetworkProfileChecker() },
|
||||
val processListProvider: () -> Sequence<Process> = { emptySequence() },
|
||||
val tryOpenUri: (String) -> Unit = {},
|
||||
acquireMulticastLock: () -> Any? = { null },
|
||||
@JvmField val configManager: ConfigManager,
|
||||
) : Thread("VRServer") {
|
||||
|
||||
@JvmField
|
||||
val humanPoseManager: HumanPoseManager
|
||||
private val trackers: MutableList<Tracker> = FastList()
|
||||
val trackersServer: TrackersUDPServer
|
||||
private val bridges: MutableList<Bridge> = FastList()
|
||||
private val tasks: Queue<Runnable> = LinkedBlockingQueue()
|
||||
private val newTrackersConsumers: MutableList<Consumer<Tracker>> = FastList()
|
||||
private val trackerStatusListeners: MutableList<TrackerStatusListener> = FastList()
|
||||
private val onTick: MutableList<Runnable> = FastList()
|
||||
private val lock = acquireMulticastLock()
|
||||
val oSCRouter: OSCRouter
|
||||
|
||||
@JvmField
|
||||
val vrcOSCHandler: VRCOSCHandler
|
||||
val vMCHandler: VMCHandler
|
||||
|
||||
@JvmField
|
||||
val deviceManager: DeviceManager
|
||||
|
||||
// UwU
|
||||
val featureFlags: FeatureFlags = featureFlagsProvider(this)
|
||||
|
||||
@JvmField
|
||||
val bvhRecorder: BVHRecorder
|
||||
|
||||
@JvmField
|
||||
val serialHandler: SerialHandler
|
||||
|
||||
var serialFlashingHandler: SerialFlashingHandler?
|
||||
|
||||
val firmwareUpdateHandler: FirmwareUpdateHandler
|
||||
|
||||
val vrcConfigManager: VRChatConfigManager
|
||||
|
||||
@JvmField
|
||||
val autoBoneHandler: AutoBoneHandler
|
||||
|
||||
@JvmField
|
||||
val tapSetupHandler: TapSetupHandler
|
||||
|
||||
@JvmField
|
||||
val protocolAPI: ProtocolAPI
|
||||
private val timer = Timer()
|
||||
private val resetTimerManager = ResetTimerManager()
|
||||
val fpsTimer = NanoTimer()
|
||||
|
||||
@JvmField
|
||||
val provisioningHandler: ProvisioningHandler
|
||||
|
||||
@JvmField
|
||||
val resetHandler: ResetHandler
|
||||
|
||||
@JvmField
|
||||
val statusSystem = StatusSystem()
|
||||
|
||||
@JvmField
|
||||
val handshakeHandler = HandshakeHandler()
|
||||
|
||||
val trackingChecklistManager: TrackingChecklistManager
|
||||
|
||||
val networkProfileChecker: NetworkProfileChecker
|
||||
|
||||
val serverGuards = ServerGuards()
|
||||
|
||||
init {
|
||||
deviceManager = DeviceManager(this)
|
||||
serialHandler = serialHandlerProvider(this)
|
||||
serialFlashingHandler = flashingHandlerProvider(this)
|
||||
provisioningHandler = ProvisioningHandler(this)
|
||||
resetHandler = ResetHandler()
|
||||
tapSetupHandler = TapSetupHandler()
|
||||
humanPoseManager = HumanPoseManager(this)
|
||||
// AutoBone requires HumanPoseManager first
|
||||
autoBoneHandler = AutoBoneHandler(this)
|
||||
firmwareUpdateHandler = FirmwareUpdateHandler(this)
|
||||
vrcConfigManager = VRChatConfigManager(this, vrcConfigHandlerProvider(this))
|
||||
networkProfileChecker = networkProfileProvider(this)
|
||||
trackingChecklistManager = TrackingChecklistManager(this)
|
||||
protocolAPI = ProtocolAPI(this)
|
||||
val computedTrackers = humanPoseManager.computedTrackers
|
||||
|
||||
// Start server for SlimeVR trackers
|
||||
val trackerPort = configManager.vrConfig.server.trackerPort
|
||||
LogManager.info("Starting the tracker server on port $trackerPort...")
|
||||
trackersServer = TrackersUDPServer(
|
||||
trackerPort,
|
||||
"Sensors UDP server",
|
||||
) { tracker: Tracker -> registerTracker(tracker) }
|
||||
|
||||
// Start bridges and WebSocket server
|
||||
for (bridge in bridgeProvider(this, computedTrackers) + sequenceOf(WebSocketVRBridge(computedTrackers, this))) {
|
||||
tasks.add(Runnable { bridge.startBridge() })
|
||||
bridges.add(bridge)
|
||||
}
|
||||
|
||||
// Initialize OSC handlers
|
||||
vrcOSCHandler = VRCOSCHandler(
|
||||
this,
|
||||
configManager.vrConfig.vrcOSC,
|
||||
computedTrackers,
|
||||
)
|
||||
vMCHandler = VMCHandler(
|
||||
this,
|
||||
humanPoseManager,
|
||||
configManager.vrConfig.vmc,
|
||||
)
|
||||
|
||||
// Initialize OSC router
|
||||
val oscHandlers = FastList<OSCHandler>()
|
||||
oscHandlers.add(vrcOSCHandler)
|
||||
oscHandlers.add(vMCHandler)
|
||||
oSCRouter = OSCRouter(configManager.vrConfig.oscRouter, oscHandlers)
|
||||
bvhRecorder = BVHRecorder(this)
|
||||
for (tracker in computedTrackers) {
|
||||
registerTracker(tracker)
|
||||
}
|
||||
|
||||
instance = this
|
||||
}
|
||||
|
||||
fun hasBridge(bridgeClass: Class<out Bridge?>): Boolean {
|
||||
for (bridge in bridges) {
|
||||
if (bridgeClass.isAssignableFrom(bridge.javaClass)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
fun getVRBridge(pred: (Bridge) -> Boolean): Bridge? {
|
||||
for (bridge in bridges) {
|
||||
if (pred(bridge)) return bridge
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
fun removeVRBridge(bridge: Bridge) {
|
||||
bridge.stopBridge()
|
||||
bridges.remove(bridge)
|
||||
}
|
||||
|
||||
fun addOnTick(runnable: Runnable) {
|
||||
onTick.add(runnable)
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
fun addNewTrackerConsumer(consumer: Consumer<Tracker>) {
|
||||
queueTask {
|
||||
newTrackersConsumers.add(consumer)
|
||||
for (tracker in trackers) {
|
||||
consumer.accept(tracker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
fun trackerUpdated(tracker: Tracker?) {
|
||||
queueTask {
|
||||
humanPoseManager.trackerUpdated(tracker)
|
||||
updateSkeletonModel()
|
||||
refreshTrackersDriftCompensationEnabled()
|
||||
configManager.vrConfig.writeTrackerConfig(tracker)
|
||||
configManager.saveConfig()
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
fun addSkeletonUpdatedCallback(consumer: Consumer<HumanSkeleton>) {
|
||||
queueTask { humanPoseManager.addSkeletonUpdatedCallback(consumer) }
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
override fun run() {
|
||||
trackersServer.start()
|
||||
while (true) {
|
||||
// final long start = System.currentTimeMillis();
|
||||
fpsTimer.update()
|
||||
do {
|
||||
val task = tasks.poll() ?: break
|
||||
task.run()
|
||||
} while (true)
|
||||
for (task in onTick) {
|
||||
task.run()
|
||||
}
|
||||
for (bridge in bridges) {
|
||||
bridge.dataRead()
|
||||
}
|
||||
for (tracker in trackers) {
|
||||
tracker.tick(fpsTimer.timePerFrame)
|
||||
}
|
||||
humanPoseManager.update()
|
||||
for (bridge in bridges) {
|
||||
bridge.dataWrite()
|
||||
}
|
||||
vrcOSCHandler.update()
|
||||
vMCHandler.update()
|
||||
// final long time = System.currentTimeMillis() - start;
|
||||
try {
|
||||
sleep(1) // 1000Hz
|
||||
} catch (error: InterruptedException) {
|
||||
LogManager.info("VRServer thread interrupted")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
fun queueTask(r: Runnable) {
|
||||
tasks.add(r)
|
||||
}
|
||||
|
||||
@VRServerThread
|
||||
private fun trackerAdded(tracker: Tracker) {
|
||||
humanPoseManager.trackerAdded(tracker)
|
||||
updateSkeletonModel()
|
||||
if (tracker.isComputed) {
|
||||
vMCHandler.addComputedTracker(tracker)
|
||||
}
|
||||
refreshTrackersDriftCompensationEnabled()
|
||||
}
|
||||
|
||||
@ThreadSecure
|
||||
fun registerTracker(tracker: Tracker) {
|
||||
configManager.vrConfig.readTrackerConfig(tracker)
|
||||
queueTask {
|
||||
trackers.add(tracker)
|
||||
trackerAdded(tracker)
|
||||
for (tc in newTrackersConsumers) {
|
||||
tc.accept(tracker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
fun updateSkeletonModel() {
|
||||
queueTask {
|
||||
humanPoseManager.updateSkeletonModelFromServer()
|
||||
vrcOSCHandler.setHeadTracker(TrackerUtils.getTrackerForSkeleton(trackers, TrackerPosition.HEAD))
|
||||
|
||||
val bridge = this.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge
|
||||
bridge?.updateShareSettingsAutomatically()
|
||||
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
|
||||
}
|
||||
}
|
||||
|
||||
fun resetTrackersFull(resetSourceName: String?, bodyParts: List<Int> = ArrayList()) {
|
||||
queueTask { humanPoseManager.resetTrackersFull(resetSourceName, bodyParts) }
|
||||
}
|
||||
|
||||
fun resetTrackersYaw(resetSourceName: String?, bodyParts: List<Int> = TrackerUtils.allBodyPartsButFingers) {
|
||||
queueTask { humanPoseManager.resetTrackersYaw(resetSourceName, bodyParts) }
|
||||
}
|
||||
|
||||
fun resetTrackersMounting(resetSourceName: String?, bodyParts: List<Int>? = null) {
|
||||
queueTask { humanPoseManager.resetTrackersMounting(resetSourceName, bodyParts) }
|
||||
}
|
||||
|
||||
fun clearTrackersMounting(resetSourceName: String?) {
|
||||
queueTask { humanPoseManager.clearTrackersMounting(resetSourceName) }
|
||||
}
|
||||
|
||||
fun getPauseTracking(): Boolean = humanPoseManager.getPauseTracking()
|
||||
|
||||
fun setPauseTracking(pauseTracking: Boolean, sourceName: String?) {
|
||||
queueTask {
|
||||
humanPoseManager.setPauseTracking(pauseTracking, sourceName)
|
||||
// Toggle trackers as they don't toggle when tracking is paused
|
||||
val bridge = this.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge
|
||||
bridge?.updateShareSettingsAutomatically()
|
||||
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
|
||||
}
|
||||
}
|
||||
|
||||
fun togglePauseTracking(sourceName: String?) {
|
||||
queueTask {
|
||||
humanPoseManager.togglePauseTracking(sourceName)
|
||||
// Toggle trackers as they don't toggle when tracking is paused
|
||||
val bridge = this.getVRBridge {
|
||||
it is ISteamVRBridge
|
||||
} as? ISteamVRBridge
|
||||
bridge?.updateShareSettingsAutomatically()
|
||||
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
|
||||
}
|
||||
}
|
||||
|
||||
fun scheduleResetTrackersFull(resetSourceName: String?, delay: Long, bodyParts: List<Int> = ArrayList(), tx: TransactionInfo? = null) {
|
||||
resetTimer(
|
||||
resetTimerManager,
|
||||
delay,
|
||||
onTick = { progress ->
|
||||
resetHandler.sendStarted(ResetType.Full, tx, bodyParts, progress, delay.toInt())
|
||||
},
|
||||
onComplete = {
|
||||
queueTask {
|
||||
humanPoseManager.resetTrackersFull(resetSourceName, bodyParts)
|
||||
resetHandler.sendFinished(ResetType.Full, tx, bodyParts, delay.toInt())
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fun scheduleResetTrackersYaw(resetSourceName: String?, delay: Long, bodyParts: List<Int> = TrackerUtils.allBodyPartsButFingers, tx: TransactionInfo? = null) {
|
||||
resetTimer(
|
||||
resetTimerManager,
|
||||
delay,
|
||||
onTick = { progress ->
|
||||
resetHandler.sendStarted(ResetType.Yaw, tx, bodyParts, progress, delay.toInt())
|
||||
},
|
||||
onComplete = {
|
||||
queueTask {
|
||||
humanPoseManager.resetTrackersYaw(resetSourceName, bodyParts)
|
||||
resetHandler.sendFinished(ResetType.Yaw, tx, bodyParts, delay.toInt())
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fun scheduleResetTrackersMounting(resetSourceName: String?, delay: Long, bodyParts: List<Int>? = null, tx: TransactionInfo? = null) {
|
||||
resetTimer(
|
||||
resetTimerManager,
|
||||
delay,
|
||||
onTick = { progress ->
|
||||
resetHandler.sendStarted(ResetType.Mounting, tx, bodyParts, progress, delay.toInt())
|
||||
},
|
||||
onComplete = {
|
||||
queueTask {
|
||||
humanPoseManager.resetTrackersMounting(resetSourceName, bodyParts)
|
||||
resetHandler.sendFinished(ResetType.Mounting, tx, bodyParts, delay.toInt())
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fun scheduleSetPauseTracking(pauseTracking: Boolean, sourceName: String?, delay: Long) {
|
||||
timer.schedule(delay) {
|
||||
queueTask { humanPoseManager.setPauseTracking(pauseTracking, sourceName) }
|
||||
}
|
||||
}
|
||||
|
||||
fun scheduleTogglePauseTracking(sourceName: String?, delay: Long) {
|
||||
timer.schedule(delay) {
|
||||
queueTask { humanPoseManager.togglePauseTracking(sourceName) }
|
||||
}
|
||||
}
|
||||
|
||||
fun setLegTweaksEnabled(value: Boolean) {
|
||||
queueTask { humanPoseManager.setLegTweaksEnabled(value) }
|
||||
}
|
||||
|
||||
fun setSkatingReductionEnabled(value: Boolean) {
|
||||
queueTask { humanPoseManager.setSkatingCorrectionEnabled(value) }
|
||||
}
|
||||
|
||||
fun setFloorClipEnabled(value: Boolean) {
|
||||
queueTask { humanPoseManager.setFloorClipEnabled(value) }
|
||||
}
|
||||
|
||||
val trackersCount: Int
|
||||
get() = trackers.size
|
||||
val allTrackers: List<Tracker>
|
||||
get() = FastList(trackers)
|
||||
|
||||
fun getTrackerById(id: TrackerIdT): Tracker? {
|
||||
for (tracker in trackers) {
|
||||
if (tracker.trackerNum != id.trackerNum) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle synthetic devices
|
||||
if (id.deviceId == null && tracker.device == null) {
|
||||
return tracker
|
||||
}
|
||||
if (tracker.device != null && id.deviceId != null && id.deviceId.id == tracker.device.id) {
|
||||
// This is a physical tracker, and both device id and the
|
||||
// tracker num match
|
||||
return tracker
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun clearTrackersDriftCompensation() {
|
||||
for (t in allTrackers) {
|
||||
if (t.isImu()) {
|
||||
t.resetsHandler.clearDriftCompensation()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshTrackersDriftCompensationEnabled() {
|
||||
for (t in allTrackers) {
|
||||
if (t.isImu()) {
|
||||
t.resetsHandler.refreshDriftCompensationEnabled()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun trackerStatusChanged(tracker: Tracker, oldStatus: TrackerStatus, newStatus: TrackerStatus) {
|
||||
trackerStatusListeners.forEach { it.onTrackerStatusChanged(tracker, oldStatus, newStatus) }
|
||||
}
|
||||
|
||||
fun addTrackerStatusListener(listener: TrackerStatusListener) {
|
||||
trackerStatusListeners.add(listener)
|
||||
}
|
||||
|
||||
fun removeTrackerStatusListener(listener: TrackerStatusListener) {
|
||||
trackerStatusListeners.removeIf { listener == it }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val nextLocalTrackerId = AtomicInteger()
|
||||
lateinit var instance: VRServer
|
||||
private set
|
||||
|
||||
val instanceInitialized: Boolean
|
||||
get() = ::instance.isInitialized
|
||||
|
||||
@JvmStatic
|
||||
fun getNextLocalTrackerId(): Int = nextLocalTrackerId.incrementAndGet()
|
||||
|
||||
@JvmStatic
|
||||
val currentLocalTrackerId: Int
|
||||
get() = nextLocalTrackerId.get()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package dev.slimevr
|
||||
|
||||
import dev.slimevr.bvh.BVHManager
|
||||
import dev.slimevr.config.AppConfig
|
||||
import dev.slimevr.firmware.FirmwareManager
|
||||
import dev.slimevr.heightcalibration.HeightCalibrationManager
|
||||
import dev.slimevr.networkprofile.NetworkProfileManager
|
||||
import dev.slimevr.provisioning.ProvisioningManager
|
||||
import dev.slimevr.resets.ResetsManager
|
||||
import dev.slimevr.serial.SerialServer
|
||||
import dev.slimevr.skeleton.Skeleton
|
||||
import dev.slimevr.trackingchecklist.TrackingChecklist
|
||||
import dev.slimevr.udp.UdpServer
|
||||
import dev.slimevr.vmc.VMCManager
|
||||
import dev.slimevr.vrchat.VRCConfigManager
|
||||
import dev.slimevr.vrcosc.VRCOSCManager
|
||||
|
||||
interface Phase1ContextProvider {
|
||||
val server: VRServer
|
||||
val config: AppConfig
|
||||
val serialServer: SerialServer
|
||||
}
|
||||
|
||||
data class Phase1Context(
|
||||
override val server: VRServer,
|
||||
override val config: AppConfig,
|
||||
override val serialServer: SerialServer,
|
||||
) : Phase1ContextProvider
|
||||
|
||||
interface AppContextProvider : Phase1ContextProvider {
|
||||
val featureFlags: FeatureFlags
|
||||
val skeleton: Skeleton
|
||||
val firmwareManager: FirmwareManager
|
||||
val vrcConfigManager: VRCConfigManager?
|
||||
val networkProfileManager: NetworkProfileManager?
|
||||
val provisioningManager: ProvisioningManager
|
||||
val heightCalibrationManager: HeightCalibrationManager
|
||||
val trackingChecklist: TrackingChecklist
|
||||
val udpServer: UdpServer
|
||||
val bvhManager: BVHManager
|
||||
val vmcManager: VMCManager
|
||||
val vrcOscManager: VRCOSCManager
|
||||
val resetsManager: ResetsManager
|
||||
fun startObserving()
|
||||
suspend fun dispose()
|
||||
}
|
||||
|
||||
class AppContext(
|
||||
override val server: VRServer,
|
||||
override val config: AppConfig,
|
||||
override val serialServer: SerialServer,
|
||||
override val featureFlags: FeatureFlags,
|
||||
override val skeleton: Skeleton,
|
||||
override val firmwareManager: FirmwareManager,
|
||||
override val vrcConfigManager: VRCConfigManager?,
|
||||
override val networkProfileManager: NetworkProfileManager?,
|
||||
override val provisioningManager: ProvisioningManager,
|
||||
override val heightCalibrationManager: HeightCalibrationManager,
|
||||
override val trackingChecklist: TrackingChecklist,
|
||||
override val udpServer: UdpServer,
|
||||
override val bvhManager: BVHManager,
|
||||
override val vmcManager: VMCManager,
|
||||
override val vrcOscManager: VRCOSCManager,
|
||||
override val resetsManager: ResetsManager,
|
||||
) : AppContextProvider {
|
||||
override fun startObserving() {
|
||||
skeleton.startObserving()
|
||||
firmwareManager.startObserving()
|
||||
provisioningManager.startObserving()
|
||||
heightCalibrationManager.startObserving()
|
||||
vrcConfigManager?.startObserving()
|
||||
networkProfileManager?.startObserving()
|
||||
trackingChecklist.startObserving(this)
|
||||
udpServer.startReceiving(this, server.context.scope)
|
||||
vmcManager.startObserving()
|
||||
vrcOscManager.startObserving(this)
|
||||
resetsManager.startObserving()
|
||||
}
|
||||
|
||||
override suspend fun dispose() {
|
||||
udpServer.dispose()
|
||||
}
|
||||
}
|
||||
@@ -1,698 +0,0 @@
|
||||
package dev.slimevr.autobone
|
||||
|
||||
import dev.slimevr.SLIMEVR_IDENTIFIER
|
||||
import dev.slimevr.VRServer
|
||||
import dev.slimevr.autobone.errors.*
|
||||
import dev.slimevr.config.AutoBoneConfig
|
||||
import dev.slimevr.config.SkeletonConfig
|
||||
import dev.slimevr.poseframeformat.PfrIO
|
||||
import dev.slimevr.poseframeformat.PfsIO
|
||||
import dev.slimevr.poseframeformat.PoseFrames
|
||||
import dev.slimevr.tracking.processor.HumanPoseManager
|
||||
import dev.slimevr.tracking.processor.config.SkeletonConfigManager
|
||||
import dev.slimevr.tracking.processor.config.SkeletonConfigOffsets
|
||||
import dev.slimevr.tracking.trackers.TrackerRole
|
||||
import io.eiren.util.OperatingSystem
|
||||
import io.eiren.util.StringUtils
|
||||
import io.eiren.util.collections.FastList
|
||||
import io.eiren.util.logging.LogManager
|
||||
import io.github.axisangles.ktmath.Vector3
|
||||
import org.apache.commons.lang3.tuple.Pair
|
||||
import java.io.File
|
||||
import java.util.*
|
||||
import java.util.function.Consumer
|
||||
import java.util.function.Function
|
||||
import kotlin.math.*
|
||||
|
||||
class AutoBone(private val server: VRServer) {
|
||||
// This is filled by loadConfigValues()
|
||||
val offsets = EnumMap<SkeletonConfigOffsets, Float>(
|
||||
SkeletonConfigOffsets::class.java,
|
||||
)
|
||||
val adjustOffsets = FastList(
|
||||
arrayOf(
|
||||
SkeletonConfigOffsets.HEAD,
|
||||
SkeletonConfigOffsets.NECK,
|
||||
SkeletonConfigOffsets.UPPER_CHEST,
|
||||
SkeletonConfigOffsets.CHEST,
|
||||
SkeletonConfigOffsets.WAIST,
|
||||
SkeletonConfigOffsets.HIP,
|
||||
// HIPS_WIDTH now works when using body proportion error! It's not the
|
||||
// best still, but it is somewhat functional
|
||||
SkeletonConfigOffsets.HIPS_WIDTH,
|
||||
SkeletonConfigOffsets.UPPER_LEG,
|
||||
SkeletonConfigOffsets.LOWER_LEG,
|
||||
),
|
||||
)
|
||||
|
||||
var estimatedHeight: Float = 1f
|
||||
|
||||
// The total height of the normalized adjusted offsets
|
||||
var adjustedHeightNormalized: Float = 1f
|
||||
|
||||
// #region Error functions
|
||||
var slideError = SlideError()
|
||||
var offsetSlideError = OffsetSlideError()
|
||||
var footHeightOffsetError = FootHeightOffsetError()
|
||||
var bodyProportionError = BodyProportionError()
|
||||
var heightError = HeightError()
|
||||
var positionError = PositionError()
|
||||
var positionOffsetError = PositionOffsetError()
|
||||
// #endregion
|
||||
|
||||
val globalConfig: AutoBoneConfig = server.configManager.vrConfig.autoBone
|
||||
val globalSkeletonConfig: SkeletonConfig = server.configManager.vrConfig.skeleton
|
||||
|
||||
init {
|
||||
loadConfigValues()
|
||||
}
|
||||
|
||||
private fun loadConfigValues() {
|
||||
// Remove all previous values
|
||||
offsets.clear()
|
||||
|
||||
// Get current or default skeleton configs
|
||||
val skeleton = server.humanPoseManager
|
||||
// Still compensate for a null skeleton, as it may not be initialized yet
|
||||
val getOffset: Function<SkeletonConfigOffsets, Float> =
|
||||
if (skeleton != null) {
|
||||
Function { key: SkeletonConfigOffsets -> skeleton.getOffset(key) }
|
||||
} else {
|
||||
val defaultConfig = SkeletonConfigManager(false)
|
||||
Function { config: SkeletonConfigOffsets ->
|
||||
defaultConfig.getOffset(config)
|
||||
}
|
||||
}
|
||||
for (bone in adjustOffsets) {
|
||||
val offset = getOffset.apply(bone)
|
||||
if (offset > 0f) {
|
||||
offsets[bone] = offset
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun applyConfig(
|
||||
humanPoseManager: HumanPoseManager,
|
||||
offsets: Map<SkeletonConfigOffsets, Float> = this.offsets,
|
||||
) {
|
||||
for ((offset, value) in offsets) {
|
||||
humanPoseManager.setOffset(offset, value)
|
||||
}
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun applyAndSaveConfig(humanPoseManager: HumanPoseManager? = this.server.humanPoseManager): Boolean {
|
||||
if (humanPoseManager == null) return false
|
||||
applyConfig(humanPoseManager)
|
||||
humanPoseManager.saveConfig()
|
||||
server.configManager.saveConfig()
|
||||
LogManager.info("[AutoBone] Configured skeleton bone lengths")
|
||||
return true
|
||||
}
|
||||
|
||||
fun calcTargetHmdHeight(
|
||||
frames: PoseFrames,
|
||||
config: AutoBoneConfig = globalConfig,
|
||||
): Float {
|
||||
val targetHeight: Float
|
||||
// Get the current skeleton from the server
|
||||
val humanPoseManager = server.humanPoseManager
|
||||
// Still compensate for a null skeleton, as it may not be initialized yet
|
||||
@Suppress("SENSELESS_COMPARISON")
|
||||
if (config.useSkeletonHeight && humanPoseManager != null) {
|
||||
// If there is a skeleton available, calculate the target height
|
||||
// from its configs
|
||||
targetHeight = humanPoseManager.userHeightFromConfig
|
||||
LogManager
|
||||
.warning(
|
||||
"[AutoBone] Target height loaded from skeleton (Make sure you reset before running!): $targetHeight",
|
||||
)
|
||||
} else {
|
||||
// Otherwise if there is no skeleton available, attempt to get the
|
||||
// max HMD height from the recording
|
||||
val hmdHeight = frames.maxHmdHeight
|
||||
if (hmdHeight <= MIN_HEIGHT) {
|
||||
LogManager
|
||||
.warning(
|
||||
"[AutoBone] Max headset height detected (Value seems too low, did you not stand up straight while measuring?): $hmdHeight",
|
||||
)
|
||||
} else {
|
||||
LogManager.info("[AutoBone] Max headset height detected: $hmdHeight")
|
||||
}
|
||||
|
||||
// Estimate target height from HMD height
|
||||
targetHeight = hmdHeight
|
||||
}
|
||||
return targetHeight
|
||||
}
|
||||
|
||||
private fun updateRecordingScale(step: PoseFrameStep<AutoBoneStep>, scale: Float) {
|
||||
step.framePlayer1.setScales(scale)
|
||||
step.framePlayer2.setScales(scale)
|
||||
step.skeleton1.update()
|
||||
step.skeleton2.update()
|
||||
}
|
||||
|
||||
fun filterFrames(frames: PoseFrames, step: PoseFrameStep<AutoBoneStep>) {
|
||||
// Calculate the initial frame errors and recording stats
|
||||
val frameErrors = FloatArray(frames.maxFrameCount)
|
||||
val frameStats = StatsCalculator()
|
||||
val recordingStats = StatsCalculator()
|
||||
for (i in 0 until frames.maxFrameCount) {
|
||||
frameStats.reset()
|
||||
for (j in 0 until frames.maxFrameCount) {
|
||||
if (i == j) continue
|
||||
|
||||
step.setCursors(
|
||||
i,
|
||||
j,
|
||||
updatePlayerCursors = true,
|
||||
)
|
||||
|
||||
frameStats.addValue(getErrorDeriv(step))
|
||||
}
|
||||
frameErrors[i] = frameStats.mean
|
||||
recordingStats.addValue(frameStats.mean)
|
||||
// LogManager.info("[AutoBone] Frame: ${i + 1}, Mean error: ${frameStats.mean} (SD ${frameStats.standardDeviation})")
|
||||
}
|
||||
LogManager.info("[AutoBone] Full recording mean error: ${frameStats.mean} (SD ${frameStats.standardDeviation})")
|
||||
|
||||
// Remove outlier frames
|
||||
val sdMult = 1.4f
|
||||
val mean = recordingStats.mean
|
||||
val sd = recordingStats.standardDeviation * sdMult
|
||||
for (i in frameErrors.size - 1 downTo 0) {
|
||||
val err = frameErrors[i]
|
||||
if (err < mean - sd || err > mean + sd) {
|
||||
for (frameHolder in frames.frameHolders) {
|
||||
frameHolder.frames.removeAt(i)
|
||||
}
|
||||
}
|
||||
}
|
||||
step.maxFrameCount = frames.maxFrameCount
|
||||
|
||||
// Calculate and print the resulting recording stats
|
||||
recordingStats.reset()
|
||||
for (i in 0 until frames.maxFrameCount) {
|
||||
frameStats.reset()
|
||||
for (j in 0 until frames.maxFrameCount) {
|
||||
if (i == j) continue
|
||||
|
||||
step.setCursors(
|
||||
i,
|
||||
j,
|
||||
updatePlayerCursors = true,
|
||||
)
|
||||
|
||||
frameStats.addValue(getErrorDeriv(step))
|
||||
}
|
||||
recordingStats.addValue(frameStats.mean)
|
||||
}
|
||||
LogManager.info("[AutoBone] Full recording after mean error: ${frameStats.mean} (SD ${frameStats.standardDeviation})")
|
||||
}
|
||||
|
||||
@Throws(AutoBoneException::class)
|
||||
fun processFrames(
|
||||
frames: PoseFrames,
|
||||
config: AutoBoneConfig = globalConfig,
|
||||
skeletonConfig: SkeletonConfig = globalSkeletonConfig,
|
||||
epochCallback: Consumer<Epoch>? = null,
|
||||
): AutoBoneResults {
|
||||
check(frames.frameHolders.isNotEmpty()) { "Recording has no trackers." }
|
||||
check(frames.maxFrameCount > 0) { "Recording has no frames." }
|
||||
|
||||
// Load current values for adjustable configs
|
||||
loadConfigValues()
|
||||
|
||||
// Set the target heights either from config or calculate them
|
||||
val targetHmdHeight = if (skeletonConfig.userHeight > MIN_HEIGHT) {
|
||||
skeletonConfig.userHeight
|
||||
} else {
|
||||
calcTargetHmdHeight(frames, config)
|
||||
}
|
||||
check(targetHmdHeight > MIN_HEIGHT) { "Configured height ($targetHmdHeight) is too small (<= $MIN_HEIGHT)." }
|
||||
|
||||
// Set up the current state, making all required players and setting up the
|
||||
// skeletons appropriately
|
||||
val step = PoseFrameStep<AutoBoneStep>(
|
||||
config = config,
|
||||
serverConfig = server.configManager,
|
||||
frames = frames,
|
||||
preEpoch = { step ->
|
||||
// Set the current adjust rate based on the current epoch
|
||||
step.data.adjustRate = decayFunc(step.config.initialAdjustRate, step.config.adjustRateDecay, step.epoch)
|
||||
},
|
||||
onStep = this::step,
|
||||
postEpoch = { step -> epoch(step, epochCallback) },
|
||||
randomSeed = config.randSeed,
|
||||
data = AutoBoneStep(
|
||||
targetHmdHeight = targetHmdHeight,
|
||||
adjustRate = 1f,
|
||||
),
|
||||
)
|
||||
|
||||
// Normalize the skeletons and get the normalized height for adjusted offsets
|
||||
scaleSkeleton(step.skeleton1)
|
||||
scaleSkeleton(step.skeleton2)
|
||||
adjustedHeightNormalized = sumAdjustedHeightOffsets(step.skeleton1)
|
||||
|
||||
// Normalize offsets based on the initial normalized skeleton
|
||||
scaleOffsets()
|
||||
|
||||
// Apply the initial normalized config values
|
||||
applyConfig(step.skeleton1)
|
||||
applyConfig(step.skeleton2)
|
||||
|
||||
// Initialize normalization to the set target height (also updates skeleton)
|
||||
estimatedHeight = targetHmdHeight
|
||||
updateRecordingScale(step, 1f / targetHmdHeight)
|
||||
|
||||
if (config.useFrameFiltering) {
|
||||
filterFrames(frames, step)
|
||||
}
|
||||
|
||||
// Iterate frames now that it's set up
|
||||
PoseFrameIterator.iterateFrames(step)
|
||||
|
||||
// Scale the normalized offsets to the estimated height for the final result
|
||||
for (entry in offsets.entries) {
|
||||
entry.setValue(entry.value * estimatedHeight)
|
||||
}
|
||||
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Target height: ${step.data.targetHmdHeight}, Final height: $estimatedHeight",
|
||||
)
|
||||
if (step.data.errorStats.mean > config.maxFinalError) {
|
||||
throw AutoBoneException("The final epoch error value (${step.data.errorStats.mean}) has exceeded the maximum allowed value (${config.maxFinalError}).")
|
||||
}
|
||||
|
||||
return AutoBoneResults(
|
||||
estimatedHeight,
|
||||
step.data.targetHmdHeight,
|
||||
offsets,
|
||||
)
|
||||
}
|
||||
|
||||
private fun epoch(
|
||||
step: PoseFrameStep<AutoBoneStep>,
|
||||
epochCallback: Consumer<Epoch>? = null,
|
||||
) {
|
||||
val config = step.config
|
||||
val epoch = step.epoch
|
||||
|
||||
// Calculate average error over the epoch
|
||||
if (epoch <= 0 || epoch >= config.numEpochs - 1 || (epoch + 1) % config.printEveryNumEpochs == 0) {
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Epoch: ${epoch + 1}, Mean error: ${step.data.errorStats.mean} (SD ${step.data.errorStats.standardDeviation}), Adjust rate: ${step.data.adjustRate}",
|
||||
)
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Target height: ${step.data.targetHmdHeight}, Estimated height: $estimatedHeight",
|
||||
)
|
||||
}
|
||||
|
||||
if (epochCallback != null) {
|
||||
// Scale the normalized offsets to the estimated height for the callback
|
||||
val scaledOffsets = EnumMap(offsets)
|
||||
for (entry in scaledOffsets.entries) {
|
||||
entry.setValue(entry.value * estimatedHeight)
|
||||
}
|
||||
epochCallback.accept(Epoch(epoch + 1, config.numEpochs, step.data.errorStats, scaledOffsets))
|
||||
}
|
||||
}
|
||||
|
||||
private fun step(step: PoseFrameStep<AutoBoneStep>) {
|
||||
// Pull frequently used variables out of trainingStep to reduce call length
|
||||
val skeleton1 = step.skeleton1
|
||||
val skeleton2 = step.skeleton2
|
||||
|
||||
// Scaling each step used to mean enforcing the target height, so keep that
|
||||
// behaviour to retain predictability
|
||||
if (!step.config.scaleEachStep) {
|
||||
// Try to estimate a new height by calculating the height with the lowest
|
||||
// error between adding or subtracting from the height
|
||||
val maxHeight = step.data.targetHmdHeight + 0.2f
|
||||
val minHeight = step.data.targetHmdHeight - 0.2f
|
||||
|
||||
step.data.hmdHeight = estimatedHeight
|
||||
val heightErrorDeriv = getErrorDeriv(step)
|
||||
val heightAdjust = errorFunc(heightErrorDeriv) * step.data.adjustRate
|
||||
|
||||
val negHeight = (estimatedHeight - heightAdjust).coerceIn(minHeight, maxHeight)
|
||||
updateRecordingScale(step, 1f / negHeight)
|
||||
step.data.hmdHeight = negHeight
|
||||
val negHeightErrorDeriv = getErrorDeriv(step)
|
||||
|
||||
val posHeight = (estimatedHeight + heightAdjust).coerceIn(minHeight, maxHeight)
|
||||
updateRecordingScale(step, 1f / posHeight)
|
||||
step.data.hmdHeight = posHeight
|
||||
val posHeightErrorDeriv = getErrorDeriv(step)
|
||||
|
||||
if (negHeightErrorDeriv < heightErrorDeriv && negHeightErrorDeriv < posHeightErrorDeriv) {
|
||||
estimatedHeight = negHeight
|
||||
// Apply the negative height scale
|
||||
updateRecordingScale(step, 1f / negHeight)
|
||||
} else if (posHeightErrorDeriv < heightErrorDeriv) {
|
||||
estimatedHeight = posHeight
|
||||
// The last estimated height set was the positive adjustment, so no need to apply it again
|
||||
} else {
|
||||
// Reset to the initial scale
|
||||
updateRecordingScale(step, 1f / estimatedHeight)
|
||||
}
|
||||
}
|
||||
|
||||
// Update the heights used for error calculations
|
||||
step.data.hmdHeight = estimatedHeight
|
||||
|
||||
val errorDeriv = getErrorDeriv(step)
|
||||
val error = errorFunc(errorDeriv)
|
||||
|
||||
// In case of fire
|
||||
if (java.lang.Float.isNaN(error) || java.lang.Float.isInfinite(error)) {
|
||||
// Extinguish
|
||||
LogManager
|
||||
.warning(
|
||||
"[AutoBone] Error value is invalid, resetting variables to recover",
|
||||
)
|
||||
// Reset adjustable config values
|
||||
loadConfigValues()
|
||||
|
||||
// Reset error sum values
|
||||
step.data.errorStats.reset()
|
||||
|
||||
// Continue on new data
|
||||
return
|
||||
}
|
||||
|
||||
// Store the error count for logging purposes
|
||||
step.data.errorStats.addValue(errorDeriv)
|
||||
val adjustVal = error * step.data.adjustRate
|
||||
|
||||
// If there is no adjustment whatsoever, skip this
|
||||
if (adjustVal == 0f) {
|
||||
return
|
||||
}
|
||||
|
||||
val slideL = skeleton2.getComputedTracker(TrackerRole.LEFT_FOOT).position -
|
||||
skeleton1.getComputedTracker(TrackerRole.LEFT_FOOT).position
|
||||
val slideLLen = slideL.len()
|
||||
val slideLUnit: Vector3? = if (slideLLen > MIN_SLIDE_DIST) slideL / slideLLen else null
|
||||
|
||||
val slideR = skeleton2.getComputedTracker(TrackerRole.RIGHT_FOOT).position -
|
||||
skeleton1.getComputedTracker(TrackerRole.RIGHT_FOOT).position
|
||||
val slideRLen = slideR.len()
|
||||
val slideRUnit: Vector3? = if (slideRLen > MIN_SLIDE_DIST) slideR / slideRLen else null
|
||||
|
||||
val intermediateOffsets = EnumMap(offsets)
|
||||
for (entry in intermediateOffsets.entries) {
|
||||
// Skip adjustment if the epoch is before starting (for logging only) or
|
||||
// if there are no BoneTypes for this value
|
||||
if (step.epoch < 0 || entry.key.affectedOffsets.isEmpty()) {
|
||||
break
|
||||
}
|
||||
val originalLength = entry.value
|
||||
|
||||
// Calculate the total effect of the bone based on change in rotation
|
||||
val slideDot = BoneContribution.getSlideDot(
|
||||
skeleton1,
|
||||
skeleton2,
|
||||
entry.key,
|
||||
slideLUnit,
|
||||
slideRUnit,
|
||||
)
|
||||
val dotLength = originalLength * slideDot
|
||||
|
||||
// Scale by the total effect of the bone
|
||||
val curAdjustVal = adjustVal * -dotLength
|
||||
if (curAdjustVal == 0f) {
|
||||
continue
|
||||
}
|
||||
|
||||
val newLength = originalLength + curAdjustVal
|
||||
// No small or negative numbers!!! Bad algorithm!
|
||||
if (newLength < 0.01f) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Apply new offset length
|
||||
skeleton1.setOffset(entry.key, newLength)
|
||||
skeleton2.setOffset(entry.key, newLength)
|
||||
scaleSkeleton(skeleton1, onlyAdjustedHeight = true)
|
||||
scaleSkeleton(skeleton2, onlyAdjustedHeight = true)
|
||||
|
||||
// Update the skeleton poses for the new offset length
|
||||
skeleton1.update()
|
||||
skeleton2.update()
|
||||
|
||||
val newErrorDeriv = getErrorDeriv(step)
|
||||
if (newErrorDeriv < errorDeriv) {
|
||||
// Apply the adjusted length to the current adjusted offsets
|
||||
entry.setValue(newLength)
|
||||
}
|
||||
|
||||
// Reset the skeleton values to minimize bias in other variables, it's applied later
|
||||
applyConfig(skeleton1)
|
||||
applyConfig(skeleton2)
|
||||
}
|
||||
|
||||
// Update the offsets from the adjusted ones
|
||||
offsets.putAll(intermediateOffsets)
|
||||
|
||||
// Normalize the scale, it will be upscaled to the target height later
|
||||
// We only need to scale height offsets, as other offsets are not affected by height
|
||||
scaleOffsets(onlyHeightOffsets = true)
|
||||
|
||||
// Apply the normalized offsets to the skeleton
|
||||
applyConfig(skeleton1)
|
||||
applyConfig(skeleton2)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sums only the adjusted height offsets of the provided HumanPoseManager
|
||||
*/
|
||||
private fun sumAdjustedHeightOffsets(humanPoseManager: HumanPoseManager): Float {
|
||||
var sum = 0f
|
||||
SkeletonConfigManager.HEIGHT_OFFSETS.forEach {
|
||||
if (!adjustOffsets.contains(it)) return@forEach
|
||||
sum += humanPoseManager.getOffset(it)
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
/**
|
||||
* Sums only the height offsets of the provided offset map
|
||||
*/
|
||||
private fun sumHeightOffsets(offsets: EnumMap<SkeletonConfigOffsets, Float> = this.offsets): Float {
|
||||
var sum = 0f
|
||||
SkeletonConfigManager.HEIGHT_OFFSETS.forEach {
|
||||
sum += offsets[it] ?: return@forEach
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
private fun scaleSkeleton(humanPoseManager: HumanPoseManager, targetHeight: Float = 1f, onlyAdjustedHeight: Boolean = false) {
|
||||
// Get the scale to apply for the appropriate offsets
|
||||
val scale = if (onlyAdjustedHeight) {
|
||||
// Only adjusted height offsets
|
||||
val adjHeight = sumAdjustedHeightOffsets(humanPoseManager)
|
||||
// Remove the constant from the target, leaving only the target for adjusted height offsets
|
||||
val adjTarget = targetHeight - (humanPoseManager.userHeightFromConfig - adjHeight)
|
||||
// Return only the scale for adjusted offsets
|
||||
adjTarget / adjHeight
|
||||
} else {
|
||||
targetHeight / humanPoseManager.userHeightFromConfig
|
||||
}
|
||||
|
||||
val offsets = if (onlyAdjustedHeight) SkeletonConfigManager.HEIGHT_OFFSETS else SkeletonConfigOffsets.values
|
||||
for (offset in offsets) {
|
||||
if (onlyAdjustedHeight && !adjustOffsets.contains(offset)) continue
|
||||
humanPoseManager.setOffset(offset, humanPoseManager.getOffset(offset) * scale)
|
||||
}
|
||||
}
|
||||
|
||||
private fun scaleOffsets(offsets: EnumMap<SkeletonConfigOffsets, Float> = this.offsets, targetHeight: Float = adjustedHeightNormalized, onlyHeightOffsets: Boolean = false) {
|
||||
// Get the scale to apply for the appropriate offsets
|
||||
val scale = targetHeight / sumHeightOffsets(offsets)
|
||||
|
||||
for (entry in offsets.entries) {
|
||||
if (onlyHeightOffsets && !SkeletonConfigManager.HEIGHT_OFFSETS.contains(entry.key)) continue
|
||||
entry.setValue(entry.value * scale)
|
||||
}
|
||||
}
|
||||
|
||||
@Throws(AutoBoneException::class)
|
||||
private fun getErrorDeriv(step: PoseFrameStep<AutoBoneStep>): Float {
|
||||
val config = step.config
|
||||
var sumError = 0f
|
||||
if (config.slideErrorFactor > 0f) {
|
||||
sumError += slideError.getStepError(step) * config.slideErrorFactor
|
||||
}
|
||||
if (config.offsetSlideErrorFactor > 0f) {
|
||||
sumError += (
|
||||
offsetSlideError.getStepError(step) *
|
||||
config.offsetSlideErrorFactor
|
||||
)
|
||||
}
|
||||
if (config.footHeightOffsetErrorFactor > 0f) {
|
||||
sumError += (
|
||||
footHeightOffsetError.getStepError(step) *
|
||||
config.footHeightOffsetErrorFactor
|
||||
)
|
||||
}
|
||||
if (config.bodyProportionErrorFactor > 0f) {
|
||||
sumError += (
|
||||
bodyProportionError.getStepError(step) *
|
||||
config.bodyProportionErrorFactor
|
||||
)
|
||||
}
|
||||
if (config.heightErrorFactor > 0f) {
|
||||
sumError += heightError.getStepError(step) * config.heightErrorFactor
|
||||
}
|
||||
if (config.positionErrorFactor > 0f) {
|
||||
sumError += (
|
||||
positionError.getStepError(step) *
|
||||
config.positionErrorFactor
|
||||
)
|
||||
}
|
||||
if (config.positionOffsetErrorFactor > 0f) {
|
||||
sumError += (
|
||||
positionOffsetError.getStepError(step) *
|
||||
config.positionOffsetErrorFactor
|
||||
)
|
||||
}
|
||||
return sumError
|
||||
}
|
||||
|
||||
val lengthsString: String
|
||||
get() {
|
||||
val configInfo = StringBuilder()
|
||||
offsets.forEach { (key, value) ->
|
||||
if (configInfo.isNotEmpty()) {
|
||||
configInfo.append(", ")
|
||||
}
|
||||
configInfo
|
||||
.append(key.configKey)
|
||||
.append(": ")
|
||||
.append(StringUtils.prettyNumber(value * 100f, 2))
|
||||
}
|
||||
return configInfo.toString()
|
||||
}
|
||||
|
||||
fun saveRecording(frames: PoseFrames, recordingFile: File) {
|
||||
if (saveDir.isDirectory || saveDir.mkdirs()) {
|
||||
LogManager
|
||||
.info("[AutoBone] Exporting frames to \"${recordingFile.path}\"...")
|
||||
if (PfsIO.tryWriteToFile(recordingFile, frames)) {
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Done exporting! Recording can be found at \"${recordingFile.path}\".",
|
||||
)
|
||||
} else {
|
||||
LogManager
|
||||
.severe(
|
||||
"[AutoBone] Failed to export the recording to \"${recordingFile.path}\".",
|
||||
)
|
||||
}
|
||||
} else {
|
||||
LogManager
|
||||
.severe(
|
||||
"[AutoBone] Failed to create the recording directory \"${saveDir.path}\".",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun saveRecording(frames: PoseFrames, recordingFileName: String) {
|
||||
saveRecording(frames, File(saveDir, recordingFileName))
|
||||
}
|
||||
|
||||
fun saveRecording(frames: PoseFrames) {
|
||||
var recordingFile: File
|
||||
var recordingIndex = 1
|
||||
do {
|
||||
recordingFile = File(saveDir, "ABRecording${recordingIndex++}.pfs")
|
||||
} while (recordingFile.exists())
|
||||
saveRecording(frames, recordingFile)
|
||||
}
|
||||
|
||||
fun loadRecordings(): FastList<Pair<String, PoseFrames>> {
|
||||
val recordings = FastList<Pair<String, PoseFrames>>()
|
||||
|
||||
loadDir.listFiles()?.forEach { file ->
|
||||
if (!file.isFile) return@forEach
|
||||
|
||||
val frames = if (file.name.endsWith(".pfs", ignoreCase = true)) {
|
||||
LogManager.info("[AutoBone] Loading PFS recording from \"${file.path}\"...")
|
||||
PfsIO.tryReadFromFile(file)
|
||||
} else if (file.name.endsWith(".pfr", ignoreCase = true)) {
|
||||
LogManager.info("[AutoBone] Loading PFR recording from \"${file.path}\"...")
|
||||
PfrIO.tryReadFromFile(file)
|
||||
} else {
|
||||
return@forEach
|
||||
}
|
||||
|
||||
if (frames == null) {
|
||||
LogManager.severe("[AutoBone] Failed to load recording from \"${file.path}\".")
|
||||
} else {
|
||||
recordings.add(Pair.of(file.name, frames))
|
||||
LogManager.info("[AutoBone] Loaded recording from \"${file.path}\".")
|
||||
}
|
||||
}
|
||||
|
||||
return recordings
|
||||
}
|
||||
|
||||
inner class Epoch(
|
||||
val epoch: Int,
|
||||
val totalEpochs: Int,
|
||||
val epochError: StatsCalculator,
|
||||
val configValues: EnumMap<SkeletonConfigOffsets, Float>,
|
||||
) {
|
||||
override fun toString(): String = "Epoch: $epoch, Epoch error: $epochError"
|
||||
}
|
||||
|
||||
inner class AutoBoneResults(
|
||||
val finalHeight: Float,
|
||||
val targetHeight: Float,
|
||||
val configValues: EnumMap<SkeletonConfigOffsets, Float>,
|
||||
) {
|
||||
val heightDifference: Float
|
||||
get() = abs(targetHeight - finalHeight)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val MIN_HEIGHT = 0.4f
|
||||
const val MIN_SLIDE_DIST = 0.002f
|
||||
const val AUTOBONE_FOLDER = "AutoBone Recordings"
|
||||
const val LOADAUTOBONE_FOLDER = "Load AutoBone Recordings"
|
||||
|
||||
// FIXME: Won't work on iOS and Android, maybe fix resolveConfigDirectory more than this
|
||||
val saveDir = File(
|
||||
OperatingSystem.resolveConfigDirectory(SLIMEVR_IDENTIFIER)?.resolve(
|
||||
AUTOBONE_FOLDER,
|
||||
)?.toString() ?: AUTOBONE_FOLDER,
|
||||
)
|
||||
val loadDir = File(
|
||||
OperatingSystem.resolveConfigDirectory(SLIMEVR_IDENTIFIER)?.resolve(
|
||||
LOADAUTOBONE_FOLDER,
|
||||
)?.toString() ?: LOADAUTOBONE_FOLDER,
|
||||
)
|
||||
|
||||
// Mean square error function
|
||||
private fun errorFunc(errorDeriv: Float): Float = 0.5f * (errorDeriv * errorDeriv)
|
||||
|
||||
private fun decayFunc(initialAdjustRate: Float, adjustRateDecay: Float, epoch: Int): Float = if (epoch >= 0) initialAdjustRate / (1 + (adjustRateDecay * epoch)) else 0.0f
|
||||
|
||||
val SYMM_CONFIGS = arrayOf(
|
||||
SkeletonConfigOffsets.HIPS_WIDTH,
|
||||
SkeletonConfigOffsets.SHOULDERS_WIDTH,
|
||||
SkeletonConfigOffsets.SHOULDERS_DISTANCE,
|
||||
SkeletonConfigOffsets.UPPER_ARM,
|
||||
SkeletonConfigOffsets.LOWER_ARM,
|
||||
SkeletonConfigOffsets.UPPER_LEG,
|
||||
SkeletonConfigOffsets.LOWER_LEG,
|
||||
SkeletonConfigOffsets.FOOT_LENGTH,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,408 +0,0 @@
|
||||
package dev.slimevr.autobone
|
||||
|
||||
import dev.slimevr.VRServer
|
||||
import dev.slimevr.autobone.AutoBone.AutoBoneResults
|
||||
import dev.slimevr.autobone.AutoBone.Companion.loadDir
|
||||
import dev.slimevr.autobone.errors.AutoBoneException
|
||||
import dev.slimevr.poseframeformat.PoseFrames
|
||||
import dev.slimevr.poseframeformat.PoseRecorder
|
||||
import dev.slimevr.poseframeformat.PoseRecorder.RecordingProgress
|
||||
import dev.slimevr.poseframeformat.trackerdata.TrackerFrameData
|
||||
import dev.slimevr.poseframeformat.trackerdata.TrackerFrames
|
||||
import dev.slimevr.tracking.processor.config.SkeletonConfigManager
|
||||
import dev.slimevr.tracking.processor.config.SkeletonConfigOffsets
|
||||
import io.eiren.util.StringUtils
|
||||
import io.eiren.util.collections.FastList
|
||||
import io.eiren.util.logging.LogManager
|
||||
import org.apache.commons.lang3.tuple.Pair
|
||||
import java.util.*
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.thread
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
class AutoBoneHandler(private val server: VRServer) {
|
||||
private val poseRecorder: PoseRecorder = PoseRecorder(server)
|
||||
private val autoBone: AutoBone = AutoBone(server)
|
||||
|
||||
private val recordingLock = ReentrantLock()
|
||||
private var recordingThread: Thread? = null
|
||||
private val saveRecordingLock = ReentrantLock()
|
||||
private var saveRecordingThread: Thread? = null
|
||||
private val autoBoneLock = ReentrantLock()
|
||||
private var autoBoneThread: Thread? = null
|
||||
|
||||
private val listeners = CopyOnWriteArrayList<AutoBoneListener>()
|
||||
|
||||
fun addListener(listener: AutoBoneListener) {
|
||||
listeners.add(listener)
|
||||
}
|
||||
|
||||
fun removeListener(listener: AutoBoneListener) {
|
||||
listeners.removeIf { listener == it }
|
||||
}
|
||||
|
||||
private fun announceProcessStatus(
|
||||
processType: AutoBoneProcessType,
|
||||
message: String? = null,
|
||||
current: Long = -1L,
|
||||
total: Long = -1L,
|
||||
eta: Float = -1f,
|
||||
completed: Boolean = false,
|
||||
success: Boolean = true,
|
||||
) {
|
||||
listeners.forEach {
|
||||
it.onAutoBoneProcessStatus(
|
||||
processType,
|
||||
message,
|
||||
current,
|
||||
total,
|
||||
eta,
|
||||
completed,
|
||||
success,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Throws(AutoBoneException::class)
|
||||
private fun processFrames(frames: PoseFrames): AutoBoneResults = autoBone
|
||||
.processFrames(frames) { epoch ->
|
||||
listeners.forEach { listener -> listener.onAutoBoneEpoch(epoch) }
|
||||
}
|
||||
|
||||
fun startProcessByType(processType: AutoBoneProcessType?): Boolean {
|
||||
when (processType) {
|
||||
AutoBoneProcessType.RECORD -> startRecording()
|
||||
|
||||
AutoBoneProcessType.SAVE -> saveRecording()
|
||||
|
||||
AutoBoneProcessType.PROCESS -> processRecording()
|
||||
|
||||
else -> {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun startRecording() {
|
||||
recordingLock.withLock {
|
||||
// Prevent running multiple times
|
||||
if (recordingThread != null) {
|
||||
return
|
||||
}
|
||||
recordingThread = thread(start = true) { startRecordingThread() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun startRecordingThread() {
|
||||
try {
|
||||
if (poseRecorder.isReadyToRecord) {
|
||||
announceProcessStatus(AutoBoneProcessType.RECORD, "Recording...")
|
||||
|
||||
// ex. 1000 samples at 20 ms per sample is 20 seconds
|
||||
val sampleCount = autoBone.globalConfig.sampleCount
|
||||
val sampleRate = autoBone.globalConfig.sampleRateMs / 1000f
|
||||
// Calculate total time in seconds
|
||||
val totalTime: Float = sampleCount * sampleRate
|
||||
|
||||
val framesFuture = poseRecorder
|
||||
.startFrameRecording(
|
||||
sampleCount,
|
||||
sampleRate,
|
||||
) { progress: RecordingProgress ->
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.RECORD,
|
||||
current = progress.frame.toLong(),
|
||||
total = progress.totalFrames.toLong(),
|
||||
eta = totalTime - (progress.frame * totalTime / progress.totalFrames),
|
||||
)
|
||||
}
|
||||
val frames = framesFuture.get()
|
||||
LogManager.info("[AutoBone] Done recording!")
|
||||
|
||||
// Save a recurring recording for users to send as debug info
|
||||
announceProcessStatus(AutoBoneProcessType.RECORD, "Saving recording...")
|
||||
autoBone.saveRecording(frames, "LastABRecording.pfs")
|
||||
if (autoBone.globalConfig.saveRecordings) {
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.RECORD,
|
||||
"Saving recording (from config option)...",
|
||||
)
|
||||
autoBone.saveRecording(frames)
|
||||
}
|
||||
listeners.forEach { listener: AutoBoneListener -> listener.onAutoBoneRecordingEnd(frames) }
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.RECORD,
|
||||
"Done recording!",
|
||||
completed = true,
|
||||
success = true,
|
||||
)
|
||||
} else {
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.RECORD,
|
||||
"The server is not ready to record",
|
||||
completed = true,
|
||||
success = false,
|
||||
)
|
||||
LogManager.severe("[AutoBone] Unable to record...")
|
||||
return
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.RECORD,
|
||||
"Recording failed: ${e.message}",
|
||||
completed = true,
|
||||
success = false,
|
||||
)
|
||||
LogManager.severe("[AutoBone] Failed recording!", e)
|
||||
} finally {
|
||||
recordingThread = null
|
||||
}
|
||||
}
|
||||
|
||||
fun stopRecording() {
|
||||
if (poseRecorder.isRecording) {
|
||||
poseRecorder.stopFrameRecording()
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelRecording() {
|
||||
if (poseRecorder.isRecording) {
|
||||
poseRecorder.cancelFrameRecording()
|
||||
}
|
||||
}
|
||||
|
||||
fun saveRecording() {
|
||||
saveRecordingLock.withLock {
|
||||
// Prevent running multiple times
|
||||
if (saveRecordingThread != null) {
|
||||
return
|
||||
}
|
||||
saveRecordingThread = thread(start = true) { saveRecordingThread() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveRecordingThread() {
|
||||
try {
|
||||
val framesFuture = poseRecorder.framesAsync
|
||||
if (framesFuture != null) {
|
||||
announceProcessStatus(AutoBoneProcessType.SAVE, "Waiting for recording...")
|
||||
val frames = framesFuture.get()
|
||||
check(frames.frameHolders.isNotEmpty()) { "Recording has no trackers." }
|
||||
check(frames.maxFrameCount > 0) { "Recording has no frames." }
|
||||
announceProcessStatus(AutoBoneProcessType.SAVE, "Saving recording...")
|
||||
autoBone.saveRecording(frames)
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.SAVE,
|
||||
"Recording saved!",
|
||||
completed = true,
|
||||
success = true,
|
||||
)
|
||||
} else {
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.SAVE,
|
||||
"No recording found",
|
||||
completed = true,
|
||||
success = false,
|
||||
)
|
||||
LogManager.severe("[AutoBone] Unable to save, no recording was done...")
|
||||
return
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.SAVE,
|
||||
"Failed to save recording: ${e.message}",
|
||||
completed = true,
|
||||
success = false,
|
||||
)
|
||||
LogManager.severe("[AutoBone] Failed to save recording!", e)
|
||||
} finally {
|
||||
saveRecordingThread = null
|
||||
}
|
||||
}
|
||||
|
||||
fun processRecording() {
|
||||
autoBoneLock.withLock {
|
||||
// Prevent running multiple times
|
||||
if (autoBoneThread != null) {
|
||||
return
|
||||
}
|
||||
autoBoneThread = thread(start = true) { processRecordingThread() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun processRecordingThread() {
|
||||
try {
|
||||
announceProcessStatus(AutoBoneProcessType.PROCESS, "Loading recordings...")
|
||||
val frameRecordings = autoBone.loadRecordings()
|
||||
if (!frameRecordings.isEmpty()) {
|
||||
LogManager.info("[AutoBone] Done loading frames!")
|
||||
} else {
|
||||
val framesFuture = poseRecorder.framesAsync
|
||||
if (framesFuture != null) {
|
||||
announceProcessStatus(AutoBoneProcessType.PROCESS, "Waiting for recording...")
|
||||
val frames = framesFuture.get()
|
||||
frameRecordings.add(Pair.of("<Recording>", frames))
|
||||
} else {
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.PROCESS,
|
||||
"No recordings found...",
|
||||
completed = true,
|
||||
success = false,
|
||||
)
|
||||
LogManager
|
||||
.severe(
|
||||
"[AutoBone] No recordings found in \"${loadDir.path}\" and no recording was done...",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
announceProcessStatus(AutoBoneProcessType.PROCESS, "Processing recording(s)...")
|
||||
LogManager.info("[AutoBone] Processing frames...")
|
||||
val errorStats = StatsCalculator()
|
||||
val offsetStats = EnumMap<SkeletonConfigOffsets, StatsCalculator>(
|
||||
SkeletonConfigOffsets::class.java,
|
||||
)
|
||||
val skeletonConfigManagerBuffer = SkeletonConfigManager(false)
|
||||
for ((key, value) in frameRecordings) {
|
||||
LogManager.info("[AutoBone] Processing frames from \"$key\"...")
|
||||
// Output tracker info for the recording
|
||||
printTrackerInfo(value.frameHolders)
|
||||
|
||||
// Actually process the recording
|
||||
val autoBoneResults = processFrames(value)
|
||||
LogManager.info("[AutoBone] Done processing!")
|
||||
|
||||
// #region Stats/Values
|
||||
// Accumulate height error
|
||||
errorStats.addValue(autoBoneResults.heightDifference)
|
||||
|
||||
// Accumulate length values
|
||||
for (offset in autoBoneResults.configValues) {
|
||||
val statCalc = offsetStats.getOrPut(offset.key) {
|
||||
StatsCalculator()
|
||||
}
|
||||
// Multiply by 100 to get cm
|
||||
statCalc.addValue(offset.value * 100f)
|
||||
}
|
||||
|
||||
// Calculate and output skeleton ratios
|
||||
skeletonConfigManagerBuffer.setOffsets(autoBoneResults.configValues)
|
||||
printSkeletonRatios(skeletonConfigManagerBuffer)
|
||||
|
||||
LogManager.info("[AutoBone] Length values: ${autoBone.lengthsString}")
|
||||
}
|
||||
// Length value stats
|
||||
val averageLengthVals = StringBuilder()
|
||||
offsetStats.forEach { (key, value) ->
|
||||
if (averageLengthVals.isNotEmpty()) {
|
||||
averageLengthVals.append(", ")
|
||||
}
|
||||
averageLengthVals
|
||||
.append(key.configKey)
|
||||
.append(": ")
|
||||
.append(StringUtils.prettyNumber(value.mean, 2))
|
||||
.append(" (SD ")
|
||||
.append(StringUtils.prettyNumber(value.standardDeviation, 2))
|
||||
.append(")")
|
||||
}
|
||||
LogManager.info("[AutoBone] Average length values: $averageLengthVals")
|
||||
|
||||
// Height error stats
|
||||
LogManager
|
||||
.info(
|
||||
"[AutoBone] Average height error: ${
|
||||
StringUtils.prettyNumber(errorStats.mean, 6)
|
||||
} (SD ${StringUtils.prettyNumber(errorStats.standardDeviation, 6)})",
|
||||
)
|
||||
// #endregion
|
||||
listeners.forEach { listener: AutoBoneListener -> listener.onAutoBoneEnd(autoBone.offsets) }
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.PROCESS,
|
||||
"Done processing!",
|
||||
completed = true,
|
||||
success = true,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
announceProcessStatus(
|
||||
AutoBoneProcessType.PROCESS,
|
||||
"Processing failed: ${e.message}",
|
||||
completed = true,
|
||||
success = false,
|
||||
)
|
||||
LogManager.severe("[AutoBone] Failed adjustment!", e)
|
||||
} finally {
|
||||
autoBoneThread = null
|
||||
}
|
||||
}
|
||||
|
||||
private fun printTrackerInfo(trackers: FastList<TrackerFrames>) {
|
||||
val trackerInfo = StringBuilder()
|
||||
for (tracker in trackers) {
|
||||
val frame = tracker?.tryGetFrame(0) ?: continue
|
||||
|
||||
// Add a comma if this is not the first item listed
|
||||
if (trackerInfo.isNotEmpty()) {
|
||||
trackerInfo.append(", ")
|
||||
}
|
||||
|
||||
trackerInfo.append(frame.tryGetTrackerPosition()?.designation ?: "unassigned")
|
||||
|
||||
// Represent the data flags
|
||||
val trackerFlags = StringBuilder()
|
||||
if (frame.hasData(TrackerFrameData.ROTATION)) {
|
||||
trackerFlags.append("R")
|
||||
}
|
||||
if (frame.hasData(TrackerFrameData.POSITION)) {
|
||||
trackerFlags.append("P")
|
||||
}
|
||||
if (frame.hasData(TrackerFrameData.ACCELERATION)) {
|
||||
trackerFlags.append("A")
|
||||
}
|
||||
if (frame.hasData(TrackerFrameData.RAW_ROTATION)) {
|
||||
trackerFlags.append("r")
|
||||
}
|
||||
|
||||
// If there are data flags, print them in brackets after the designation
|
||||
if (trackerFlags.isNotEmpty()) {
|
||||
trackerInfo.append(" (").append(trackerFlags).append(")")
|
||||
}
|
||||
}
|
||||
LogManager.info("[AutoBone] (${trackers.size} trackers) [$trackerInfo]")
|
||||
}
|
||||
|
||||
private fun printSkeletonRatios(skeleton: SkeletonConfigManager) {
|
||||
val neckLength = skeleton.getOffset(SkeletonConfigOffsets.NECK)
|
||||
val upperChestLength = skeleton.getOffset(SkeletonConfigOffsets.UPPER_CHEST)
|
||||
val chestLength = skeleton.getOffset(SkeletonConfigOffsets.CHEST)
|
||||
val waistLength = skeleton.getOffset(SkeletonConfigOffsets.WAIST)
|
||||
val hipLength = skeleton.getOffset(SkeletonConfigOffsets.HIP)
|
||||
val torsoLength = upperChestLength + chestLength + waistLength + hipLength
|
||||
val hipWidth = skeleton.getOffset(SkeletonConfigOffsets.HIPS_WIDTH)
|
||||
val legLength = skeleton.getOffset(SkeletonConfigOffsets.UPPER_LEG) +
|
||||
skeleton.getOffset(SkeletonConfigOffsets.LOWER_LEG)
|
||||
val lowerLegLength = skeleton.getOffset(SkeletonConfigOffsets.LOWER_LEG)
|
||||
|
||||
val neckTorso = neckLength / torsoLength
|
||||
val chestTorso = (upperChestLength + chestLength) / torsoLength
|
||||
val torsoWaist = hipWidth / torsoLength
|
||||
val legTorso = legLength / torsoLength
|
||||
val legBody = legLength / (torsoLength + neckLength)
|
||||
val kneeLeg = lowerLegLength / legLength
|
||||
|
||||
LogManager.info(
|
||||
"[AutoBone] Ratios: [{Neck-Torso: ${
|
||||
StringUtils.prettyNumber(neckTorso)}}, {Chest-Torso: ${
|
||||
StringUtils.prettyNumber(chestTorso)}}, {Torso-Waist: ${
|
||||
StringUtils.prettyNumber(torsoWaist)}}, {Leg-Torso: ${
|
||||
StringUtils.prettyNumber(legTorso)}}, {Leg-Body: ${
|
||||
StringUtils.prettyNumber(legBody)}}, {Knee-Leg: ${
|
||||
StringUtils.prettyNumber(kneeLeg)}}]",
|
||||
)
|
||||
}
|
||||
|
||||
fun applyValues() {
|
||||
autoBone.applyAndSaveConfig()
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package dev.slimevr.autobone
|
||||
|
||||
import dev.slimevr.autobone.AutoBone.Epoch
|
||||
import dev.slimevr.poseframeformat.PoseFrames
|
||||
import dev.slimevr.tracking.processor.config.SkeletonConfigOffsets
|
||||
import java.util.*
|
||||
|
||||
interface AutoBoneListener {
|
||||
fun onAutoBoneProcessStatus(
|
||||
processType: AutoBoneProcessType,
|
||||
message: String?,
|
||||
current: Long,
|
||||
total: Long,
|
||||
eta: Float,
|
||||
completed: Boolean,
|
||||
success: Boolean,
|
||||
)
|
||||
|
||||
fun onAutoBoneRecordingEnd(recording: PoseFrames)
|
||||
fun onAutoBoneEpoch(epoch: Epoch)
|
||||
fun onAutoBoneEnd(configValues: EnumMap<SkeletonConfigOffsets, Float>)
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package dev.slimevr.autobone
|
||||
|
||||
enum class AutoBoneProcessType(val id: Int) {
|
||||
NONE(0),
|
||||
RECORD(1),
|
||||
SAVE(2),
|
||||
PROCESS(3),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun getById(id: Int): AutoBoneProcessType? = byId[id]
|
||||
}
|
||||
}
|
||||
|
||||
private val byId = AutoBoneProcessType.values().associateBy { it.id }
|
||||
Loaded 100 of 508 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user