Compare commits

..
Author SHA1 Message Date
Sapphire 81a46c2ea5 Fix tracker battery display when UDP tracker only sends level (#1850) 2026-05-19 19:10:54 +02:00
Sapphire 1006b32e83 Make sure bridge threads properly handle interrupts and cleanup (#1849) 2026-05-19 19:10:45 +02:00
SlimeVR-botandinex dd39621a30 Pontoon/GUI: Update Brazilian Portuguese (pt-BR)
Co-Authored-By: inex <[email protected]>
2026-05-18 23:27:09 +02:00
SlimeVR-botandnekomona 0f9a001f17 Pontoon/GUI: Update Simplified Chinese (zh-Hans)
Co-authored-by: nekomona <[email protected]> (zh-Hans)
2026-05-18 23:27:09 +02:00
SlimeVR-bot f94ac3d1b6 Pontoon/GUI: Update 28 localizations 2026-05-18 23:27:09 +02:00
SlimeVR-botandTluxxa 246342d7b7 Pontoon/GUI: Update Turkish (tr)
Co-Authored-By: Tluxxa <[email protected]>
2026-05-18 23:27:09 +02:00
lucas lelievre a29ad7c4d2 Fix onboarding start / end sequence (#1848) 2026-05-18 22:13:50 +02:00
Sapphire b522c82af3 Fix socket getting placed in XDG_CONFIG_HOME instead of data home (#1846) 2026-05-18 22:08:01 +02:00
lucas lelievre 4b239e892e Remove failed merge of Quiz in FWTool (#1836) 2026-05-18 22:06:31 +02:00
Sapphire bcc139ecc9 Fix URL whitelist regex (#1838) 2026-05-18 22:06:19 +02:00
Sapphire 0d2c2e4a5c Bindings provider bug fixes + reformat (#1823) 2026-05-04 15:57:57 +02:00
Sapphire 3d18eae168 Mark onboarding as done in onboardingEnded (#1830) 2026-05-04 15:57:52 +02:00
Sapphire f1e3be0aec Fix discord RPC connection repeatedly being disconnected and reconnected (#1833) 2026-05-04 15:57:47 +02:00
Sapphire bc46269c24 Restore old behaviour of maximize button toggling fullscreen (#1832) 2026-05-04 15:57:41 +02:00
Sapphire 905c5a4514 Retain VRMv0 extension in vrmJson (#1831) 2026-05-04 15:57:35 +02:00
Hannah 789ba55af5 Bugfix for launch args (#1821) 2026-04-21 21:16:58 +02:00
Hannah 986f8fcbb2 Fix server startup command (#1820) 2026-04-21 20:08:23 +02:00
Sapphire 3288069ae5 Deactivate feeder bridge when using new driver, add bindings provider (#1806) 2026-04-21 19:12:05 +02:00
Ilia Ki 15ff70dda2 Reduce allowed list of Gestures PIDs (#1818) 2026-04-20 19:19:14 +02:00
lucas lelievre f6833ecb85 fix videos (#1819) 2026-04-20 19:18:37 +02:00
Sapphire 638bce86e6 v20.0-rc.1 fixes (#1816) 2026-04-20 15:04:50 +02:00
94 changed files with 2776 additions and 873 deletions

No files matched your search

+2
View File
@@ -30,6 +30,8 @@
/server/src/main/java/dev/slimevr/tracking/processor/ @Erimelowo
/server/src/main/java/dev/slimevr/filtering/ @Erimelowo
/bindings-provider/ @ImSapphire
# Linux files
*.nix @loucass003
/flake.lock @loucass003
+45 -1
View File
@@ -13,6 +13,7 @@ jobs:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
matrix-cpp: ${{ steps.set-matrix.outputs.matrix-cpp }}
steps:
- id: set-matrix
shell: bash
@@ -25,7 +26,44 @@ jobs:
else
RESULT=$(echo "$BASE" | jq -c '.')
fi
RESULT_CPP=$(echo "$RESULT" | jq -c '[ .[] | select ( (.platform != "macos") and ( (.platform != "windows") or (.os | endswith("-arm") | not) ) ) ]')
echo "matrix={\"include\":$RESULT}" >> "$GITHUB_OUTPUT"
echo "matrix-cpp={\"include\":$RESULT_CPP}" >> "$GITHUB_OUTPUT"
build-bindings-provider:
name: Build bindings provider for ${{ matrix.os }}
needs: [setup-matrix]
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix-cpp) }}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
submodules: recursive
- if: matrix.platform == 'linux'
name: Install GCC
uses: egor-tensin/setup-gcc@v2
with:
version: 16
- name: Get CMake
uses: lukka/get-cmake@latest
- name: Configure
run: cmake -S bindings-provider/ -B bindings-provider/build -DCMAKE_BUILD_TYPE=Release
- name: Build
run: cmake --build bindings-provider/build --config Release -j6
- name: Upload artifact
uses: actions/upload-artifact@v7
with:
name: bindings-provider-${{ matrix.platform }}-${{ matrix.os }}
path: |
bindings-provider/build/slimevr-bindings-provider
bindings-provider/build/libopenvr_api.so
bindings-provider/build/Release/SlimeVR-Bindings-Provider.exe
bindings-provider/build/openvr_api.dll
gui-checks:
name: Gui Checks
runs-on: ubuntu-latest
@@ -125,7 +163,7 @@ jobs:
package-desktop:
name: Package Desktop (${{ matrix.platform }} - ${{ matrix.os }})
needs: [setup-matrix, build-server-jar, build-gui-frontend]
needs: [setup-matrix, build-server-jar, build-gui-frontend, build-bindings-provider]
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix) }}
@@ -149,6 +187,12 @@ jobs:
with:
name: server-jar
path: server
- if: contains(fromJson(needs.setup-matrix.outputs.matrix-cpp).include.*.os, matrix.os)
name: Download bindings provider artifact
uses: actions/download-artifact@v8
with:
name: bindings-provider-${{ matrix.platform }}-${{ matrix.os }}
path: bindings-provider/build/${{ matrix.platform == 'windows' && 'win' || 'linux' }}-${{ endsWith(matrix.os, '-arm') && 'arm64' || 'x64' }}
- name: Download GUI Dist
uses: actions/download-artifact@v8
with:
+3
View File
@@ -1,3 +1,6 @@
[submodule "solarxr-protocol"]
path = solarxr-protocol
url = https://github.com/SlimeVR/SolarXR-Protocol.git
[submodule "svr-bindings-provider/openvr"]
path = bindings-provider/openvr
url = https://github.com/ValveSoftware/openvr.git
+297
View File
@@ -0,0 +1,297 @@
---
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: true
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseArrows: false
AlignCaseColons: false
AlignConsecutiveTableGenBreakingDAGArgColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenCondOperatorColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenDefinitionColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignEscapedNewlines: Right
AlignOperands: DontAlign
AlignTrailingComments:
Kind: Never
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowBreakBeforeNoexceptSpecifier: Never
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseExpressionOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AllowShortNamespacesOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AttributeMacros:
- __capability
BinPackArguments: true
BinPackLongBracedList: true
BinPackParameters: BinPack
BitFieldColonSpacing: Both
BracedInitializerIndentWidth: -1
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterExternBlock: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAdjacentStringLiterals: true
BreakAfterAttributes: Leave
BreakAfterJavaFieldAnnotations: false
BreakAfterReturnType: None
BreakArrays: true
BreakBeforeBinaryOperators: All
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTemplateCloser: false
BreakBeforeTernaryOperators: true
BreakBinaryOperations: Never
BreakConstructorInitializers: BeforeComma
BreakFunctionDefinitionParameters: false
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
BreakTemplateDeclarations: MultiLine
ColumnLimit: 0
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
EnumTrailingComma: Leave
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: false
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: false
IndentExportBlock: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertBraces: false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLines:
AtEndOfFile: false
AtStartOfBlock: true
AtStartOfFile: true
KeepFormFeed: false
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ''
MacroBlockEnd: ''
MainIncludeChar: Quote
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 4
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
OneLineFormatOffRegex: ''
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakBeforeMemberAccess: 150
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakScopeResolution: 500
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
PPIndentWidth: -1
QualifierAlignment: Leave
ReferenceAlignment: Pointer
ReflowComments: Always
RemoveBracesLLVM: false
RemoveEmptyLinesInUnwrappedLines: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes:
Enabled: true
IgnoreCase: false
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterOperatorKeyword: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterNot: false
AfterOverloadedOperator: false
AfterPlacementOperator: true
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: true
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
ExceptDoubleParentheses: false
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TableGenBreakInsideDAGArg: DontBreak
TabWidth: 8
UseTab: Never
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
WrapNamespaceBodyWithEmptyLines: Leave
...
+12
View File
@@ -0,0 +1,12 @@
# Garbage left behind on Windows
.vs/
out/
CMakeFiles/
vcpkg_installed/
src/resources/resources.hpp
CMakeCache.txt
build.ninja
*.cmake
*.dll
*.log
+78
View File
@@ -0,0 +1,78 @@
cmake_minimum_required(VERSION 3.26)
project(SlimeVR-Bindings-Provider)
set(SOLARXR_PROTOCOL_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../solarxr-protocol")
set(FLATBUFFERS_GENERATED_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../solarxr-protocol/protocol/cpp")
# These are used to determine the OpenVR library path
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(PROCESSOR_ARCH "64")
else()
set(PROCESSOR_ARCH "32")
endif()
if(WIN32)
set(OPENVR_LIBRARY_NAME "openvr_api")
set(OPENVR_LIBRARY_EXT "dll")
set(PLATFORM_NAME "win")
elseif(APPLE)
set(OPENVR_LIBRARY_NAME "libopenvr_api")
set(OPENVR_LIBRARY_EXT "dylib")
set(PLATFORM_NAME "osx")
elseif(LINUX)
set(OPENVR_LIBRARY_NAME "libopenvr_api")
set(OPENVR_LIBRARY_EXT "so")
if (CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
set(PLATFORM_NAME "linuxarm")
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
set(PLATFORM_NAME "linux")
else()
message(FATAL_ERROR "Unknown/unsupported CPU architecture")
endif()
else()
message(FATAL_ERROR "Unknown/unsupported platform")
endif()
set(OPENVR_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/openvr")
message(STATUS "OpenVR library search path: ${OPENVR_ROOT}/lib/${PLATFORM_NAME}${PROCESSOR_ARCH}")
find_library(OPENVR_LIBRARY NAMES openvr_api REQUIRED PATHS "${OPENVR_ROOT}/lib/${PLATFORM_NAME}${PROCESSOR_ARCH}/" NO_DEFAULT_PATH)
message(STATUS "Found OpenVR library at: ${OPENVR_LIBRARY}")
add_executable("${PROJECT_NAME}"
"${CMAKE_CURRENT_SOURCE_DIR}/src/paths.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/logger.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/solarxr.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/vr_utils.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp"
)
set_target_properties("${PROJECT_NAME}" PROPERTIES CXX_STANDARD 23)
target_include_directories("${PROJECT_NAME}" PRIVATE "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/include" "${SOLARXR_PROTOCOL_ROOT}/lib/flatbuffers/" "${FLATBUFFERS_GENERATED_ROOT}/include" "${CMAKE_CURRENT_SOURCE_DIR}/include" "${OPENVR_ROOT}/headers")
target_link_libraries("${PROJECT_NAME}" PRIVATE "${OPENVR_LIBRARY}")
if(LINUX)
set_target_properties("${PROJECT_NAME}" PROPERTIES OUTPUT_NAME slimevr-bindings-provider)
endif()
set(OPENVR_RUNTIME_LIBRARY "${OPENVR_ROOT}/bin/${PLATFORM_NAME}${PROCESSOR_ARCH}/${OPENVR_LIBRARY_NAME}.${OPENVR_LIBRARY_EXT}")
message(STATUS "Found OpenVR runtime library: ${OPENVR_RUNTIME_LIBRARY}")
configure_file("${OPENVR_RUNTIME_LIBRARY}" "${CMAKE_CURRENT_BINARY_DIR}/." COPYONLY)
# Embed the resources into resources.hpp
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
src/resources/manifest.vrmanifest
src/resources/action_manifest.json
src/resources/generic.json
src/resources/knuckles.json
src/resources/oculus_touch.json
src/resources/vive_controller.json
)
file(STRINGS src/resources/manifest.vrmanifest SVR_VRAPP_MANIFEST NEWLINE_CONSUME)
file(STRINGS src/resources/action_manifest.json SVR_VRAPP_ACTION_MANIFEST NEWLINE_CONSUME)
file(STRINGS src/resources/generic.json SVR_VRAPP_GENERIC_BINDS NEWLINE_CONSUME)
file(STRINGS src/resources/knuckles.json SVR_VRAPP_KNUCKLES_BINDS NEWLINE_CONSUME)
file(STRINGS src/resources/oculus_touch.json SVR_VRAPP_OCULUS_BINDS NEWLINE_CONSUME)
file(STRINGS src/resources/vive_controller.json SVR_VRAPP_VIVE_BINDS NEWLINE_CONSUME)
configure_file(src/resources/resources.hpp.in src/resources/resources.hpp @ONLY)
target_include_directories("${PROJECT_NAME}" PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/src")
+21
View File
@@ -0,0 +1,21 @@
#include "logger.hpp"
#include "paths.hpp"
#ifdef _WIN32
#define WIN32_MEAN_AND_LEAN
#include <Windows.h>
#endif
Logger::Logger()
: log_stream(Paths::getLogPath() / "slimevr-bindings-provider.log",
std::ios::out | std::ios::app)
#ifdef _WIN32
, should_log_to_std_streams(GetConsoleWindow() != nullptr)
#endif
{
}
Logger &Logger::get() {
static Logger logger;
return logger;
}
+77
View File
@@ -0,0 +1,77 @@
#pragma once
#include <cassert>
#include <chrono>
#include <format>
#include <fstream>
#include <iomanip>
#include <iostream>
class Logger {
private:
std::ofstream log_stream;
#ifdef _WIN32
bool should_log_to_std_streams;
#endif
template <bool important, typename... Args>
void log(std::string_view suffix, std::format_string<Args...> fmt,
Args &&...args) {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
auto s = std::format(fmt, std::forward<Args>(args)...);
#ifdef _WIN32
if (should_log_to_std_streams) {
#endif
if constexpr (important)
std::cerr << suffix << ' ' << s << '\n';
else
std::cout << suffix << ' ' << s << '\n';
#ifdef _WIN32
}
#endif
log_stream << std::put_time(std::localtime(&time_t), "[%F %T]") //
<< ' ' << suffix << ' ' << s << '\n';
}
public:
Logger();
template <typename... Args>
void debug(std::format_string<Args...> fmt, Args &&...args) {
#ifndef NDEBUG
log<false>("[DEBUG]", fmt, std::forward<Args>(args)...);
#endif
}
template <typename... Args>
void info(std::format_string<Args...> fmt, Args &&...args) {
log<false>("[INFO]", fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void warning(std::format_string<Args...> fmt, Args &&...args) {
log<true>("[WARN]", fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void error(std::format_string<Args...> fmt, Args &&...args) {
log<true>("[ERROR]", fmt, std::forward<Args>(args)...);
}
void flush() {
#ifdef _WIN32
if (should_log_to_std_streams) {
#endif
std::cerr.flush();
std::cout.flush();
#ifdef _WIN32
}
#endif
log_stream.flush();
}
static Logger &get();
};
+288
View File
@@ -0,0 +1,288 @@
#include <cassert>
#include <csignal>
#include <map>
#include <optional>
#include <thread>
#include <tuple>
// These must be included before Windows.h because of some macro collisions.
#include "flatbuffers/flatbuffers.h"
#include "solarxr_protocol/generated/all_generated.h"
#include "logger.hpp"
#include "solarxr.hpp"
#include "vr_utils.hpp"
#include "openvr.h"
using namespace std::chrono_literals;
using namespace solarxr_protocol;
static void shutdown_vr(vr::IVRSystem *_sys) { vr::VR_Shutdown(); }
static void onYawReset(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Yaw, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onFullReset(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Full, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onMountingCalibration(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Mounting, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onFeetMountingCalibration(SolarXRConnection &conn) {
flatbuffers::FlatBufferBuilder fbb;
auto bodyParts = fbb.CreateVector(
{ datatypes::BodyPart::LEFT_FOOT, datatypes::BodyPart::RIGHT_FOOT });
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::Mounting, bodyParts, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
static void onToggleTracking(SolarXRConnection &conn) {
static bool shouldPause = false;
flatbuffers::FlatBufferBuilder fbb;
shouldPause = !shouldPause;
auto toggleReq = rpc::CreateSetPauseTrackingRequest(fbb, shouldPause);
auto msgHeader = rpc::CreateRpcMessageHeader(
fbb, nullptr, rpc::RpcMessage::SetPauseTrackingRequest,
toggleReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs, 0);
fbb.Finish(bundle);
conn.sendMsg(fbb);
}
sig_atomic_t should_exit = 0;
static void signal_handler(int signal) {
Logger::get().info("Received signal {}", signal);
should_exit = 1;
}
int main() {
auto &logger = Logger::get();
try {
SolarXRConnection conn;
std::unique_ptr<vr::IVRSystem, decltype(&shutdown_vr)> sys{ nullptr,
shutdown_vr };
// On vrlink, VR_Init returns
// VRInitError_Driver_WirelessHmdNotConnected while the connection
// is initialising, so keep calling VR_Init until it ends up
// succeeding
vr::EVRInitError err{ vr::VRInitError_Driver_WirelessHmdNotConnected };
while (err == vr::VRInitError_Driver_WirelessHmdNotConnected) {
sys.reset(vr::VR_Init(&err, vr::VRApplication_Background));
if (err == vr::VRInitError_Driver_WirelessHmdNotConnected)
std::this_thread::sleep_for(500ms);
}
if (sys == nullptr or err != vr::VRInitError_None) {
logger.error("Failed to init OpenVR: {} ({})",
vr::VR_GetVRInitErrorAsSymbol(err),
vr::VR_GetVRInitErrorAsEnglishDescription(err));
return 1;
}
logger.info("Initialised OpenVR, HMD model '{}'",
VRUtils::getStringProp(vr::k_unTrackedDeviceIndex_Hmd,
vr::Prop_ModelNumber_String)
.value_or("<unknown>"));
vr::IVRApplications *app = vr::VRApplications();
vr::IVRInput *input = vr::VRInput();
auto [appManifestPath, actionManifestPath] = VRUtils::initialiseManifest();
if (auto err = app->AddApplicationManifest(appManifestPath.string().data(), true);
err != vr::VRApplicationError_None) {
logger.error("Failed to add application manifest: {}",
app->GetApplicationsErrorNameFromEnum(err));
return 1;
}
// SetActionManifestPath may return IPCError if vrserver is busy and takes
// too long to reply, so keep invoking until it succeeds
{
vr::EVRInputError err{};
constexpr int max_tries = 5;
int tries = 0;
while ((err = input->SetActionManifestPath(
actionManifestPath.string().data()))
== vr::VRInputError_IPCError
&& tries++ < max_tries) {
logger.debug("IPC error loading action manifest, retrying ({}/{})",
tries, max_tries);
std::this_thread::sleep_for(20ms);
}
if (err != vr::VRInputError_None) {
logger.error("Failed to set action manifest path: {}",
std::to_underlying(err));
return 1;
}
}
vr::VRActionSetHandle_t action_set;
if (auto err = input->GetActionSetHandle("/actions/main", &action_set);
err != vr::VRInputError_None) {
logger.error("Failed to get main action set handle: {}",
std::to_underlying(err));
return 1;
}
std::map<std::string, std::tuple<vr::VRActionHandle_t, std::function<void(SolarXRConnection &)>>>
actions{
{ "/actions/main/in/YawReset",
std::make_tuple(vr::k_ulInvalidActionHandle, onYawReset) },
{ "/actions/main/in/FullReset",
std::make_tuple(vr::k_ulInvalidActionHandle, onFullReset) },
{ "/actions/main/in/MountingCalibration",
std::make_tuple(vr::k_ulInvalidActionHandle,
onMountingCalibration) },
{ "/actions/main/in/FeetMountingCalibration",
std::make_tuple(vr::k_ulInvalidActionHandle,
onFeetMountingCalibration) },
{ "/actions/main/in/ToggleTracking",
std::make_tuple(vr::k_ulInvalidActionHandle, onToggleTracking) },
};
for (auto &[name, tuple] : actions) {
auto &[handle, _] = tuple;
if (auto err = input->GetActionHandle(name.c_str(), &handle);
err != vr::VRInputError_None || handle == vr::k_ulInvalidActionHandle) {
logger.warning("Failed to get action handle for action {}: {}", name,
std::to_underlying(err));
}
}
constexpr auto interval = 1000ms / 30;
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
while (!should_exit) {
vr::VREvent_t event{};
while (sys->PollNextEvent(&event, sizeof(event))) {
switch (event.eventType) {
case vr::VREvent_Quit:
logger.info("OpenVR runtime requested quit");
should_exit = 1;
break;
case vr::VREvent_Input_BindingLoadFailed: {
auto &loadData = event.data.inputBinding;
logger.debug("Binding load failed (ulAppContainer={} "
"pathMessage={} pathUrl={} pathControllerType={})",
loadData.ulAppContainer, loadData.pathMessage,
loadData.pathUrl, loadData.pathControllerType);
break;
}
case vr::VREvent_Input_BindingLoadSuccessful: {
auto &loadData = event.data.inputBinding;
logger.debug("Binding load successful (ulAppContainer={} "
"pathMessage={} pathUrl={} pathControllerType={})",
loadData.ulAppContainer, loadData.pathMessage,
loadData.pathUrl, loadData.pathControllerType);
break;
}
case vr::VREvent_Input_ActionManifestReloaded:
logger.debug("Action manifest reloaded");
break;
case vr::VREvent_Input_ActionManifestLoadFailed: {
auto &manifestData = event.data.actionManifest;
logger.debug(
"Action manifest load failed (pathAppKey={} pathMessage={} "
"pathMessageParam={} pathManifestPath={})",
manifestData.pathAppKey, manifestData.pathMessage,
manifestData.pathMessageParam, manifestData.pathManifestPath);
break;
}
default:
break;
}
}
if (!conn.connected()) {
logger.warning("Connection to SlimeVR lost, exiting");
break;
}
vr::VRActiveActionSet_t set{
.ulActionSet = action_set,
.ulRestrictedToDevice = vr::k_ulInvalidInputValueHandle,
.ulSecondaryActionSet = vr::k_ulInvalidActionSetHandle,
.nPriority = 0,
};
if (auto err = input->UpdateActionState(&set, sizeof(set), 1);
err != vr::VRInputError_None) {
logger.warning("Error when updating action states: {}",
std::to_underlying(err));
}
for (auto &[name, tuple] : actions) {
auto &[handle, callback] = tuple;
vr::InputDigitalActionData_t action_data{};
if (auto err = input->GetDigitalActionData(
handle, &action_data, sizeof(action_data),
vr::k_ulInvalidInputValueHandle);
err != vr::VRInputError_None) {
logger.warning("Failed to get action state for {} ({}): {}", name,
handle, std::to_underlying(err));
continue;
}
if (action_data.bActive && action_data.bChanged && action_data.bState) {
logger.debug("Action {} triggered", name);
callback(conn);
}
}
logger.flush();
std::this_thread::sleep_for(interval);
}
logger.info("Main loop done");
} catch (std::exception &ex) {
logger.error("Exception in main: {}", ex.what());
logger.flush();
return 1;
}
logger.flush();
return 0;
}
+33
View File
@@ -0,0 +1,33 @@
#include "paths.hpp"
namespace fs = std::filesystem;
fs::path Paths::getDataPath() {
fs::path basePath{};
#if defined(__linux__)
if (const char *dataHomeOverride = getenv("XDG_DATA_HOME")) {
basePath = dataHomeOverride;
} else {
const char *homeDir = getenv("HOME");
if (homeDir == nullptr)
throw std::runtime_error("HOME is unset");
basePath = fs::path(homeDir) / ".local" / "share";
}
#elif defined(_WIN32)
{
const char *appData = getenv("APPDATA");
if (appData == nullptr)
throw std::runtime_error("APPDATA is unset");
basePath = appData;
}
#else
#error "Unsupported platform"
#endif
return basePath / "dev.slimevr.SlimeVR";
}
fs::path Paths::getLogPath() { return Paths::getDataPath() / "logs"; }
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <filesystem>
namespace Paths {
// Throws when path cannot be found
std::filesystem::path getDataPath() noexcept(false);
// Throws when path cannot be found
std::filesystem::path getLogPath() noexcept(false);
} // namespace Paths
@@ -0,0 +1,64 @@
{
"default_bindings": [
{
"controller_type": "generic",
"binding_url": "generic.json"
},
{
"controller_type": "oculus_touch",
"binding_url": "oculus_touch.json"
},
{
"controller_type": "knuckles",
"binding_url": "knuckles.json"
},
{
"controller_type": "vive_controller",
"binding_url": "vive_controller.json"
}
],
"actions": [
{
"name": "/actions/main/in/YawReset",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/FullReset",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/MountingCalibration",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/FeetMountingCalibration",
"requirement": "optional",
"type": "boolean"
},
{
"name": "/actions/main/in/ToggleTracking",
"requirement": "optional",
"type": "boolean"
}
],
"action_sets": [
{
"name": "/actions/main",
"usage": "leftright"
}
],
"localization": [
{
"language_tag": "en_us",
"/actions/main": "Utility Bindings",
"/actions/main/in/YawReset": "Yaw Reset",
"/actions/main/in/FullReset": "Full Reset",
"/actions/main/in/MountingCalibration": "Mounting Calibration",
"/actions/main/in/FeetMountingCalibration": "Feet Mounting Calibration",
"/actions/main/in/ToggleTracking": "Toggle Tracking"
}
]
}
@@ -0,0 +1,12 @@
{
"name": "Default Bindings for Generic",
"controller_type": "generic",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
@@ -0,0 +1,12 @@
{
"name": "Default Bindings for Knuckles",
"controller_type": "knuckles",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
@@ -0,0 +1,14 @@
{
"source": "builtin",
"applications": [{
"app_key": "dev.slimevr.BindingsProvider",
"is_dashboard_overlay": false,
"action_manifest_path": "action_manifest.json",
"strings": {
"en_us": {
"name": "SlimeVR Bindings Provider",
"description": "SlimeVR Bindings Provider"
}
}
}]
}
@@ -0,0 +1,12 @@
{
"name": "Default Bindings for Oculus Touch",
"controller_type": "oculus_touch",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
@@ -0,0 +1,8 @@
#pragma once
#cmakedefine SVR_VRAPP_MANIFEST R"(@SVR_VRAPP_MANIFEST@)"
#cmakedefine SVR_VRAPP_ACTION_MANIFEST R"(@SVR_VRAPP_ACTION_MANIFEST@)"
#cmakedefine SVR_VRAPP_GENERIC_BINDS R"(@SVR_VRAPP_GENERIC_BINDS@)"
#cmakedefine SVR_VRAPP_KNUCKLES_BINDS R"(@SVR_VRAPP_KNUCKLES_BINDS@)"
#cmakedefine SVR_VRAPP_OCULUS_BINDS R"(@SVR_VRAPP_OCULUS_BINDS@)"
#cmakedefine SVR_VRAPP_VIVE_BINDS R"(@SVR_VRAPP_VIVE_BINDS@)"
@@ -0,0 +1,12 @@
{
"name": "Default Bindings for Vive Wands",
"controller_type": "vive_controller",
"bindings": {
"/actions/main": {
"sources": [],
"skeleton": [],
"haptics": [],
"poses": []
}
}
}
+163
View File
@@ -0,0 +1,163 @@
#include "solarxr.hpp"
#include "logger.hpp"
#include <stdexcept>
#if defined(__linux__)
#include <sys/socket.h>
#include <sys/un.h>
#elif defined(_WIN32)
#include <Windows.h>
#else
#error "Unsupported platform"
#endif
namespace fs = std::filesystem;
fs::path SolarXRConnection::getSocketPath() {
using namespace std::string_view_literals;
#if defined(__linux__)
#define MAKE_SOCKET_PATH(PATH) \
std::make_pair(PATH##sv, static_cast<const char *>(getenv(PATH)))
constexpr std::string_view socketName = "SlimeVRRpc";
std::array<std::pair<std::string_view, const char *>, 4> socketPaths{
MAKE_SOCKET_PATH("SLIMEVR_SOCKET_DIR"),
MAKE_SOCKET_PATH("XDG_RUNTIME_DIR"),
MAKE_SOCKET_PATH("TMPDIR"),
{ "/tmp", "/tmp" }
};
#undef MAKE_SOCKET_PATH
for (auto [name, path] : socketPaths) {
if (path == nullptr) {
Logger::get().info(
"Skipping socket directory {} because it doesn't exist", name);
continue;
}
fs::path socketPath = fs::path(path) / socketName;
if (fs::exists(socketPath))
return socketPath;
Logger::get().info(
"Skipping socket directory {} because socket does not exist", name);
}
#elif defined(_WIN32)
throw std::logic_error(
"SolarXRConnection::getSocketPath should not be called on Windows");
#else
#error "Unsupported platform"
#endif
throw std::runtime_error("Failed to find socket directory");
}
SolarXRConnection::SolarXRConnection() {
#if defined(__linux__)
sockaddr_un addr{};
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, getSocketPath().string().data());
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
throw std::runtime_error(
std::format("Failed to create listen socket: {}", strerror(errno)));
}
if (connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
int e = errno;
close(fd);
throw std::runtime_error(std::format("Failed to connect to socket {}: {}",
addr.sun_path, strerror(e)));
}
#elif defined(_WIN32)
const char *pipeName = R"(\\.\pipe\SlimeVRRpc)";
if (!WaitNamedPipe(pipeName, 5000)) {
throw std::runtime_error("Timed out waiting for pipe");
}
pipe = CreateFile(pipeName, GENERIC_READ | GENERIC_WRITE, 0, nullptr,
OPEN_EXISTING, 0, nullptr);
if (pipe == INVALID_HANDLE_VALUE) {
throw std::runtime_error(
std::format("Unable to open pipe (error={})", GetLastError()));
}
#else
#error "Unsupported platform"
#endif
}
SolarXRConnection::~SolarXRConnection() {
#if defined(__linux__)
if (fd != -1)
close(fd);
#elif defined(_WIN32)
if (pipe != INVALID_HANDLE_VALUE)
CloseHandle(pipe);
#else
#error "Unsupported platform"
#endif
}
bool SolarXRConnection::connected() {
#if defined(__linux__)
if (read(fd, nullptr, 0) == -1) {
return !(errno == EBADF || errno == EINVAL);
}
return true;
#elif defined(_WIN32)
if (!WriteFile(pipe, nullptr, 0, nullptr, nullptr)) {
int err = GetLastError();
// The documentation says it should return ERROR_BROKEN_PIPE
// when the write-end has been closed, but it seems to actually
// return ERROR_NO_DATA...
return !(err == ERROR_NO_DATA || err == ERROR_BROKEN_PIPE);
}
return true;
#else
#error "Unsupported platform"
#endif
}
void SolarXRConnection::sendMsg(flatbuffers::FlatBufferBuilder &fbb) {
// The server expects the total size of the buffer to be written at the
// start of the packet, including the first 4 bytes for the size
int size = fbb.GetSize() + 4;
// This may be wrong on mixed-endianness, but oh well...
if constexpr (std::endian::native != std::endian::little)
size = std::byteswap(size);
#if defined(__linux__)
if (write(fd, &size, sizeof(size)) == -1) {
Logger::get().warning("Failed to write message size to socket: {}",
strerror(errno));
return;
}
if (write(fd, fbb.GetBufferPointer(), fbb.GetSize()) == -1) {
Logger::get().warning("Failed to write message to socket: {}",
strerror(errno));
return;
}
#elif defined(_WIN32)
uint8_t tempBuf[2048];
if (fbb.GetSize() > 2048 - 4) {
Logger::get().warning("Message is too big for temporary buffer");
return;
}
*reinterpret_cast<int *>(&tempBuf[0]) = size;
memcpy(&tempBuf[4], fbb.GetBufferPointer(), fbb.GetSize());
if (!WriteFile(pipe, tempBuf, fbb.GetSize() + 4, nullptr, nullptr)) {
Logger::get().warning("Failed to write message to pipe (error={})",
GetLastError());
return;
}
#else
#error "Unsupported platform"
#endif
}
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <filesystem>
#if defined(_WIN32)
#define WIN32_MEAN_AND_LEAN
#include <Windows.h>
#endif
#include "flatbuffers/flatbuffer_builder.h"
class SolarXRConnection {
private:
#if defined(__linux__)
int fd{ -1 };
#elif defined(_WIN32)
HANDLE pipe{ INVALID_HANDLE_VALUE };
#else
#error "Unsupported platform"
#endif
static std::filesystem::path getSocketPath();
public:
SolarXRConnection() noexcept(false);
~SolarXRConnection();
bool connected();
void sendMsg(flatbuffers::FlatBufferBuilder &fbb);
};
+72
View File
@@ -0,0 +1,72 @@
#include "vr_utils.hpp"
#include "logger.hpp"
#include "paths.hpp"
#include "resources/resources.hpp"
#include <array>
#include <fstream>
#include <string_view>
#include <utility>
namespace fs = std::filesystem;
std::optional<std::string>
VRUtils::getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
vr::ETrackedDeviceProperty prop) {
vr::IVRSystem *sys = vr::VRSystem();
vr::ETrackedPropertyError err{ vr::TrackedProp_Success };
uint32_t required_len = sys->GetStringTrackedDeviceProperty(deviceIndex, prop, nullptr, 0, &err);
if (err != vr::TrackedProp_BufferTooSmall) {
Logger::get().info(
"Failed to get size of string property {} for device {}: {}",
std::to_underlying(prop), deviceIndex,
sys->GetPropErrorNameFromEnum(err));
return std::nullopt;
}
std::string s(required_len - 1, '\0');
sys->GetStringTrackedDeviceProperty(deviceIndex, prop, s.data(), required_len,
&err);
if (err != vr::TrackedProp_Success) {
Logger::get().info("Failed to get string property {} for device {}: {}",
std::to_underlying(prop), deviceIndex,
sys->GetPropErrorNameFromEnum(err));
return std::nullopt;
}
return s;
}
std::tuple<fs::path, fs::path> VRUtils::initialiseManifest() {
fs::path manifestDir = Paths::getDataPath() / "bindings-provider";
std::error_code ec;
fs::create_directories(manifestDir, ec);
if (ec) {
throw std::runtime_error(
std::format("Failed to create manifest folder: {}", ec.message()));
}
using namespace std::string_view_literals;
// Make sure the vrmanifest and action manifest are 1st and 2nd respectively
// in the array
std::array requiredFiles{
std::make_pair("manifest.vrmanifest"sv, SVR_VRAPP_MANIFEST),
std::make_pair("action_manifest.json"sv, SVR_VRAPP_ACTION_MANIFEST),
std::make_pair("generic.json"sv, SVR_VRAPP_GENERIC_BINDS),
std::make_pair("knuckles.json"sv, SVR_VRAPP_KNUCKLES_BINDS),
std::make_pair("oculus_touch.json"sv, SVR_VRAPP_OCULUS_BINDS),
std::make_pair("vive_controller.json"sv, SVR_VRAPP_VIVE_BINDS),
};
for (auto &[name, contents] : requiredFiles) {
fs::path path = manifestDir / name;
if (!fs::exists(path)) {
std::ofstream stream(path);
stream << contents;
}
}
return { manifestDir / requiredFiles.at(0).first,
manifestDir / requiredFiles.at(1).first };
}
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include <filesystem>
#include <optional>
#include <string>
#include <tuple>
#include "openvr.h"
namespace VRUtils {
std::optional<std::string> getStringProp(vr::TrackedDeviceIndex_t deviceIndex,
vr::ETrackedDeviceProperty prop);
// Returns <app vrmanifest path, action manifest json path>
std::tuple<std::filesystem::path, std::filesystem::path> initialiseManifest();
} // namespace VRUtils
+1 -1
View File
@@ -15,7 +15,7 @@
runtimeLibs = pkgs: (with pkgs; [
jdk17
alsa-lib at-spi2-atk at-spi2-core cairo cups dbus expat
alsa-lib libpulseaudio at-spi2-atk at-spi2-core cairo cups dbus expat
gdk-pixbuf glib gtk3 libdrm libgbm libglvnd libnotify
libxkbcommon mesa nspr nss pango systemd vulkan-loader
wayland xorg.libX11 xorg.libXcomposite xorg.libXdamage
+8
View File
@@ -35,6 +35,10 @@ linux:
extraFiles:
- from: "../server/desktop/build/libs/slimevr.jar"
to: "."
- from: "../bindings-provider/build/linux-${arch}/slimevr-bindings-provider"
to: "."
- from: "../bindings-provider/build/linux-${arch}/libopenvr_api.so"
to: "."
- from: "./electron/resources/69-slimevr-devices.rules"
to: "."
icon: "./electron/resources/icons"
@@ -59,6 +63,10 @@ win:
- from: "../server/core/resources"
to: "."
filter: ["**/*"]
- from: "../bindings-provider/build/${os}-${arch}/Release/SlimeVR-Bindings-Provider.exe"
to: "."
- from: "../bindings-provider/build/${os}-${arch}/openvr_api.dll"
to: "."
mac:
target: dmg
+29 -25
View File
@@ -16,6 +16,7 @@ import open from 'open';
import trayIcon from '../resources/icons/icon.png?asset';
import appleTrayIcon from '../resources/icons/Square30x30Logo.png?asset';
import { readFile, stat } from 'fs/promises';
import { pathToFileURL } from 'node:url';
import { getPlatform, handleIpc, isPortAvailable } from './utils';
import {
findServerJar,
@@ -57,6 +58,7 @@ protocol.registerSchemesAsPrivileged([
secure: true,
supportFetchAPI: true,
corsEnabled: true,
stream: true,
},
},
]);
@@ -126,11 +128,11 @@ handleIpc(IPC_CHANNELS.LOG, (e, type, ...args) => {
handleIpc(IPC_CHANNELS.OPEN_URL, (e, url) => {
const allowed_urls = [
/steam:\/\/.*/,
/ms-settings:network$/,
/https:\/\/.*\.slimevr\.dev.*/,
/https:\/\/github\.com\/.*/,
/https:\/\/discord\.gg\/slimevr$/,
/^steam:\/\//,
/^ms-settings:network$/,
/^https:\/\/(?:.+\.)?slimevr\.dev(?:\/.+)?$/,
/^https:\/\/github\.com\/SlimeVR(?:\/.+)?$/,
/^https:\/\/discord\.gg\/slimevr$/,
];
if (allowed_urls.find((a) => url.match(a))) open(url);
else logger.error({ url }, 'attempted to open non-whitelisted URL');
@@ -153,10 +155,11 @@ handleIpc(IPC_CHANNELS.STORAGE, async (e, { type, method, key, value }) => {
});
handleIpc(IPC_CHANNELS.DISCORD_PRESENCE, async (e, options) => {
if (options.enable && !discordPresence.state.ready) {
await discordPresence.connect();
if (options.enable) {
if (!discordPresence.state.ready)
await discordPresence.connect();
discordPresence.updateActivity(options.activity);
} else if (!options.enable && discordPresence.state.ready) {
} else if (discordPresence.state.ready) {
discordPresence.destroy();
}
});
@@ -278,18 +281,22 @@ function createWindow() {
});
handleIpc('window-actions', (e, action) => {
if (mainWindow === null) return;
switch (action) {
case 'close':
mainWindow?.close();
mainWindow.close();
break;
case 'hide':
mainWindow?.hide();
mainWindow.hide();
break;
case 'minimize':
mainWindow?.minimize();
mainWindow.minimize();
break;
case 'maximize':
mainWindow?.maximize();
case 'toggle-maximize':
if (mainWindow.isMaximized())
mainWindow.unmaximize();
else
mainWindow.maximize();
break;
}
});
@@ -402,18 +409,16 @@ const spawnServer = async () => {
logger.info({ javaBin, serverJar }, 'Found Java and server jar');
const platform = getPlatform();
const serverWorkdir = getServerDataFolder()
const serverArgs = ['-Xmx128M', '-jar', serverJar]
if (options.steam) serverArgs.push(`--steam`)
if (options.install) serverArgs.push(`--install`)
if (options.noUdev) serverArgs.push(`--no-udev`)
serverArgs.push('run')
const serverArgs = ['-Xmx128M', '-jar', serverJar];
if (options.steam) serverArgs.push('--steam');
if (options.install) serverArgs.push('--install');
if (options.noUdev) serverArgs.push('--no-udev');
serverArgs.push('run');
const serverProcess = spawn(javaBin, serverArgs, {
cwd: serverWorkdir,
cwd: sharedDir,
shell: false,
env:
platform === 'windows'
@@ -466,11 +471,10 @@ const createFolders = async () => {
let isQuitting = false;
app.whenReady().then(async () => {
// Register protocol handler for app:// scheme to handle assets with leading slashes
protocol.handle('app', (request) => {
const url = request.url.slice('app://'.length);
const filePath = path.normalize(join(__dirname, '../renderer', url));
return net.fetch('file://' + filePath);
const { pathname } = new URL(request.url);
const filePath = path.normalize(join(__dirname, '../renderer', pathname));
return net.fetch(pathToFileURL(filePath).toString(), { headers: request.headers });
});
+4 -2
View File
@@ -22,9 +22,10 @@ export const richPresence = () => {
state,
connect: async () => {
try {
logger.info('Logging into Discord RPC');
await client.login();
} catch (e) {
logger.error(e, 'unable to connect to discord rpc');
logger.error(e, 'Unable to connect to Discord RPC');
}
},
updateActivity: (content: string) => {
@@ -36,10 +37,11 @@ export const richPresence = () => {
startTimestamp: state.start,
})
.catch((e) => {
logger.error(e, 'unable to update rpc activity');
logger.error(e, 'Failed to update Discord RPC activity');
});
},
destroy: () => {
logger.info('Destroying Discord RPC');
client.destroy();
Object.assign(state, initialState());
},
+2 -2
View File
@@ -14,7 +14,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
close: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'close'),
hide: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'hide'),
minimize: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'minimize'),
maximize: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'maximize'),
toggleMaximize: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'toggle-maximize'),
getStorage: async (type) => {
return {
get: (key) =>
@@ -37,5 +37,5 @@ contextBridge.exposeInMainWorld('electronAPI', {
openFile: (path) => ipcRenderer.invoke(IPC_CHANNELS.OPEN_FILE, path),
ghGet: (req) => ipcRenderer.invoke(IPC_CHANNELS.GH_FETCH, req),
setPresence: (options) => ipcRenderer.invoke(IPC_CHANNELS.DISCORD_PRESENCE, options),
getInstallDir: () => ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'exe')
getInstallDir: () => ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'exe'),
} satisfies IElectronAPI);
+1 -1
View File
@@ -45,7 +45,7 @@ export interface IElectronAPI {
close: () => void;
hide: () => void;
minimize: () => void;
maximize: () => void;
toggleMaximize: () => void;
showDecorations: (decorations: boolean) => void;
setTranslations: (translations: Record<string, string>) => void;
i18nOverride: () => Promise<string | false>;
+3 -1
View File
@@ -25,7 +25,9 @@ export const IPC_CHANNELS = {
export interface IpcInvokeMap {
[IPC_CHANNELS.OPEN_URL]: (url: string) => void;
[IPC_CHANNELS.OS_STATS]: () => Promise<OSStats>;
[IPC_CHANNELS.WINDOW_ACTIONS]: (action: 'close' | 'minimize' | 'maximize' | 'hide') => void;
[IPC_CHANNELS.WINDOW_ACTIONS]: (
action: 'close' | 'minimize' | 'toggle-maximize' | 'hide'
) => void;
[IPC_CHANNELS.LOG]: (type: 'info' | 'error' | 'warn', ...args: unknown[]) => void;
[IPC_CHANNELS.OPEN_DIALOG]: (
options: OpenDialogOptions
+1 -1
View File
@@ -68,7 +68,7 @@
"dmg-license": "^1.0.11",
"dotenv": "^16.4.5",
"electron": "^40.3.0",
"electron-builder": "^26.7.0",
"electron-builder": "^26.9.0",
"electron-vite": "^5.0.0",
"@eslint/eslintrc": "^3.3.5",
"@eslint/js": "^9.39.4",
+6 -1
View File
@@ -811,9 +811,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = تخطى الإعداد
onboarding-setup_warning-cancel = متابعة الإعداد
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = العودة إلى المقدمة
onboarding-wifi_creds-skip = تخطى إعدادات واي فاي
onboarding-wifi_creds-submit = إرسال!
onboarding-wifi_creds-ssid =
@@ -849,6 +851,9 @@ onboarding-reset_tutorial-2 =
يجب أن تكون في وضع تزلج كما هو موضح في معالج "التثبيت التلقائي" ولديك تأخير لمدة 3 ثوانٍ (قابل للتكوين) قبل أن يتم تشغيله.
## Install info
## Setup start
onboarding-home = مرحبا بكم في سلايم في ار
+6 -1
View File
@@ -836,9 +836,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Přeskočit nastavení
onboarding-setup_warning-cancel = Pokračovat v nastavení
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Zpět na úvod
onboarding-wifi_creds-v2 = Trackey používající Wi-Fi
onboarding-wifi_creds-skip = Přeskočit nastavení Wi-Fi
onboarding-wifi_creds-submit = Odeslat!
@@ -870,6 +872,9 @@ onboarding-reset_tutorial-1 =
Pro tuto funkci musíte stát v základní pozici (ruce podél těla). Před provedením resetu je zde 3 sekundová prodleva (lze nastavit).
Tímto se kompletně resetuje pozice a rotace všech vašich trackerů, což by mělo vyřešit většinu problémů.
## Install info
## Setup start
onboarding-home = Vítejte ve SlimeVR
+6 -1
View File
@@ -480,9 +480,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Spring opsætning over
onboarding-setup_warning-cancel = Fortsæt konfigurationen
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Gå tilbage til introduktion
onboarding-wifi_creds-skip = Spring Wi-Fi-indstillinger over
onboarding-wifi_creds-submit = Færdig!
onboarding-wifi_creds-ssid =
@@ -497,6 +499,9 @@ onboarding-wifi_creds-password =
onboarding-reset_tutorial-back = Gå tilbage til monteringskalibrering
onboarding-reset_tutorial = Start forfra
## Install info
## Setup start
onboarding-home = Velkommen til SlimeVR
+6 -1
View File
@@ -884,9 +884,11 @@ onboarding-setup_warning = <b>Warnung:</b> Für gutes Tracking ist die Ersteinri
onboarding-setup_warning-skip = Einrichtung überspringen
onboarding-setup_warning-cancel = Einrichtung fortsetzen
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Zurück zur Einführung
onboarding-wifi_creds-v2 = Tracker mit WLAN
onboarding-wifi_creds-skip = WLAN-Zugangsdaten überspringen
onboarding-wifi_creds-submit = Weiter!
@@ -925,6 +927,9 @@ onboarding-reset_tutorial-2 =
Sie müssen sich in einer "Skifahren"-Pose, wie im Tracker-Ausrichtung-Assistenten gezeigt wird, befinden. Nach dem Auslösen wird der Reset nach 3 Sekunden (konfigurierbar) durchgeführt.
## Install info
## Setup start
onboarding-home = Willkommen zu SlimeVR
+6
View File
@@ -291,12 +291,18 @@ settings-osc-vrchat-network-trackers-feet = Πόδια
## Setup/onboarding menu
## Quiz
## Wi-Fi setup
## Mounting setup
## Install info
## Setup start
+6 -1
View File
@@ -739,9 +739,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = skipy setup
onboarding-setup_warning-cancel = continu setup
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = gaww bawwk to intwoduction
onboarding-wifi_creds-skip = skipy wi-fi settiwyngs
onboarding-wifi_creds-submit = suwbmyt!
onboarding-wifi_creds-ssid =
@@ -777,6 +779,9 @@ onboarding-reset_tutorial-2 =
u need to be on pose wike you awe skiing wike it's shown on da Pawtomatic Meownting wizawd and you have a 3 second deway (configuwabwe) befowe it gets twiggewed.
## Install info
## Setup start
onboarding-home = wewcome to SwimeVR
+6 -1
View File
@@ -904,9 +904,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Omitir configuración
onboarding-setup_warning-cancel = Continuar con la configuración
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Volver a la introducción
onboarding-wifi_creds-skip = Omitir configuración Wi-Fi
onboarding-wifi_creds-submit = ¡Enviar!
onboarding-wifi_creds-ssid =
@@ -942,6 +944,9 @@ onboarding-reset_tutorial-2 =
Necesitas estar en una pose como si estuvieras esquiando como se muestra en el asistente de montaje automático y tienes un retraso de 3 segundos (configurable) antes de que se active.
## Install info
## Setup start
onboarding-home = Bienvenido a SlimeVR
+6 -1
View File
@@ -556,9 +556,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Jäta seadistamine vahele
onboarding-setup_warning-cancel = Jätka seadistamist
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Mine tagasi juhistele
onboarding-wifi_creds-skip = Jätke Wi-Fi seaded vahele.
onboarding-wifi_creds-submit = Jätka!
onboarding-wifi_creds-ssid =
@@ -593,6 +595,9 @@ onboarding-reset_tutorial-2 =
Peate olema poosis, nagu suusatate, nagu see on näidatud automaatse paigaldamise viisardil, ja teil on 3-sekundiline viivitus (konfigureeritav), enne kui see käivitub.
## Install info
## Setup start
onboarding-home = Tere tulemast SlimeVR-i
+6 -1
View File
@@ -589,9 +589,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Ohita asennus
onboarding-setup_warning-cancel = Jatka asennusta
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Palaa esittelyyn
onboarding-wifi_creds-skip = Ohita Wi-Fi-asetukset
onboarding-wifi_creds-submit = Lähetä!
onboarding-wifi_creds-ssid =
@@ -626,6 +628,9 @@ onboarding-reset_tutorial-2 =
Sinun on oltava hiihto-asennossa, kuten on näytettynä Automaattisessa Asennuksessa ja sinulla on 3 sekunnin viive (muokattavissa), ennen kuin se käynnistyy.
## Install info
## Setup start
onboarding-home = Tervetuloa SlimeVR:ään
+6 -1
View File
@@ -971,9 +971,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Passer la configuration
onboarding-setup_warning-cancel = Continuer la configuration
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Retour à l'introduction
onboarding-wifi_creds-v2 = Capteurs utilisant le Wi-Fi
# This cares about multilines
onboarding-wifi_creds-description-v2 =
@@ -1020,6 +1022,9 @@ onboarding-reset_tutorial-2 =
Accroupissez-vous dans une position de « ski » comme affiché sur l'assistant d'alignement des capteurs. Vous aurez un délai de 3 secondes (configurable) avant la réinitialisation.
## Install info
## Setup start
onboarding-home = Bienvenue sur SlimeVR
+6
View File
@@ -291,12 +291,18 @@ settings-osc-vrchat-network-trackers-elbows = מרפקים
## Setup/onboarding menu
## Quiz
## Wi-Fi setup
## Mounting setup
## Install info
## Setup start
+6 -1
View File
@@ -907,9 +907,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Salta la configurazione
onboarding-setup_warning-cancel = Continua la configurazione
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Torna all'introduzione
onboarding-wifi_creds-skip = Salta impostazioni Wi-Fi
onboarding-wifi_creds-submit = Conferma!
onboarding-wifi_creds-ssid =
@@ -945,6 +947,9 @@ onboarding-reset_tutorial-2 =
Devi essere in posa come se stessi sciando come mostrato nella procedura guidata di posizionamento automatico e ha un ritardo di 3 secondi (configurabile) prima che venga attivato.
## Install info
## Setup start
onboarding-home = Benvenuti a SlimeVR
+6 -1
View File
@@ -574,9 +574,11 @@ onboarding-wip = 実行中
onboarding-setup_warning-skip = セットアップをスキップする
onboarding-setup_warning-cancel = セットアップを続行する
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = 戻る
onboarding-wifi_creds-skip = Wi-Fi設定をスキップする
onboarding-wifi_creds-submit = 実行!
onboarding-wifi_creds-ssid =
@@ -592,6 +594,9 @@ onboarding-reset_tutorial-back = マウントキャリブレーションに戻
onboarding-reset_tutorial = リセットチュートリアル
onboarding-reset_tutorial-skip = ステップをスキップする
## Install info
## Setup start
onboarding-home = SlimeVRへようこそ
+6 -1
View File
@@ -740,9 +740,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = 설정 건너뛰기
onboarding-setup_warning-cancel = 설정 계속하기
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = 처음으로 돌아가기
onboarding-wifi_creds-skip = Wi-Fi 설정 건너뛰기
onboarding-wifi_creds-submit = 저장!
onboarding-wifi_creds-ssid =
@@ -778,6 +780,9 @@ onboarding-reset_tutorial-2 =
자동 착용 방향 설정 마법사에서 봤던 것처럼 스키를 타는 듯한 자세로 몸을 구부리고 있으세요. 탭한 다음 3초 뒤에(설정에서 변경 가능) 보정이 시작될 거예요.
## Install info
## Setup start
onboarding-home = SlimeVR에 어서오세요!
+6
View File
@@ -609,12 +609,18 @@ settings-general-gesture_control-trackers =
## Setup/onboarding menu
## Quiz
## Wi-Fi setup
## Mounting setup
## Install info
## Setup start
+6 -1
View File
@@ -494,9 +494,11 @@ onboarding-skip = Hopp over oppsett
onboarding-continue = Fortsett
onboarding-wip = Arbeid pågår
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Gå tilbake til introduksjonen
onboarding-wifi_creds-skip = Hopp over Wi-Fi innstillinger
onboarding-wifi_creds-submit = Send inn!
onboarding-wifi_creds-ssid =
@@ -512,6 +514,9 @@ onboarding-reset_tutorial-back = Gå tilbake til monterings kalibrering
onboarding-reset_tutorial = Nullstill opplæringen
onboarding-reset_tutorial-skip = Hopp over trinn
## Install info
## Setup start
onboarding-home = Velkommen til SlimeVR
+6 -1
View File
@@ -962,9 +962,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Setupgids overslaan
onboarding-setup_warning-cancel = Doorgaan met setupgids
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Ga terug naar de introductie
onboarding-wifi_creds-v2 = Trackers die Wi-Fi gebruiken
# This cares about multilines
onboarding-wifi_creds-description-v2 =
@@ -1011,6 +1013,9 @@ onboarding-reset_tutorial-2 =
Je moet in een houding staan alsof je aan het skiën bent, zoals wordt weergegeven in de Automatische montage wizard, je hebt een vertraging van 3 seconden (instelbaar) voordat deze wordt geactiveerd.
## Install info
## Setup start
onboarding-home = Welkom bij SlimeVR
+6 -1
View File
@@ -960,9 +960,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Pomiń konfigurację
onboarding-setup_warning-cancel = Kontynuuj konfigurację
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Cofnij się do początku
onboarding-wifi_creds-skip = Pomiń ustawienia Wi-Fi
onboarding-wifi_creds-submit = Potwierdź!
onboarding-wifi_creds-ssid =
@@ -998,6 +1000,9 @@ onboarding-reset_tutorial-2 =
Musisz być w pozie, jakbyś jechał na nartach, tak jak jest to pokazane w kreatorze automatycznego montażu, i masz 3-sekundowe opóźnienie (konfigurowalne), zanim zostanie uruchomione.
## Install info
## Setup start
onboarding-home = Witamy w SlimeVR
+52 -1
View File
@@ -654,6 +654,8 @@ settings-general-fk_settings-enforce_joint_constraints-correct_constraints-descr
settings-general-fk_settings-ik = Dados de posição
settings-general-fk_settings-ik-use_position = Usar dados de posição
settings-general-fk_settings-ik-use_position-description = Ativa o uso de dados de posição dos trackers que os fornecem. Ao ativar isso, certifique-se de executar "Redefinir Tudo" e recalibrar no jogo.
settings-general-fk_settings-velocity_settings = Configurações de Velocidade
settings-general-fk_settings-velocity_settings-description = Envia dados de velocidade derivados para o SteamVR. Necessário para suporte ao Natural Locomotion. Pode causar instabilidade no FBT.
settings-general-fk_settings-arm_fk = Rastreamento dos braços
settings-general-fk_settings-arm_fk-description = Forçar o rastreamento dos braços a partir do headset (HMD), mesmo que dados posicionais das mãos estejam disponíveis.
settings-general-fk_settings-arm_fk-force_arms = Forçar braços do HMD
@@ -970,9 +972,47 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Pular configurações
onboarding-setup_warning-cancel = Continuar configurações
## Quiz
onboarding-quiz_continue = Continuar
onboarding-quiz_back = Voltar
onboarding-quiz-more_sets_modal-title = Você conectou todos os seus trackers?
onboarding-quiz-more_sets_modal-desc = Se você tiver conjuntos de modelos diferentes, podemos conectá-los agora mesmo!
onboarding-quiz-more_sets_modal-confirm = Eu conectei todos os meus trackers
onboarding-quiz-more_sets_modal-cancel = Quero conectar mais trackers
onboarding-quiz-slimeset-title = Que tipo de trackers você está conectando?
onboarding-quiz-slimeset-description = Se você tiver vários conjuntos, você será solicitado novamente mais tarde no processo
onboarding-quiz-slimeset-official-sets = Trackers Oficiais do SlimeVR
onboarding-quiz-slimeset-thirdparty-sets = Trackers de Terceiros ou Feitos por Você.
onboarding-quiz-slimeset-answer-regular = SlimeVR V1.0 e V1.2
onboarding-quiz-slimeset-answer-butterfly = Butterfly
onboarding-quiz-slimeset-answer-wifi = Slime baseado em Wi-Fi
onboarding-quiz-slimeset-answer-dongle = Slime baseado em Dongle
onboarding-quiz-usage-title = Para que você está usando seus trackers?
onboarding-quiz-usage-description = Se você pretende usar o SlimeVR para múltiplas finalidades, você pode alterar as configurações afetadas mais tarde.
onboarding-quiz-usage-answer-VRC = Jogos em VR (ex.: VRChat)
onboarding-quiz-usage-answer-mocap_vtubing = Mocap e VTubing
onboarding-quiz-runtime-title = Você executa jogos via SteamVR ou diretamente no headset (standalone)?
onboarding-quiz-runtime-answer-steamvr = SteamVR
onboarding-quiz-runtime-answer-standalone = Standalone
onboarding-quiz-mocap_preferences-title = Preferências de Mocap
onboarding-quiz-mocap_preferences-desc = Especifique como você pretende usar o SlimeVR para mocap ou VTubing
onboarding-quiz-mocap_preferences-playspace-title = Qual é o seu espaço de jogo?
onboarding-quiz-mocap_preferences-playspace-desc = Se estiver em pé, o SlimeVR tentará rastrear o movimento de caminhada em vez de manter você ancorado em um único lugar.
onboarding-quiz-mocap_preferences-playspace-sitting = Sentado
onboarding-quiz-mocap_preferences-playspace-standing = Em Pé
onboarding-quiz-mocap_preferences-vrm_model-title = Você tem um modelo VRM? (Opcional)
onboarding-quiz-mocap_preferences-vrm_model-desc = Carregar um modelo VRM melhorará a qualidade do rastreamento e a compatibilidade com aplicativos que usam VMC.
onboarding-quiz-mocap_preferences-head_tracker-title = Você está usando um tracker ou um headset VR na cabeça?
onboarding-quiz-mocap_preferences-head_tracker-yes = Sim
onboarding-quiz-mocap_preferences-head_tracker-no = Não
onboarding-quiz-mocap_preferences-head_tracker_location-title = Onde está localizado o seu rastreador de cabeça?
onboarding-quiz-mocap_preferences-head_tracker_location-forehead = Testa
onboarding-quiz-mocap_preferences-head_tracker_location-face = Rosto
## Wi-Fi setup
onboarding-wifi_creds-back = Voltar para introdução
onboarding-wifi_creds-back-v2 = Voltar
onboarding-wifi_creds-v2 = Trackers conectados via Wi-Fi
# This cares about multilines
onboarding-wifi_creds-description-v2 =
@@ -1018,6 +1058,13 @@ onboarding-reset_tutorial-2 =
Você precisa estar em uma pose como se estivesse esquiando, conforme mostrado no assistente de montagem automática, e há um atraso de 3 segundos (configurável) antes que ela seja acionada.
## Install info
install-info_udev-rules_modal_title = Regras de acesso udev de hardware não encontradas
install-info_udev-rules_warning = Regras de acesso via udev são necessárias para acesso ao console serial e conexão do dongle. Cole o seguinte comando no seu terminal para adicionar as regras do udev.
install-info_udev-rules_modal_button = Fechar
install-info_udev-rules_modal-dont-show-again_checkbox = Não mostrar novamente
## Setup start
onboarding-home = Bem-vindo ao SlimeVR
@@ -1360,6 +1407,7 @@ onboarding-user_height-description = Precisamos da sua altura para calcular as p
onboarding-user_height-need_head_tracker = É necessário um headset e controles com rastreamento posicional para realizar a calibração.
onboarding-user_height-calculate = Calcular minha altura automaticamente
onboarding-user_height-next_step = Continuar e salvar
onboarding-user_height-prev_step = Voltar
onboarding-user_height-manual-proportions = Proporções Manuais
onboarding-user_height-calibration-title = Progresso da Calibração
onboarding-user_height-calibration-RECORDING_FLOOR = Toque o chão com a ponta do seu controle
@@ -1515,6 +1563,7 @@ firmware_tool-flashing_step-description = Seus trackers estão atualizando, por
firmware_tool-flashing_step-warning-v2 = Não desconecte nem desligue o tracker durante o processo de envio, a menos que seja instruído a fazê-lo, pois isso pode tornar sua placa inutilizável
firmware_tool-flashing_step-flash_more = Atualizar mais trackers
firmware_tool-flashing_step-exit = Sair
firmware_tool-flashing_step-onboarding_continue = Continuar
## firmware tool build status
@@ -1655,6 +1704,8 @@ tracking_checklist-FULL_RESET-desc = Alguns trackers precisam que uma redefiniç
tracking_checklist-STEAMVR_DISCONNECTED = O SteamVR não está em execução
tracking_checklist-STEAMVR_DISCONNECTED-desc = O SteamVR não está em execução. Você está usando ele para VR?
tracking_checklist-STEAMVR_DISCONNECTED-open = Iniciar o SteamVR
tracking_checklist-STEAMVR_HANDS_ENABLED-desc = Você ativou os Trackers de mãos virtuais do SteamVR. Isso fará com que os comandos feitos por meio de botões não funcionem no SteamVR e nos jogos.
tracking_checklist-STEAMVR_HANDS_ENABLED-go = Desabilitá-los
tracking_checklist-TRACKERS_REST_CALIBRATION = Calibre seus trackers
tracking_checklist-TRACKERS_REST_CALIBRATION-desc = Você não realizou a calibração dos trackers. Por favor, deixe os trackers (destacados em amarelo) repousarem sobre uma superfície estável por alguns segundos.
tracking_checklist-TRACKER_ERROR = Trackers com Erros
+6 -1
View File
@@ -917,9 +917,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Пропустить настройку
onboarding-setup_warning-cancel = Продолжить настройку
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Вернуться к введению
onboarding-wifi_creds-skip = Пропустить настройки Wi-Fi
onboarding-wifi_creds-submit = Отправить!
onboarding-wifi_creds-ssid =
@@ -955,6 +957,9 @@ onboarding-reset_tutorial-2 =
Вы должны быть в позе, как будто вы катаетесь на лыжах, как показано в мастере автоматического монтажа крепления, и у вас есть 3-секундная задержка (настраиваемая) перед тем, как она сработает.
## Install info
## Setup start
onboarding-home = Добро пожаловать в SlimeVR
+6 -1
View File
@@ -839,9 +839,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Hoppa över inställning
onboarding-setup_warning-cancel = Fortsätt inställning
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Gå tillbaka till introduktion
onboarding-wifi_creds-skip = Hoppa över Wi-Fi inställningar.
onboarding-wifi_creds-submit = Överlämna!
onboarding-wifi_creds-ssid =
@@ -864,6 +866,9 @@ onboarding-reset_tutorial-0 =
Detta gör att spårarna vänds i samma riktning som ditt headset (HMD).
## Install info
## Setup start
onboarding-home = Välkommen till SlimeVR
+6 -1
View File
@@ -954,9 +954,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = ข้ามการตั้งค่า
onboarding-setup_warning-cancel = ดำเนินการตั้งค่าต่อ
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = กลับไปที่หน้าบทนำ
onboarding-wifi_creds-v2 = แทร็กเกอร์ที่ใช้ Wi-Fi
# This cares about multilines
onboarding-wifi_creds-description-v2 =
@@ -1001,6 +1003,9 @@ onboarding-reset_tutorial-2 =
คุณต้องอยู่ในท่าเล่นสกีตามที่แสดงในตัวช่วยตั้งค่า โดยจะนับถอยหลังใน 3 วินาที (สามารถกำหนดได้) ก่อนที่การรีเซ็ตจะเกิดขึ้น
## Install info
## Setup start
onboarding-home = ยินดีต้อนรับสู่ SlimeVR!
+160 -21
View File
@@ -7,68 +7,194 @@
## Websocket (server) status
websocket-connecting = Sunucuya bağlanılıyor
websocket-connecting = Sunucuya bağlanılıyor...
websocket-connection_lost = Sunucuyla bağlantı kesildi. Tekrar bağlanılmaya çalışılıyor...
websocket-connection_lost-desc = SlimeVR sunucusu çöktü. Kayıtları kontrol edip programı yeniden başlat.
websocket-timedout = Sunucuya bağlanılamadı
websocket-timedout-desc = SlimeVR sunucusu çöktü veya zaman aşımına uğradı. Kayıtları kontrol et ve programı yeniden başlat.
websocket-error-close = SlimeVR'ı kapat
websocket-error-logs = Kayıtlar klasörünü aç
## Update notification
version_update-title = Yeni sürüm mevcut: { $version }
version_update-description = "{ version_update-update }" seçeneğine tıklamak SlimeVR kurulum uygulamasını indirir.
version_update-update = Güncelle
version_update-close = Kapat
## Tips
tips-find_tracker = Hangi takipçi hangisi emin değil misin? Takipçilerden birini hareket ettirerek belirleyebilirsin.
tips-do_not_move_heels = Kayıt sırasında ayaklarınızın hareket etmediğinden emin olun!
tips-do_not_move_heels = Kayıt sırasında ayaklarının hareket etmediğinden emin ol!
tips-file_select = Dosyaları sürükleyip bırak veya dosyalarından <u>seç</u>.
tips-tap_setup = Menüden seçmek yerine takipçine 2 kez yavaşça dokunarak da seçebilirsin.
tips-turn_on_tracker = Resmi SlimeVR takipçisi mi kullanıyorsun? Takipçilerini bilgisayara bağladıktan sonra onları <b><em>açmayı</em></b> unutma!
tips-failed_webgl = WebGL başlatılamadı.
## Units
unit-meter = Metre
unit-foot = Ayak
unit-inch = Inç
unit-cm = cm
## Body parts
body_part-NONE = Atanmamış
body_part-HEAD = Kafa
body_part-NECK = Boyun
body_part-RIGHT_SHOULDER = Sağ omuz
body_part-RIGHT_UPPER_ARM = Sağ üst kol
body_part-RIGHT_LOWER_ARM = Sağ alt kol
body_part-RIGHT_HAND = Sağ el
body_part-RIGHT_UPPER_LEG = Sağ uyluk
body_part-RIGHT_LOWER_LEG = Sağ ayak bileği
body_part-RIGHT_FOOT = Sağ ayak
body_part-UPPER_CHEST = Üst göğüs
body_part-RIGHT_SHOULDER = Sağ Omuz
body_part-RIGHT_UPPER_ARM = Sağ Üst Kol
body_part-RIGHT_LOWER_ARM = Sağ Alt Kol
body_part-RIGHT_HAND = Sağ El
body_part-RIGHT_UPPER_LEG = Sağ Uyluk
body_part-RIGHT_LOWER_LEG = Sağ Ayak Bileği
body_part-RIGHT_FOOT = Sağ Ayak
body_part-UPPER_CHEST = Üst Göğüs
body_part-CHEST = Göğüs
body_part-WAIST = Bel
body_part-HIP = Kalça
body_part-LEFT_SHOULDER = Sol omuz
body_part-LEFT_UPPER_ARM = Sol üst kol
body_part-LEFT_LOWER_ARM = Sol alt kol
body_part-LEFT_HAND = Sol el
body_part-LEFT_UPPER_LEG = Sol uyluk
body_part-LEFT_LOWER_LEG = Sol ayak bileği
body_part-LEFT_FOOT = Sol ayak
body_part-LEFT_SHOULDER = Sol Omuz
body_part-LEFT_UPPER_ARM = Sol Üst Kol
body_part-LEFT_LOWER_ARM = Sol Alt Kol
body_part-LEFT_HAND = Sol El
body_part-LEFT_UPPER_LEG = Sol Uyluk
body_part-LEFT_LOWER_LEG = Sol Ayak Bileği
body_part-LEFT_FOOT = Sol Ayak
body_part-LEFT_THUMB_METACARPAL = Sol başparmak metakarpal kemiği
body_part-LEFT_THUMB_PROXIMAL = Sol başparmak proksimal kemiği
body_part-LEFT_THUMB_DISTAL = Sol başparmak distal falanks kemiği
body_part-LEFT_INDEX_PROXIMAL = Sol işaret parmağının proksimal falanks kemiği
body_part-LEFT_INDEX_INTERMEDIATE = Sol işaret parmağının orta falanks kemiği
body_part-LEFT_INDEX_DISTAL = Sol işaret parmağının distal falanks kemiği
body_part-LEFT_MIDDLE_PROXIMAL = Sol orta parmağın proksimal falanks kemiği
body_part-LEFT_MIDDLE_INTERMEDIATE = Sol orta parmağın orta falanks kemiği
body_part-LEFT_MIDDLE_DISTAL = Sol orta parmağın distal falanks kemiği
body_part-LEFT_RING_PROXIMAL = Sol yüzük parmağının proksimal falanks kemiği
body_part-LEFT_RING_INTERMEDIATE = Sol yüzük parmağının orta falanks kemiği
body_part-LEFT_RING_DISTAL = Sol yüzük parmağının distal falanks kemiği
body_part-LEFT_LITTLE_PROXIMAL = Sol küçük parmağın proksimal falanks kemiği
body_part-LEFT_LITTLE_INTERMEDIATE = Sol küçük parmağın orta falanks kemiği
body_part-LEFT_LITTLE_DISTAL = Sol küçük parmağın distal falanks kemiği
body_part-RIGHT_THUMB_METACARPAL = Sağ başparmak metakarpal kemiği
body_part-RIGHT_THUMB_PROXIMAL = Sağ başparmağın proksimal falanks kemiği
body_part-RIGHT_THUMB_DISTAL = Sağ başparmağın distal falanks kemiği
body_part-RIGHT_INDEX_PROXIMAL = Sağ işaret parmağının proksimal falanks kemiği
body_part-RIGHT_INDEX_INTERMEDIATE = Sağ işaret parmağının orta falanks kemiği
body_part-RIGHT_INDEX_DISTAL = Sağ işaret parmağının distal falanks kemiği
body_part-RIGHT_MIDDLE_PROXIMAL = Sağ orta parmağın proksimal falanks kemiği
body_part-RIGHT_MIDDLE_INTERMEDIATE = Sağ orta parmağın orta falanks kemiği
body_part-RIGHT_MIDDLE_DISTAL = Sağ orta parmağın distal falanks kemiği
body_part-RIGHT_RING_PROXIMAL = Sağ yüzük parmağının proksimal falanks kemiği
body_part-RIGHT_RING_INTERMEDIATE = Sağ yüzük parmağının orta falanks kemiği
body_part-RIGHT_RING_DISTAL = Sağ yüzük parmağının distal falanks kemiği
body_part-RIGHT_LITTLE_PROXIMAL = Sağ küçük parmağın proksimal falanks kemiği
body_part-RIGHT_LITTLE_INTERMEDIATE = Sağ küçük parmağın orta falanks kemiği
body_part-RIGHT_LITTLE_DISTAL = Sağ küçük parmağın distal falanks kemiği
## BoardType
board_type-UNKNOWN = Bilinmeyen
board_type-NODEMCU = NodeMCU
board_type-WROOM32 = WROOM32
board_type-WEMOSD1MINI = Wemos D1 Mini
board_type-TTGO_TBASE = TTGO T-Base
board_type-ESP01 = ESP-01
board_type-SLIMEVR = SlimeVR
board_type-SLIMEVR_DEV = SlimeVR Dev Board
board_type-SLIMEVR_V1_2 = SlimeVR v1.2
board_type-LOLIN_C3_MINI = Lolin C3 Mini
board_type-BEETLE32C3 = Beetle ESP32-C3
board_type-ESP32C3DEVKITM1 = Espressif ESP32-C3 DevKitM-1
board_type-OWOTRACK = owoTrack
board_type-WRANGLER = Wrangler Joycons
board_type-MOCOPI = Sony Mocopi
board_type-WEMOSWROOM02 = Wemos Wroom-02 D1 Mini
board_type-XIAO_ESP32C3 = Seeed Studio XIAO ESP32C3
board_type-HARITORA = Haritora
board_type-ESP32C6DEVKITC1 = Espressif ESP32-C6 DevKitC-1
board_type-GLOVE_IMU_SLIMEVR_DEV = SlimeVR Dev IMU Eldiveni
board_type-GESTURES = Hareketler
board_type-ESP32S3_SUPERMINI = ESP32-S3 Supermini
board_type-GENERIC_NRF = Jenerik nRF
board_type-SLIMEVR_BUTTERFLY_DEV = SlimeVR Dev Butterfly
board_type-SLIMEVR_BUTTERFLY = SlimeVR Butterfly
## Proportions
skeleton_bone-NONE = Yok
skeleton_bone-HEAD = Kafa hizası
skeleton_bone-HEAD = Kafa Hizası
skeleton_bone-HEAD-desc =
Bu, kulaklığın ile başının ortası arasındaki mesafedir.
Ayarlamak için, 'hayır' der gibi başını soldan sağa ve sağdan sola salla,
diğer takipçiler yerinden oynamayana kadar bunu tekrarlayıp ayarla.
skeleton_bone-NECK = Boyun Uzunluğu
skeleton_bone-torso_group = Gövde uzunluğu
skeleton_bone-NECK-desc =
Bu, başının ortasından boynunun başlangıcına kadar olan mesafedir.
Ayarlamak için başını 'evet' der gibi yukarı-aşağı hareket ettir veya başını hafifçe öne eğip, başını sola ve sağa kaydır,
diğer takipçiler yerinden oynamayana kadar bunu tekrarlayıp ayarla.
skeleton_bone-torso_group = Gövde Uzunluğu
skeleton_bone-torso_group-desc =
Bu, boynunun başlangıcından kalçalarına kadar olan mesafedir.
Ayarlamak için dik dur ve sanal kalçaların, gerçek kalçalarınla hizalanana kadar değeri değiştir.
skeleton_bone-UPPER_CHEST = Üst Göğüs Uzunluğu
skeleton_bone-CHEST_OFFSET = Göğüs hizası
skeleton_bone-UPPER_CHEST-desc =
Bu, boynunun başlangıcından göğsünün ortasına kadar olan mesafedir.
Gövde uzunluğunu doğru şekilde ayarlayıp (otururken, eğilirken, uzanırken vb. duruşlarda) sanal omurgan,
gerçek omurganla eşleşene kadar bu değeri değiştir.
skeleton_bone-CHEST_OFFSET = Göğüs Hizası
skeleton_bone-CHEST_OFFSET-desc =
Bu, bazı oyun veya uygulamalarda kalibrasyona yardımcı olmak için,
sanal göğüs takipçisini yukarı ya da aşağı hareket ettirmene izin verir.
skeleton_bone-CHEST = Göğüs Uzunluğu
skeleton_bone-CHEST-desc =
Bu, göğsünün ortasından omurganın ortasına kadar olan mesafedir.
Gövde uzunluğunu doğru şekilde ayarlayıp (otururken, eğilirken, uzanırken vb. duruşlarda) sanal omurgan,
gerçek omurganla eşleşene kadar bu değeri değiştir.
skeleton_bone-WAIST = Bel Uzunluğu
skeleton_bone-WAIST-desc =
Bu, omurganın ortasından göbek deliğine kadar olan mesafedir.
Gövde uzunluğunu doğru şekilde ayarlayıp (otururken, eğilirken, uzanırken vb. duruşlarda) sanal omurgan,
gerçek omurganla eşleşene kadar bu değeri değiştir.
skeleton_bone-HIP = Kalça Uzunluğu
skeleton_bone-HIP_OFFSET = Kalça hizası
skeleton_bone-HIP-desc =
Bu, göbek deliğinden kalçalarına kadar olan mesafedir.
Gövde uzunluğunu doğru şekilde ayarlayıp (otururken, eğilirken, uzanırken vb. duruşlarda) sanal omurgan,
gerçek omurganla eşleşene kadar bu değeri değiştir.
skeleton_bone-HIP_OFFSET = Kalça Hizası
skeleton_bone-HIP_OFFSET-desc =
Bu, bazı oyun veya uygulamalarda kalibrasyona yardımcı olmak için,
sanal kalça takipçisini yukarı ya da aşağı hareket ettirmene izin verir.
skeleton_bone-HIPS_WIDTH = Kalça Genişliği
skeleton_bone-HIPS_WIDTH-desc =
Bu, bacaklarının başladığı noktalar arasındaki mesafedir.
Ayarlamak için bacaklarını düz tutarak tam bir sıfırlama yap ve,
sanal bacaklarının aralığı, gerçek bacaklarının aralığıyla hizalanana kadar bu değeri değiştir.
skeleton_bone-leg_group = Bacak uzunluğu
skeleton_bone-leg_group-desc =
Bu, kalçandan ayaklarına olan mesafedir.
Ayarlamak için Gövde uzunluğunu doğru şekilde ayarla ve,
sanal ayakların gerçek ayaklarınla aynı seviyeye gelene kadar bu değeri değiştir.
skeleton_bone-UPPER_LEG = Üst Bacak Uzunluğu
skeleton_bone-UPPER_LEG-desc =
Bu, kalçandan dizlerine olan mesafedir.
Ayarlamak için Bacak uzunluğunu doğru şekilde ayarla ve,
sanal dizlerin gerçek dizlerinle aynı seviyeye gelene kadar bu değeri değiştir.
skeleton_bone-LOWER_LEG = Alt Bacak Uzunluğu
skeleton_bone-LOWER_LEG-desc =
Bu, dizlerinden ayak bileklerine olan mesafedir.
Ayarlamak için Bacak uzunluğunu doğru şekilde ayarla ve,
sanal dizlerin gerçek dizlerinle aynı seviyeye gelene kadar bu değeri değiştir.
skeleton_bone-FOOT_LENGTH = Ayak Uzunluğu
skeleton_bone-FOOT_LENGTH-desc =
Bu, ayak bileklerinden ayak parmaklarına olan mesafedir.
Ayarlamak için parmak uçlarına çık ve sanal ayakların sabit kalana kadar bu değeri değiştir.
skeleton_bone-FOOT_SHIFT = Ayak hizası
skeleton_bone-FOOT_SHIFT-desc =
Bu değer, dizinden ayak bileğine olan yatay mesafedir.
Bu, dik dururken alt bacaklarının geriye doğru konumlanmasını telafi eder.
Ayarlamak için Ayak uzunluğunu 0 olarak ayarla, tam sıfırlama yap ve,
sanal ayakların ayak bileklerinin ortasıyla hizalanana kadar bu değeri değiştir.
skeleton_bone-SKELETON_OFFSET = İskelet hizası
skeleton_bone-SHOULDERS_DISTANCE = Omuz Mesafesi
skeleton_bone-SHOULDERS_WIDTH = Omuz Genişliği
@@ -80,7 +206,10 @@ skeleton_bone-ELBOW_OFFSET = Dirsek hizası
## Tracker reset buttons
reset-reset_all = Tüm oranları sıfırla
reset-reset_all_warning-cancel = İptal et
reset-full = Sıfırlama
reset-mounting-feet = Ayak Kalibrasyonu
reset-mounting-fingers = Parmak Kalibrasyonu
## Serial detection stuff
@@ -128,10 +257,13 @@ widget-developer_mode-more_info = Daha fazla bilgi
## Widget: IMU Visualizer
widget-imu_visualizer = Rotasyon
widget-imu_visualizer-preview = Önizle
widget-imu_visualizer-hide = Gizle
widget-imu_visualizer-rotation_preview = Önizle
## Widget: Skeleton Visualizer
widget-skeleton_visualizer-hide = Gizle
## Tracker status
@@ -140,6 +272,7 @@ tracker-status-busy = Meşgul
tracker-status-error = Hata
tracker-status-disconnected = Bağlantı kesildi
tracker-status-ok = İYİ
tracker-status-timed_out = Zaman aşımı
## Tracker status columns
@@ -293,12 +426,18 @@ settings-osc-vrchat-network-address = Ağ adresi
## Setup/onboarding menu
## Quiz
## Wi-Fi setup
## Mounting setup
## Install info
## Setup start
+6 -1
View File
@@ -612,9 +612,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Пропустити налаштування
onboarding-setup_warning-cancel = Продовжити налаштування
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Повернутися до вступу
onboarding-wifi_creds-skip = Пропустити налаштування Wi-Fi
onboarding-wifi_creds-submit = Підтвердити!
onboarding-wifi_creds-ssid =
@@ -649,6 +651,9 @@ onboarding-reset_tutorial-2 =
Вам потрібно бути в позі, ніби ви катаєтеся на лижах, як показано на майстрі автоматичної прив'язки положення. У вас є затримка у 3 секунди (можна налаштувати), перш ніж спрацює скидання.
## Install info
## Setup start
onboarding-home = Ласкаво просимо до SlimeVR
+6 -1
View File
@@ -649,9 +649,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Bỏ qua cài đặt
onboarding-setup_warning-cancel = Tiếp tục thiết lập
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = Quay lại giới thiệu
onboarding-wifi_creds-skip = Bỏ qua cài đặt Wi-Fi
onboarding-wifi_creds-submit = Gửi
onboarding-wifi_creds-ssid =
@@ -686,6 +688,9 @@ onboarding-reset_tutorial-2 =
Bạn cần phải ở trên một tư thế như bạn đang trượt tuyết như nó được hiển thị trên trình hướng dẫn gắn tự động và bạn có độ trễ 3 giây (có thể định cấu hình) trước khi nó được kích hoạt.
## Install info
## Setup start
onboarding-home = Chào mừng bạn đến với SlimeVR!
+51 -1
View File
@@ -955,9 +955,47 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = 跳过设置
onboarding-setup_warning-cancel = 继续设置
## Quiz
onboarding-quiz_continue = 继续
onboarding-quiz_back = 返回
onboarding-quiz-more_sets_modal-title = 已经连接好所有的追踪器了吗?
onboarding-quiz-more_sets_modal-desc = 如有不同类型的追踪器,现在可以继续进行连接
onboarding-quiz-more_sets_modal-confirm = 所有的追踪器都连接好了
onboarding-quiz-more_sets_modal-cancel = 还需要连接更多追踪器
onboarding-quiz-slimeset-title = 将要连接什么类型的追踪器?
onboarding-quiz-slimeset-description = 如果有多组不同类型的追踪器,稍后将会继续连接其余类型
onboarding-quiz-slimeset-official-sets = 官方SlimeVR追踪器
onboarding-quiz-slimeset-thirdparty-sets = 第三方或DIY追踪器
onboarding-quiz-slimeset-answer-regular = SlimeVR V1.0 和 V1.2
onboarding-quiz-slimeset-answer-butterfly = Butterfly (蝴蝶)
onboarding-quiz-slimeset-answer-wifi = 通过ESP/WiFi连接的追踪器
onboarding-quiz-slimeset-answer-dongle = 通过USB接收器连接的追踪器
onboarding-quiz-usage-title = 将使用SlimeVR进行何种应用?
onboarding-quiz-usage-description = 如果打算将SlimeVR用至不同用途,可之后在设置中进行修改。
onboarding-quiz-usage-answer-VRC = VR游戏(如VRChat)
onboarding-quiz-usage-answer-mocap_vtubing = 动作捕捉与虚拟偶像直播
onboarding-quiz-runtime-title = 将通过SteamVR运行游戏,还是在直接在头显上运行?
onboarding-quiz-runtime-answer-steamvr = SteamVR
onboarding-quiz-runtime-answer-standalone = 头显独立运行
onboarding-quiz-mocap_preferences-title = 动作捕捉偏好
onboarding-quiz-mocap_preferences-desc = 设置使用SlimeVR进行动作捕捉或虚拟偶像直播的方式
onboarding-quiz-mocap_preferences-playspace-title = 将在怎样的空间内使用?
onboarding-quiz-mocap_preferences-playspace-desc = 如果选择站立使用,SlimeVR会试图追踪你的行走动作,而不是固定在原地。
onboarding-quiz-mocap_preferences-playspace-sitting = 坐下
onboarding-quiz-mocap_preferences-playspace-standing = 站立
onboarding-quiz-mocap_preferences-vrm_model-title = 你有将要使用的VRM模型吗?(可选)
onboarding-quiz-mocap_preferences-vrm_model-desc = 加载VRM模型将提升跟踪质量,并与使用VMC的应用程序兼容。
onboarding-quiz-mocap_preferences-head_tracker-title = 你头上戴着追踪器或VR头显吗?
onboarding-quiz-mocap_preferences-head_tracker-yes = 是
onboarding-quiz-mocap_preferences-head_tracker-no = 否
onboarding-quiz-mocap_preferences-head_tracker_location-title = 你的头部追踪器放在哪里?
onboarding-quiz-mocap_preferences-head_tracker_location-forehead = 额头
onboarding-quiz-mocap_preferences-head_tracker_location-face = 脸
## Wi-Fi setup
onboarding-wifi_creds-back = 返回简介
onboarding-wifi_creds-back-v2 = 返回
onboarding-wifi_creds-v2 = 通过 Wi-Fi 连接
# This cares about multilines
onboarding-wifi_creds-description-v2 =
@@ -1004,6 +1042,13 @@ onboarding-reset_tutorial-2 =
你需要摆出一个像滑雪那样的姿势,就像在运行自动设置佩戴向导时做的那样,在重置实际发生前有 3 秒延迟(可配置)。
## Install info
install-info_udev-rules_modal_title = 未找到硬件udev访问规则
install-info_udev-rules_warning = 通过udev设置访问规则是串口控制台访问和USB接收器连接的必需条件。将以下命令粘贴到终端并执行,以添加udev规则。
install-info_udev-rules_modal_button = 关闭
install-info_udev-rules_modal-dont-show-again_checkbox = 不再显示
## Setup start
onboarding-home = 欢迎来到 SlimeVR
@@ -1331,6 +1376,7 @@ onboarding-user_height-description = 我们需要你的身高来计算躯干比
onboarding-user_height-need_head_tracker = 进行校准需要具备定位功能的头戴显示器与控制器。
onboarding-user_height-calculate = 自动计算我的身高
onboarding-user_height-next_step = 保存并继续
onboarding-user_height-prev_step = 返回
onboarding-user_height-manual-proportions = 手动调整躯干比例
onboarding-user_height-calibration-title = 校准进度
onboarding-user_height-calibration-RECORDING_FLOOR = 用控制器的前端触碰地面
@@ -1480,6 +1526,7 @@ firmware_tool-flashing_step-description = 正在向追踪器烧录固件,请
firmware_tool-flashing_step-warning-v2 = 除非特别指示,在固件传输过程中请勿断开或关闭追踪器,否则可能会导致您的电路板无法使用
firmware_tool-flashing_step-flash_more = 烧录更多的追踪器
firmware_tool-flashing_step-exit = 退出
firmware_tool-flashing_step-onboarding_continue = 继续
## firmware tool build status
@@ -1615,6 +1662,9 @@ tracking_checklist-FULL_RESET-desc = 有些追踪器需要进行重置
tracking_checklist-STEAMVR_DISCONNECTED = SteamVR 未在运行
tracking_checklist-STEAMVR_DISCONNECTED-desc = SteamVR 未在运行。你要将追踪器用于 VR 吗?
tracking_checklist-STEAMVR_DISCONNECTED-open = 启动 SteamVR
tracking_checklist-STEAMVR_HANDS_ENABLED = 手部追踪器已开启
tracking_checklist-STEAMVR_HANDS_ENABLED-desc = 你已经启用了SteamVR的虚拟手部追踪器。这会导致SteamVR和游戏中的按键输入无法使用。
tracking_checklist-STEAMVR_HANDS_ENABLED-go = 关闭它们
tracking_checklist-TRACKERS_REST_CALIBRATION = 校准追踪器
tracking_checklist-TRACKERS_REST_CALIBRATION-desc = 您尚未执行追踪器校准。请将(黄色高亮显示的)追踪器放置在平稳表面上,并静置数秒。
tracking_checklist-TRACKER_ERROR = 追踪器出现错误
+6 -1
View File
@@ -957,9 +957,11 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = 跳過設定
onboarding-setup_warning-cancel = 繼續設定
## Quiz
## Wi-Fi setup
onboarding-wifi_creds-back = 返回簡介
onboarding-wifi_creds-v2 = 透過 Wi-Fi 連接
# This cares about multilines
onboarding-wifi_creds-description-v2 =
@@ -1006,6 +1008,9 @@ onboarding-reset_tutorial-2 =
做此校正時需要進行滑雪姿勢,如自動配戴校正的畫面所示。在觸發 3 秒後(可修改)才會真正進行重置。
## Install info
## Setup start
onboarding-home = 歡迎來到 SlimeVR
+1 -1
View File
@@ -234,7 +234,7 @@ export function TopBar({
</div>
<div
className="flex items-center justify-center hover:bg-background-60 rounded-full w-7 h-7"
onClick={() => electron.api.maximize()}
onClick={() => electron.api.toggleMaximize()}
>
<MaximiseIcon />
</div>
@@ -36,7 +36,7 @@ export function FlashingStep({
const { l10n } = useLocalization();
const { selectedDevices, selectDevices, files, selectedDefault } =
useFirmwareTool();
const { state: onboardingState, state } = useOnboarding();
const { state: onboardingState } = useOnboarding();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [status, setStatus] = useState<{
[key: string]: {
@@ -203,28 +203,15 @@ export function FlashingStep({
onClick={() => goTo('FlashingMethod')}
/>
</Localized>
{state.alonePage && (
<Localized id="firmware_tool-flashing_step-exit">
<Button
variant="primary"
onClick={() => {
clear();
nav('/');
}}
/>
</Localized>
)}
{!state.alonePage && (
<Localized id="firmware_tool-flashing_step-onboarding_continue">
<Button
variant="primary"
onClick={() => {
clear();
nav('/onboarding/trackers-assign');
}}
/>
</Localized>
)}
<Localized id="firmware_tool-flashing_step-exit">
<Button
variant="primary"
onClick={() => {
clear();
nav('/');
}}
/>
</Localized>
</div>
</div>
</div>
+9 -2
View File
@@ -4,13 +4,20 @@ import { Button } from '@/components/commons/Button';
import { SlimeVRIcon } from '@/components/commons/icon/SimevrIcon';
import { LangSelector } from '@/components/commons/LangSelector';
import { Typography } from '@/components/commons/Typography';
import { useNavigate } from 'react-router-dom';
export function HomePage() {
const nav = useNavigate();
const { l10n } = useLocalization();
const { applyProgress } = useOnboarding();
const { applyProgress, onboardingStarted } = useOnboarding();
applyProgress(0.1);
const start = () => {
onboardingStarted();
nav('/onboarding/quiz/slime-set');
};
return (
<>
<div className="flex relative flex-col gap-5 h-full items-center w-full justify-center px-4 overflow-clip">
@@ -19,7 +26,7 @@ export function HomePage() {
<Typography variant="mobile-title">
{l10n.getString('onboarding-home')}
</Typography>
<Button variant="primary" to="/onboarding/quiz/slime-set">
<Button variant="primary" onClick={start}>
{l10n.getString('onboarding-home-start')}
</Button>
</div>
@@ -7,10 +7,18 @@ import { useState } from 'react';
import { SittingIcon } from '@/components/commons/icon/SittingIcon';
import { VMCFileUpload } from '@/components/settings/pages/VMCSettings';
import { QuizButton } from './SlimeSetQuestion';
import { useNavigate } from 'react-router-dom';
export function QuizMocapPosQuestion() {
const { applyProgress, setMocapPos, mocapPos, playspace, setPlayspace } =
useOnboarding();
const nav = useNavigate();
const {
applyProgress,
setMocapPos,
mocapPos,
playspace,
setPlayspace,
onboardingEnded,
} = useOnboarding();
const [headTracker, setHeadTracker] = useState(true);
@@ -18,6 +26,11 @@ export function QuizMocapPosQuestion() {
const canContinue = (!headTracker || mocapPos) && playspace;
const end = () => {
onboardingEnded();
nav('/');
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
@@ -146,7 +159,7 @@ export function QuizMocapPosQuestion() {
variant="primary"
id="onboarding-quiz_continue"
disabled={!canContinue}
to="/"
onClick={end}
/>
</div>
</div>
@@ -7,13 +7,14 @@ import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/commons/Button';
export function QuizRuntimeQuestion() {
const { applyProgress, setVrcOSC, vrcOsc } = useOnboarding();
const { applyProgress, setVrcOSC, vrcOsc, onboardingEnded } = useOnboarding();
const nav = useNavigate();
applyProgress(0.9);
const next = (type: typeof vrcOsc) => {
setVrcOSC(type);
onboardingEnded();
nav('/');
};
@@ -1,5 +1,5 @@
import { Localized, useLocalization } from '@fluent/react';
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { DefaultValues, useForm } from 'react-hook-form';
import {
ChangeSettingsRequestT,
@@ -180,6 +180,13 @@ export function GeneralSettings() {
const { config } = useConfig();
const { currentLocales } = useLocaleConfig();
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',
maximumFractionDigits: 0,
@@ -200,15 +207,11 @@ export function GeneralSettings() {
});
const {
trackers: {
automaticTrackerToggle,
leftHand: steamVrLeftHand,
rightHand: steamVrRightHand,
},
trackers: { automaticTrackerToggle },
} = watch();
const onSubmit = (values: SettingsForm) => {
const settings = new ChangeSettingsRequestT();
const settingsReq = new ChangeSettingsRequestT();
if (values.trackers) {
const trackers = new SteamVRTrackersSettingT();
@@ -226,8 +229,29 @@ export function GeneralSettings() {
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;
settings.steamVrTrackers = trackers;
settingsReq.steamVrTrackers = trackers;
}
const modelSettings = new ModelSettingsT();
@@ -272,7 +296,7 @@ export function GeneralSettings() {
modelSettings.legTweaks = legTweaks;
}
settings.modelSettings = modelSettings;
settingsReq.modelSettings = modelSettings;
const tapDetection = new TapDetectionSettingsT();
tapDetection.fullResetDelay = values.tapDetection.fullResetDelay;
@@ -288,24 +312,24 @@ export function GeneralSettings() {
tapDetection.numberTrackersOverThreshold =
values.tapDetection.numberTrackersOverThreshold;
tapDetection.setupMode = false;
settings.tapDetectionSettings = tapDetection;
settingsReq.tapDetectionSettings = tapDetection;
const filtering = new FilteringSettingsT();
filtering.type = values.filtering.type;
filtering.amount = values.filtering.amount;
settings.filtering = filtering;
settingsReq.filtering = filtering;
settings.stayAligned = serializeStayAlignedSettings(values.stayAligned);
settingsReq.stayAligned = serializeStayAlignedSettings(values.stayAligned);
const hidSettings = new HIDSettingsT();
hidSettings.trackersOverHid = values.hidSettings.trackersOverHID;
settings.hidSettings = hidSettings;
settingsReq.hidSettings = hidSettings;
if (values.resetsSettings) {
settings.resetsSettings = loadResetSettings(values.resetsSettings);
settingsReq.resetsSettings = loadResetSettings(values.resetsSettings);
}
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsReq);
};
useEffect(() => {
@@ -329,10 +353,11 @@ export function GeneralSettings() {
if (settings.steamVrTrackers) {
formData.trackers = settings.steamVrTrackers;
if (
settings.steamVrTrackers.leftHand ||
settings.steamVrTrackers.rightHand
!blockHandsWarning.current &&
(settings.steamVrTrackers.leftHand ||
settings.steamVrTrackers.rightHand)
) {
setHandsWarning(false);
blockHandsWarning.current = true;
}
}
@@ -424,37 +449,25 @@ export function GeneralSettings() {
reset({ ...getValues(), ...formData });
}, [settings]);
// If null, we still haven't shown the hands warning
// if false then initially the hands warning was disabled
const [handsWarning, setHandsWarning] = useState<boolean | null>(null);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
setSettings(settings);
});
useEffect(() => {
if ((steamVrLeftHand || steamVrRightHand) && handsWarning === null) {
setHandsWarning(true);
} else if (
!(steamVrLeftHand || steamVrRightHand) &&
handsWarning === false
) {
setHandsWarning(null);
}
}, [steamVrLeftHand, steamVrRightHand, handsWarning]);
return (
<SettingsPageLayout>
<HandsWarningModal
isOpen={!!handsWarning}
isOpen={!!showHandsWarning}
onClose={() => {
setValue('trackers.leftHand', false);
setValue('trackers.rightHand', false);
setHandsWarning(null);
setShowHandsWarning(null);
}}
accept={() => {
setValue('trackers.leftHand', true);
setValue('trackers.rightHand', true);
setHandsWarning(false);
const [leftHand, rightHand] = showHandsWarning!;
blockHandsWarning.current = true;
setValue('trackers.leftHand', leftHand);
setValue('trackers.rightHand', rightHand);
setShowHandsWarning(null);
}}
/>
<form className="flex flex-col gap-2 w-full">
@@ -408,7 +408,7 @@ async function parseVRMFile(
/* eslint-disable camelcase */
const vrmJson = {
extensions: {
vrmV0: data.extensions.vrmV0,
VRM: data.extensions.VRM,
VRMC_vrm: data.extensions.VRMC_vrm,
},
extensionsUsed: data.extensionsUsed,
+7 -8
View File
@@ -6,26 +6,25 @@ import { useAtomValue } from 'jotai';
import { useElectron } from './electron';
export function useDiscordPresence() {
const electron = useElectron();
if (!electron.isElectron) return;
const { config } = useConfig();
const { l10n } = useLocalization();
const electron = useElectron();
const imuTrackers = useAtomValue(connectedIMUTrackersAtom);
const imuTrackersCount = useMemo(() => imuTrackers.length, [imuTrackers.length]);
useEffect(() => {
if (config?.discordPresence === false) return;
if (config?.discordPresence === false) {
electron.api.setPresence({ enable: false });
return;
}
if (!electron.isElectron) return;
electron.api.setPresence({
enable: true,
activity: l10n.getString('settings-general-interface-discord_presence-message', {
amount: imuTrackersCount,
}),
});
return () => {
if (!electron.isElectron) return;
electron.api.setPresence({ enable: false });
};
}, [config?.discordPresence, imuTrackersCount]);
}
+4 -13
View File
@@ -78,8 +78,7 @@ export function useProvideOnboarding() {
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const { state: locatioState, pathname } = useLocation();
const [previousPath, setPreviousPath] = useState(pathname);
const { state: locatioState } = useLocation();
const [settings, setSettings] = useState<SettingsResponseT>();
useLayoutEffect(() => {
@@ -102,6 +101,7 @@ export function useProvideOnboarding() {
});
const onboardingEnded = () => {
setConfig({ doneOnboarding: true });
if (!settings?.modelSettings || !settings?.vrcOsc) return;
const req = new ChangeSettingsRequestT();
const modelSettings = new ModelSettingsT();
@@ -138,17 +138,6 @@ export function useProvideOnboarding() {
setPlayspace(undefined);
};
useEffect(() => {
setPreviousPath(pathname);
if (!pathname.startsWith('/onboarding') && previousPath.startsWith('/onboarding')) {
onboardingEnded();
}
if (pathname.startsWith('/onboarding') && !previousPath.startsWith('/onboarding')) {
onboardingStarted();
}
}, [pathname]);
return {
state,
slimeSet,
@@ -172,6 +161,8 @@ export function useProvideOnboarding() {
setUsage,
setVrcOSC,
setMocapPos,
onboardingEnded,
onboardingStarted,
};
}
+41 -41
View File
@@ -163,8 +163,8 @@ importers:
specifier: ^40.3.0
version: 40.9.1
electron-builder:
specifier: ^26.7.0
version: 26.8.1(electron-builder-squirrel-windows@26.8.1)
specifier: ^26.9.0
version: 26.9.0(electron-builder-squirrel-windows@26.9.0)
electron-vite:
specifier: ^5.0.0
version: 5.0.0(@swc/[email protected])([email protected](@types/[email protected])([email protected]))
@@ -1798,12 +1798,12 @@ packages:
[email protected]:
resolution: {integrity: sha512-j87o0j6LqPL3QRr8yid6c+Tt5gC7xNfYo6uQIQkorAC6MpeayVMZrEDzKmJJ/Hlv7EnOQpaRm53k6ktDYZyB6w==}
app-builder-lib@26.8.1:
resolution: {integrity: sha512-p0Im/Dx5C4tmz8QEE1Yn4MkuPC8PrnlRneMhWJj7BBXQfNTJUshM/bp3lusdEsDbvvfJZpXWnYesgSLvwtM2Zw==}
app-builder-lib@26.9.0:
resolution: {integrity: sha512-f/1GhVrDfBH7sSzhAwiXa1rpR/7pB7Av5woUjmt+QYE0QyNvrOAiY05rngtR/PK4/1BzS6/zVoYobIwDAsrtBA==}
engines: {node: '>=14.0.0'}
peerDependencies:
dmg-builder: 26.8.1
electron-builder-squirrel-windows: 26.8.1
dmg-builder: 26.9.0
electron-builder-squirrel-windows: 26.9.0
[email protected]:
resolution: {integrity: sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==}
@@ -1975,12 +1975,12 @@ packages:
[email protected]:
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
builder-util-runtime@9.5.1:
resolution: {integrity: sha512-qt41tMfgHTllhResqM5DcnHyDIWNgzHvuY2jDcYP9iaGpkWxTUzV6GQjDeLnlR1/DtdlcsWQbA7sByMpmJFTLQ==}
builder-util-runtime@9.6.0:
resolution: {integrity: sha512-k9V5I18PXLepLZ8jVmPzsH+gVCVZ+9aMVLyCZ0ZLOkT2KSyiBblDCCN8WxDbjOpfLGNHZqqJPBmW0HYeqxlgkQ==}
engines: {node: '>=12.0.0'}
builder-util@26.8.1:
resolution: {integrity: sha512-pm1lTYbGyc90DHgCDO7eo8Rl4EqKLciayNbZqGziqnH9jrlKe8ZANGdityLZU+pJh16dfzjAx2xQq9McuIPEtw==}
builder-util@26.9.0:
resolution: {integrity: sha512-+eocmbdisnyb40B9nAp/KREfYLXvGagxV50KZv/Zh4aflsr1fdY9Qxs6QG1Jtx1vH5d5NQ3hIcemUi4RSlFK/Q==}
[email protected]:
resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==}
@@ -2346,8 +2346,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==}
dmg-builder@26.8.1:
resolution: {integrity: sha512-glMJgnTreo8CFINujtAhCgN96QAqApDMZ8Vl1r8f0QT8QprvC1UCltV4CcWj20YoIyLZx6IUskaJZ0NV8fokcg==}
dmg-builder@26.9.0:
resolution: {integrity: sha512-5uSyg0yY+JRMMGwFjIweaukYkCGcZSZwvH5VPlBHiKkTEP1a1/uV+bs4y+VAxPMgzg67YB4CF1vD4U/2d3chfg==}
[email protected]:
resolution: {integrity: sha512-ZdzmqwKmECOWJpqefloC5OJy1+WZBBse5+MR88z9g9Zn4VY+WYUkAyojmhzJckH5YbbZGcYIuGAkY5/Ys5OM2Q==}
@@ -2386,16 +2386,16 @@ packages:
engines: {node: '>=0.10.0'}
hasBin: true
electron-builder-squirrel-windows@26.8.1:
resolution: {integrity: sha512-o288fIdgPLHA76eDrFADHPoo7VyGkDCYbLV1GzndaMSAVBoZrGvM9m2IehdcVMzdAZJ2eV9bgyissQXHv5tGzA==}
electron-builder-squirrel-windows@26.9.0:
resolution: {integrity: sha512-Jzsxa3Kjv94ZRZDK7pc8bzu5iglwGsDOBMWTqLpWx2sCEvb3TLW9PMWqOjpDwizqkMBp8GjP6rceLzQYLFIVow==}
electron-builder@26.8.1:
resolution: {integrity: sha512-uWhx1r74NGpCagG0ULs/P9Nqv2nsoo+7eo4fLUOB8L8MdWltq9odW/uuLXMFCDGnPafknYLZgjNX0ZIFRzOQAw==}
electron-builder@26.9.0:
resolution: {integrity: sha512-7BEeGz8Xlk7Qvitj70nGAQaq7WQIZ2amsDvsyKSZbxgtL2pM9fm/woZrtn0hoID6Fl7wkn456dK3OmtFNzgiOA==}
engines: {node: '>=14.0.0'}
hasBin: true
electron-publish@26.8.1:
resolution: {integrity: sha512-q+jrSTIh/Cv4eGZa7oVR+grEJo/FoLMYBAnSL5GCtqwUpr1T+VgKB/dn1pnzxIxqD8S/jP1yilT9VrwCqINR4w==}
electron-publish@26.9.0:
resolution: {integrity: sha512-gsy+U7JfDuD1lPOrCXeECDQoUsWjFah3s1Fv3pqKnjdJuKYDDvGdvC74kLHVG6nl5G0uQ7YN0eftCQ4rUmhvVw==}
[email protected]:
resolution: {integrity: sha512-Is+0BBHJ4NrdpAYiperrmp53pLywG/yV/6lIMTAnhxvzj/Cmn5Q/ogSHC6AKe7X+8kPLxxFk0cs5oc/3j/fxIg==}
@@ -6568,7 +6568,7 @@ snapshots:
[email protected]: {}
app-builder-lib@26.8.1(dmg-builder@26.8.1)(electron-builder-squirrel-windows@26.8.1):
app-builder-lib@26.9.0(dmg-builder@26.9.0)(electron-builder-squirrel-windows@26.9.0):
dependencies:
'@develar/schema-utils': 2.6.5
'@electron/asar': 3.4.1
@@ -6581,17 +6581,17 @@ snapshots:
'@malept/flatpak-bundler': 0.4.0
'@types/fs-extra': 9.0.13
async-exit-hook: 2.0.1
builder-util: 26.8.1
builder-util-runtime: 9.5.1
builder-util: 26.9.0
builder-util-runtime: 9.6.0
chromium-pickle-js: 0.2.0
ci-info: 4.3.1
debug: 4.4.3
dmg-builder: 26.8.1(electron-builder-squirrel-windows@26.8.1)
dmg-builder: 26.9.0(electron-builder-squirrel-windows@26.9.0)
dotenv: 16.6.1
dotenv-expand: 11.0.7
ejs: 3.1.10
electron-builder-squirrel-windows: 26.8.1(dmg-builder@26.8.1)
electron-publish: 26.8.1
electron-builder-squirrel-windows: 26.9.0(dmg-builder@26.9.0)
electron-publish: 26.9.0
fs-extra: 10.1.0
hosted-git-info: 4.1.0
isbinaryfile: 5.0.7
@@ -6795,19 +6795,19 @@ snapshots:
base64-js: 1.5.1
ieee754: 1.2.1
builder-util-runtime@9.5.1:
builder-util-runtime@9.6.0:
dependencies:
debug: 4.4.3
sax: 1.6.0
transitivePeerDependencies:
- supports-color
builder-util@26.8.1:
builder-util@26.9.0:
dependencies:
7zip-bin: 5.2.0
'@types/debug': 4.1.13
app-builder-bin: 5.0.0-alpha.12
builder-util-runtime: 9.5.1
builder-util-runtime: 9.6.0
chalk: 4.1.2
cross-spawn: 7.0.6
debug: 4.4.3
@@ -7188,10 +7188,10 @@ snapshots:
[email protected]: {}
dmg-builder@26.8.1(electron-builder-squirrel-windows@26.8.1):
dmg-builder@26.9.0(electron-builder-squirrel-windows@26.9.0):
dependencies:
app-builder-lib: 26.8.1(dmg-builder@26.8.1)(electron-builder-squirrel-windows@26.8.1)
builder-util: 26.8.1
app-builder-lib: 26.9.0(dmg-builder@26.9.0)(electron-builder-squirrel-windows@26.9.0)
builder-util: 26.9.0
fs-extra: 10.1.0
iconv-lite: 0.6.3
js-yaml: 4.1.1
@@ -7238,23 +7238,23 @@ snapshots:
dependencies:
jake: 10.9.4
electron-builder-squirrel-windows@26.8.1(dmg-builder@26.8.1):
electron-builder-squirrel-windows@26.9.0(dmg-builder@26.9.0):
dependencies:
app-builder-lib: 26.8.1(dmg-builder@26.8.1)(electron-builder-squirrel-windows@26.8.1)
builder-util: 26.8.1
app-builder-lib: 26.9.0(dmg-builder@26.9.0)(electron-builder-squirrel-windows@26.9.0)
builder-util: 26.9.0
electron-winstaller: 5.4.0
transitivePeerDependencies:
- dmg-builder
- supports-color
electron-builder@26.8.1(electron-builder-squirrel-windows@26.8.1):
electron-builder@26.9.0(electron-builder-squirrel-windows@26.9.0):
dependencies:
app-builder-lib: 26.8.1(dmg-builder@26.8.1)(electron-builder-squirrel-windows@26.8.1)
builder-util: 26.8.1
builder-util-runtime: 9.5.1
app-builder-lib: 26.9.0(dmg-builder@26.9.0)(electron-builder-squirrel-windows@26.9.0)
builder-util: 26.9.0
builder-util-runtime: 9.6.0
chalk: 4.1.2
ci-info: 4.4.0
dmg-builder: 26.8.1(electron-builder-squirrel-windows@26.8.1)
dmg-builder: 26.9.0(electron-builder-squirrel-windows@26.9.0)
fs-extra: 10.1.0
lazy-val: 1.0.5
simple-update-notifier: 2.0.0
@@ -7263,11 +7263,11 @@ snapshots:
- electron-builder-squirrel-windows
- supports-color
electron-publish@26.8.1:
electron-publish@26.9.0:
dependencies:
'@types/fs-extra': 9.0.13
builder-util: 26.8.1
builder-util-runtime: 9.5.1
builder-util: 26.9.0
builder-util-runtime: 9.6.0
chalk: 4.1.2
form-data: 4.0.5
fs-extra: 10.1.0
@@ -195,19 +195,20 @@ class VRServer @JvmOverloads constructor(
return false
}
// FIXME: Code using this function normally uses this to get the SteamVR driver but
// that's because we first save the SteamVR driver bridge and then the feeder in the array.
// Not really a great thing to have.
@ThreadSafe
fun <E : Bridge?> getVRBridge(bridgeClass: Class<E>): E? {
fun getVRBridge(pred: (Bridge) -> Boolean): Bridge? {
for (bridge in bridges) {
if (bridgeClass.isAssignableFrom(bridge.javaClass)) {
return bridgeClass.cast(bridge)
}
if (pred(bridge)) return bridge
}
return null
}
@ThreadSafe
fun removeVRBridge(bridge: Bridge) {
bridge.stopBridge()
bridges.remove(bridge)
}
fun addOnTick(runnable: Runnable) {
onTick.add(runnable)
}
@@ -305,7 +306,11 @@ class VRServer @JvmOverloads constructor(
queueTask {
humanPoseManager.updateSkeletonModelFromServer()
vrcOSCHandler.setHeadTracker(TrackerUtils.getTrackerForSkeleton(trackers, TrackerPosition.HEAD))
this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically()
val bridge = this.getVRBridge {
it is ISteamVRBridge
} as? ISteamVRBridge
bridge?.updateShareSettingsAutomatically()
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
}
}
@@ -332,7 +337,10 @@ class VRServer @JvmOverloads constructor(
queueTask {
humanPoseManager.setPauseTracking(pauseTracking, sourceName)
// Toggle trackers as they don't toggle when tracking is paused
this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically()
val bridge = this.getVRBridge {
it is ISteamVRBridge
} as? ISteamVRBridge
bridge?.updateShareSettingsAutomatically()
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
}
}
@@ -341,7 +349,10 @@ class VRServer @JvmOverloads constructor(
queueTask {
humanPoseManager.togglePauseTracking(sourceName)
// Toggle trackers as they don't toggle when tracking is paused
this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically()
val bridge = this.getVRBridge {
it is ISteamVRBridge
} as? ISteamVRBridge
bridge?.updateShareSettingsAutomatically()
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
}
}
@@ -41,6 +41,9 @@ interface Bridge {
@VRServerThread
fun startBridge()
@VRServerThread
fun stopBridge()
fun isConnected(): Boolean
}
@@ -163,6 +163,9 @@ fun createTapDetectionSettings(
tapDetectionConfig.mountingResetTaps,
tapDetectionConfig.setupMode,
tapDetectionConfig.numberTrackersOverThreshold,
0,
0,
0,
)
fun createSteamVRSettings(fbb: FlatBufferBuilder, bridge: ISteamVRBridge?): Int {
@@ -372,7 +375,9 @@ fun createArmsResetModeSettings(
)
fun createSettingsResponse(fbb: FlatBufferBuilder, server: VRServer): Int {
val bridge = server.getVRBridge(ISteamVRBridge::class.java)
val bridge = server.getVRBridge {
it is ISteamVRBridge
} as? ISteamVRBridge
return SettingsResponse
.createSettingsResponse(
@@ -32,8 +32,9 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
.message(ChangeSettingsRequest()) as? ChangeSettingsRequest ?: return
if (req.steamVrTrackers() != null) {
val bridge = api.server
.getVRBridge(ISteamVRBridge::class.java)
val bridge = api.server.getVRBridge {
it is ISteamVRBridge
} as? ISteamVRBridge
if (bridge != null) {
bridge.changeShareSettings(TrackerRole.WAIST, req.steamVrTrackers().waist())
@@ -371,8 +372,9 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
companion object {
fun sendSteamVRUpdatedSettings(api: ProtocolAPI, rpcHandler: RPCHandler) {
val fbb = FlatBufferBuilder(32)
val bridge: ISteamVRBridge =
api.server.getVRBridge(ISteamVRBridge::class.java) ?: return
val bridge = api.server.getVRBridge {
it is ISteamVRBridge
} as? ISteamVRBridge ?: return
val settings = SettingsResponse
.createSettingsResponse(
@@ -29,8 +29,8 @@ class HIDCommon {
const val HID_RECEIVER_PID = 0x7690
const val HID_TRACKER_PID = 0x7692
const val GESTURES_INC_VID = 0x4E76
const val GESTURES_INC_PID_D2XX = 0xD200
const val GESTURES_INC_PID_D2XX_MASK = 0xFF00
const val GESTURES_INC_PID_D2DX = 0xD2D0
const val GESTURES_INC_PID_D2DX_MASK = 0xFFF0
const val PACKET_SIZE = 16
@@ -44,7 +44,7 @@ class HIDCommon {
val receiverProductRules = listOf(
HidProductRule(HID_TRACKER_RECEIVER_VID, HID_RECEIVER_PID),
HidProductRule(GESTURES_INC_VID, GESTURES_INC_PID_D2XX, GESTURES_INC_PID_D2XX_MASK),
HidProductRule(GESTURES_INC_VID, GESTURES_INC_PID_D2DX, GESTURES_INC_PID_D2DX_MASK),
)
val trackerProductRules = listOf(
HidProductRule(HID_TRACKER_RECEIVER_VID, HID_TRACKER_PID),
@@ -490,11 +490,15 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
// Too low or high voltage should mean there is no battery or there is a measurement error
// Some ESP can run at 2.3V, set a limit at 2V
// Below this the tracker is definitely dead if everything is working properly
if (packet.voltage > 2f && packet.voltage < 6f) {
// Assuming floor when converting to int
it.batteryLevel = if (packet.level < 0.01f) -1f else packet.level * 100
if (packet.voltage != null) {
if (packet.voltage!! > 2f && packet.voltage!! < 6f) {
// Assuming floor when converting to int
it.batteryLevel = if (packet.level < 0.01f) -1f else packet.level * 100
} else {
it.batteryLevel = 0f
}
} else {
it.batteryLevel = 0f
it.batteryLevel = packet.level * 100
}
// Server displays 0% if received 255 or -1, otherwise 0 will hide battery icon
}
@@ -186,17 +186,16 @@ data class UDPPacket11Serial(var serial: String = "") : UDPPacket(11) {
}
data class UDPPacket12BatteryLevel(
var voltage: Float = 0.0f,
var voltage: Float? = null,
var level: Float = 0.0f,
) : UDPPacket(12) {
override fun readData(buf: ByteBuffer) {
voltage = UDPUtils.getSafeBufferFloat(buf)
if (buf.remaining() > 3) {
if (buf.remaining() >= 8) {
voltage = UDPUtils.getSafeBufferFloat(buf)
level = UDPUtils.getSafeBufferFloat(buf)
} else {
level = voltage
voltage = 0.0f
level = UDPUtils.getSafeBufferFloat(buf)
}
}
}
@@ -273,7 +273,9 @@ class TrackingChecklistManager(private val vrServer: VRServer) : VRCConfigListen
}
}
val steamVRBridge = vrServer.getVRBridge(ISteamVRBridge::class.java)
val steamVRBridge = vrServer.getVRBridge {
it is ISteamVRBridge
} as? ISteamVRBridge
if (steamVRBridge != null) {
val steamvrConnected = steamVRBridge.isConnected()
updateValidity(
@@ -231,6 +231,10 @@ class WebSocketVRBridge(
start()
}
override fun stopBridge() {
stop()
}
override fun isConnected(): Boolean = super.getConnections().isNotEmpty()
companion object {
@@ -41,7 +41,7 @@ enum class OperatingSystem(
if (currentPlatform == LINUX) {
val isPressureVessel = System.getenv("PRESSURE_VESSEL_RUNTIME")?.isNotEmpty() == true
if (isPressureVessel) {
dir = System.getenv("XDG_CONFIG_HOME")?.let { Path(it, SLIMEVR_IDENTIFIER).toString() }
dir = System.getenv("XDG_DATA_HOME")?.let { Path(it, SLIMEVR_IDENTIFIER).toString() }
?: System.getenv("HOME")?.let { Path(it, ".local", "share", SLIMEVR_IDENTIFIER).toString() }
if (dir != null) return dir
}
@@ -4,10 +4,9 @@ import com.jme3.math.FastMath
import dev.slimevr.VRServer.Companion.getNextLocalTrackerId
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.udp.IMUType
import dev.slimevr.unit.TrackerTestUtils.assertAngleEquals
import dev.slimevr.unit.TrackerTestUtils.degYaw
import dev.slimevr.unit.TrackerTestUtils.radToDeg
import dev.slimevr.unit.TrackerTestUtils.radYaw
import dev.slimevr.unit.TrackerTestUtils.assertAnglesApproxEqual
import dev.slimevr.unit.TrackerTestUtils.deg
import dev.slimevr.unit.TrackerTestUtils.yaw
import io.github.axisangles.ktmath.EulerAngles
import io.github.axisangles.ktmath.EulerOrder
import io.github.axisangles.ktmath.Quaternion
@@ -27,7 +26,7 @@ class MountingResetTests {
fun testResetAndMounting(): List<DynamicTest> = TrackerTestUtils.directions.flatMap { e ->
TrackerTestUtils.directions.map { m ->
DynamicTest.dynamicTest(
"Full and Mounting Reset Test of Tracker (Expected: ${degYaw(e)}, reference: ${degYaw(m)})",
"Full and Mounting Reset Test of Tracker (Expected: ${deg(e)}, reference: ${deg(m)})",
) {
checkResetMounting(e, m)
}
@@ -57,12 +56,12 @@ class MountingResetTests {
tracker.setRotation(trackerRot)
tracker.resetsHandler.resetMounting(Quaternion.IDENTITY)
val expectedYaw = radYaw(expected)
val resultYaw = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
val expectedYaw = yaw(expected)
val resultYaw = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
expectedYaw,
resultYaw,
message = "Resulting mounting yaw after full reset is not equal to reference yaw (${radToDeg(expectedYaw)} vs ${radToDeg(resultYaw)})",
"Resulting mounting yaw after full reset is not equal to reference yaw (${deg(expectedYaw)} vs ${deg(resultYaw)})",
)
// Apply full reset and mounting plus offset
@@ -74,12 +73,12 @@ class MountingResetTests {
// it needs to be applied twice
tracker.resetsHandler.resetMounting(reference * reference)
val expectedYaw2 = radYaw(expected)
val resultYaw2 = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
val expectedYaw2 = yaw(expected)
val resultYaw2 = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
expectedYaw2,
resultYaw2,
message = "Resulting mounting yaw after full reset with offset is not equal to reference yaw (${radToDeg(expectedYaw2)} vs ${radToDeg(resultYaw2)})",
"Resulting mounting yaw after full reset with offset is not equal to reference yaw (${deg(expectedYaw2)} vs ${deg(resultYaw2)})",
)
// Apply yaw reset and mounting
@@ -89,12 +88,12 @@ class MountingResetTests {
tracker.setRotation(trackerRot)
tracker.resetsHandler.resetMounting(Quaternion.IDENTITY)
val expectedYaw3 = radYaw(expected)
val resultYaw3 = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
val expectedYaw3 = yaw(expected)
val resultYaw3 = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
expectedYaw3,
resultYaw3,
message = "Resulting mounting yaw after yaw reset is not equal to reference yaw (${radToDeg(expectedYaw3)} vs ${radToDeg(resultYaw3)})",
"Resulting mounting yaw after yaw reset is not equal to reference yaw (${deg(expectedYaw3)} vs ${deg(resultYaw3)})",
)
// Apply yaw reset and mounting plus offset
@@ -107,12 +106,12 @@ class MountingResetTests {
// it needs to be applied twice
tracker.resetsHandler.resetMounting(reference * reference)
val expectedYaw4 = radYaw(expected)
val resultYaw4 = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
val expectedYaw4 = yaw(expected)
val resultYaw4 = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
expectedYaw3,
resultYaw3,
message = "Resulting mounting yaw after yaw reset with offset is not equal to reference yaw (${radToDeg(expectedYaw4)} vs ${radToDeg(resultYaw4)})",
"Resulting mounting yaw after yaw reset with offset is not equal to reference yaw (${deg(expectedYaw4)} vs ${deg(resultYaw4)})",
)
}
@@ -142,23 +141,23 @@ class MountingResetTests {
tracker.setRotation(trackerRot)
tracker.resetsHandler.resetMounting(Quaternion.IDENTITY)
val expectedYaw = radYaw(expected)
val resultYaw = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
val expectedYaw = yaw(expected)
val resultYaw = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
expectedYaw,
resultYaw,
message = "Resulting mounting yaw after full reset is not equal to reference yaw (${radToDeg(expectedYaw)} vs ${radToDeg(resultYaw)})",
"Resulting mounting yaw after full reset is not equal to reference yaw (${deg(expectedYaw)} vs ${deg(resultYaw)})",
)
tracker.setRotation(reference * reference)
tracker.resetsHandler.resetYaw(reference)
val expectedYaw2 = radYaw(reference)
val resultYaw2 = radYaw(tracker.getRotation())
assertAngleEquals(
val expectedYaw2 = yaw(reference)
val resultYaw2 = yaw(tracker.getRotation())
assertAnglesApproxEqual(
expectedYaw2,
resultYaw2,
message = "Resulting rotation after yaw reset is not equal to reference yaw (${radToDeg(expectedYaw2)} vs ${radToDeg(resultYaw2)})",
"Resulting rotation after yaw reset is not equal to reference yaw (${deg(expectedYaw2)} vs ${deg(resultYaw2)})",
)
}
}
@@ -1,231 +0,0 @@
package dev.slimevr.unit
import com.jme3.math.FastMath
import dev.slimevr.unit.TrackerTestUtils.assertAngleEquals
import dev.slimevr.unit.TrackerTestUtils.assertQuatEquals
import dev.slimevr.unit.TrackerTestUtils.assertQuatNotEquals
import dev.slimevr.unit.TrackerTestUtils.quatApproxEqual
import io.github.axisangles.ktmath.EulerAngles
import io.github.axisangles.ktmath.EulerOrder
import io.github.axisangles.ktmath.Quaternion
import org.junit.jupiter.api.DynamicTest
import org.junit.jupiter.api.TestFactory
import kotlin.math.abs
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
// These technically don't test any implemented code, but serves as a definitive proof
// and learning material for our "session calibration" math and logic.
class ResetTheoryTests {
@TestFactory
fun makeRawOrientationTests(): List<DynamicTest> = roughHeading.flatMap { hC ->
roughAttitude.flatMap { aA ->
roughHeading.map { hA ->
DynamicTest.dynamicTest(
"testMakeOrientation( hC: $hC, aA: $aA, hA: $hA )",
) {
// We can just use identity for the target orientation as only the
// calibration quaternions themselves matter.
testMakeRawOrientation(Quaternion.IDENTITY, hC, aA, hA)
}
}
}
}
/**
* We're trying to prove stuff here using this, so let's at least prove that we can
* make a raw orientation and then bring it back to the bone frame of reference.
*/
fun testMakeRawOrientation(
boneOrientation: Quaternion,
headingCorrect: Quaternion,
attitudeAlign: Quaternion,
headingAlign: Quaternion,
) {
val rawOrientation = makeRawOrientation(boneOrientation, headingCorrect, attitudeAlign, headingAlign)
val newBoneOrientation = headingCorrect * rawOrientation * attitudeAlign * headingAlign
// Now that we re-applied the calibrations, let's see if it matches!
assertQuatEquals(boneOrientation, newBoneOrientation)
}
@TestFactory
fun headingCorrectTimingTests(): List<DynamicTest> = roughHeading.flatMap { hC ->
roughAttitude.flatMap { aA ->
roughHeading.map { hA ->
DynamicTest.dynamicTest(
"testHeadingCorrectTiming( hC: $hC, aA: $aA, hA: $hA )",
) {
// We can just use identity for the target orientation as only the
// calibration quaternions themselves matter.
testHeadingCorrectTiming(Quaternion.IDENTITY, hC, aA, hA)
}
}
}
}
/**
* It doesn't actually matter *when* you add heading correction, just as long as
* it's on the left side.
*/
fun testHeadingCorrectTiming(
rawOrientation: Quaternion,
headingCorrect: Quaternion,
attitudeAlign: Quaternion,
headingAlign: Quaternion,
) {
val boneOrientationA = headingCorrect * rawOrientation * attitudeAlign * headingAlign
val boneOrientationB = headingCorrect * (rawOrientation * attitudeAlign * headingAlign)
val boneOrientationC = headingCorrect * (rawOrientation * attitudeAlign) * headingAlign
assertQuatEquals(boneOrientationA, boneOrientationB)
assertQuatEquals(boneOrientationA, boneOrientationC)
}
@TestFactory
fun headingCorrectAttitudeAlignTests(): List<DynamicTest> = roughHeading.flatMap { hC ->
roughAttitude.map { aA ->
DynamicTest.dynamicTest(
"testHeadingCorrectAttitudeAlign( hC: $hC, aA: $aA )",
) {
// We can just use identity for the target orientation as only the
// calibration quaternions themselves matter.
testHeadingCorrectAttitudeAlign(Quaternion.IDENTITY, hC, aA)
}
}
}
/**
* Heading correction also does not affect the calculation of the attitude alignment
* using euler angles.
*/
fun testHeadingCorrectAttitudeAlign(
rawOrientation: Quaternion,
headingCorrect: Quaternion,
attitudeAlign: Quaternion,
) {
val boneOrientationA = (rawOrientation * attitudeAlign).toEulerAngles(EulerOrder.YZX)
val boneOrientationB = (headingCorrect * rawOrientation * attitudeAlign).toEulerAngles(EulerOrder.YZX)
assertAngleEquals(boneOrientationA.x, boneOrientationB.x, FastMath.ZERO_TOLERANCE)
assertAngleEquals(boneOrientationA.z, boneOrientationB.z, FastMath.ZERO_TOLERANCE)
// We can also show that we're calculating the right attitude alignment.
val attitudeAlignEul = attitudeAlign.toEulerAngles(EulerOrder.YZX)
assertAngleEquals(attitudeAlignEul.x, boneOrientationA.x, FastMath.ZERO_TOLERANCE)
assertAngleEquals(attitudeAlignEul.z, boneOrientationA.z, FastMath.ZERO_TOLERANCE)
}
@TestFactory
fun attitudeHeadingAlignDependenceTests(): List<DynamicTest> {
// Order doesn't matter if the attitude alignment has no attitude.
return roughAttitude.filterNot { FastMath.isApproxZero(it.x) && FastMath.isApproxZero(it.z) }.flatMap { aA ->
// Same for if heading alignment is the quaternion identity.
roughHeading.filterNot { quatApproxEqual(it, Quaternion.IDENTITY) }.map { hA ->
DynamicTest.dynamicTest(
"testAttitudeHeadingAlignDependence( aA: $aA, hA: $hA )",
) {
// We can just use identity for the target orientation as only the
// calibration quaternions themselves matter.
testAttitudeHeadingAlignDependence(Quaternion.IDENTITY, aA, hA)
}
}
}
}
/**
* It *does* matter what order you apply attitude and heading alignment.
*/
fun testAttitudeHeadingAlignDependence(
rawOrientation: Quaternion,
attitudeAlign: Quaternion,
headingAlign: Quaternion,
) {
val boneOrientationA = rawOrientation * attitudeAlign * headingAlign
val boneOrientationB = rawOrientation * headingAlign * attitudeAlign
assertQuatNotEquals(boneOrientationA, boneOrientationB)
}
@TestFactory
fun attitudeHeadingAlignOrderTests(): List<DynamicTest> {
// We're not proving anything if both attitude axes are of equal magnitude.
return roughAttitude.filterNot { FastMath.isApproxEqual(abs(it.x), abs(it.z)) }.flatMap { aA ->
roughHeading.map { hA ->
DynamicTest.dynamicTest(
"testAttitudeHeadingAlignOrder( aA: $aA, hA: $hA )",
) {
// We can just use identity for the target orientation as only the
// calibration quaternions themselves matter.
testAttitudeHeadingAlignOrder(Quaternion.IDENTITY, aA, hA)
}
}
}
}
/**
* If we want to modify heading alignment but keep a constant attitude alignment,
* we need to apply heading alignment *after* attitude.
*/
fun testAttitudeHeadingAlignOrder(
rawOrientation: Quaternion,
attitudeAlign: Quaternion,
headingAlign: Quaternion,
) {
// Perpendicular heading alignment (rotated by 90 deg), makes it easy to check
// our results.
val headingAlignB = headingAlign * Quaternion.rotationAroundYAxis(FastMath.HALF_PI)
// We must also apply an inverse of the heading alignment to make our
// quaternions comparable; we just want to affect the axes, not add to the
// orientation.
val boneOrientationA = headingAlign.inv() * (rawOrientation * attitudeAlign * headingAlign)
val boneOrientationB = headingAlignB.inv() * (rawOrientation * attitudeAlign * headingAlignB)
assertEquals(abs(boneOrientationA.x), abs(boneOrientationB.z), FastMath.ZERO_TOLERANCE)
assertEquals(abs(boneOrientationA.z), abs(boneOrientationB.x), FastMath.ZERO_TOLERANCE)
// Since it's required for this test, we can also show that by applying the
// inverse of heading alignment as a heading correction, we can retain the same
// heading orientation despite changing alignment. By doing this, we remove
// dependence between correction and alignment; they can resolve to definitive
// values.
assertEquals(boneOrientationA.y, boneOrientationB.y, FastMath.ZERO_TOLERANCE)
// We can also show that this does not work when heading alignment comes before
// attitude alignment.
val boneOrientationC = headingAlign.inv() * (rawOrientation * headingAlign * attitudeAlign)
val boneOrientationD = headingAlignB.inv() * (rawOrientation * headingAlignB * attitudeAlign)
assertNotEquals(abs(boneOrientationC.x), abs(boneOrientationD.z), FastMath.ZERO_TOLERANCE)
assertNotEquals(abs(boneOrientationC.z), abs(boneOrientationD.x), FastMath.ZERO_TOLERANCE)
}
companion object {
// 5 steps
val roughStep = -180..180 step 72
// 12 steps
val fineStep = -180..180 step 30
// Will not work when we don't know the heading correction or heading alignment,
// we will need euler angles to calculate those, and it needs to sacrifice one
// axis for euler angles to work
val roughAttitude = roughStep.flatMap { x ->
roughStep.map { z ->
EulerAngles(EulerOrder.YZX, x * FastMath.DEG_TO_RAD, 0f, z * FastMath.DEG_TO_RAD).toQuaternion()
}
}
val roughHeading = roughStep.map { y ->
Quaternion.rotationAroundYAxis(y * FastMath.DEG_TO_RAD)
}
/**
* Reverse calibration to get a raw orientation from a bone orientation.
*/
// We reverse the order of headingAlign and attitudeAlign here since our
// attitude alignment is within the raw heading frame of reference, so we must
// bring the orientation back into that frame of reference first. Whatever is
// applied last must be taken off first.
fun makeRawOrientation(
boneOrientation: Quaternion,
headingCorrect: Quaternion,
attitudeAlign: Quaternion,
headingAlign: Quaternion,
): Quaternion = headingCorrect.inv() * boneOrientation * headingAlign.inv() * attitudeAlign.inv()
}
}
@@ -3,7 +3,7 @@ package dev.slimevr.unit
import com.jme3.math.FastMath
import dev.slimevr.tracking.processor.HumanPoseManager
import dev.slimevr.tracking.trackers.TrackerPosition
import dev.slimevr.unit.TrackerTestUtils.assertAngleEquals
import dev.slimevr.unit.TrackerTestUtils.assertAnglesApproxEqual
import dev.slimevr.unit.TrackerTestUtils.quatApproxEqual
import io.github.axisangles.ktmath.EulerAngles
import io.github.axisangles.ktmath.EulerOrder
@@ -57,8 +57,8 @@ class SkeletonResetTests {
hpm.resetTrackersYaw(resetSource)
for (tracker in trackers.set) {
val yaw = TrackerTestUtils.radYaw(tracker.getRotation())
assertAngleEquals(0f, yaw, message = "\"${tracker.name}\" did not reset to the reference rotation.")
val yaw = TrackerTestUtils.yaw(tracker.getRotation())
assertAnglesApproxEqual(0f, yaw, "\"${tracker.name}\" did not reset to the reference rotation.")
}
}
@@ -104,9 +104,9 @@ class SkeletonResetTests {
val actualMounting = tracker.resetsHandler.mountRotFix
// Make sure yaw matches
val expectedY = TrackerTestUtils.radYaw(expectedMounting)
val actualY = TrackerTestUtils.radYaw(actualMounting)
assertAngleEquals(expectedY, actualY, message = "\"${tracker.name}\" did not reset to the reference rotation.")
val expectedY = TrackerTestUtils.yaw(expectedMounting)
val actualY = TrackerTestUtils.yaw(actualMounting)
assertAnglesApproxEqual(expectedY, actualY, "\"${tracker.name}\" did not reset to the reference rotation.")
// X and Z components should be zero for mounting
assert(FastMath.isApproxZero(actualMounting.x)) {
@@ -56,71 +56,32 @@ object TrackerTestUtils {
/**
* Gets the yaw of a rotation in radians
*/
fun radYaw(rot: Quaternion): Float = posRad(rot.toEulerAngles(EulerOrder.YZX).y)
fun yaw(rot: Quaternion): Float = posRad(rot.toEulerAngles(EulerOrder.YZX).y)
/**
* Converts radians to degrees
*/
fun radToDeg(rot: Float): Float = rot * FastMath.RAD_TO_DEG
fun deg(rot: Float): Float = rot * FastMath.RAD_TO_DEG
fun degYaw(rot: Quaternion): Float = radToDeg(radYaw(rot))
fun deg(rot: Quaternion): Float = deg(yaw(rot))
private fun angleApproxEqual(a: Float, b: Float, tolerance: Float = FastMath.ZERO_TOLERANCE): Boolean = FastMath.isApproxEqual(a, b, tolerance) ||
FastMath.isApproxEqual(a - FastMath.TWO_PI, b, tolerance) ||
FastMath.isApproxEqual(a, b - FastMath.TWO_PI, tolerance)
private fun anglesApproxEqual(a: Float, b: Float): Boolean = FastMath.isApproxEqual(a, b) ||
FastMath.isApproxEqual(a - FastMath.TWO_PI, b) ||
FastMath.isApproxEqual(a, b - FastMath.TWO_PI)
fun assertAngleEquals(expected: Float, actual: Float, tolerance: Float = FastMath.ZERO_TOLERANCE, message: String? = null) {
if (!angleApproxEqual(expected, actual, tolerance)) {
fun assertAnglesApproxEqual(expected: Float, actual: Float, message: String?) {
if (!anglesApproxEqual(expected, actual)) {
AssertionFailureBuilder.assertionFailure().message(message)
.expected(expected).actual(actual).buildAndThrow()
}
}
fun assertAngleNotEquals(expected: Float, actual: Float, tolerance: Float = FastMath.ZERO_TOLERANCE, message: String? = null) {
if (angleApproxEqual(expected, actual, tolerance)) {
AssertionFailureBuilder.assertionFailure().message(message)
.expected(expected).actual(actual).buildAndThrow()
}
}
/**
* True if the quaternions are approximately equal in quaternion space, not rotation
* space.
*/
fun quatApproxEqual(q1: Quaternion, q2: Quaternion, tolerance: Float = FastMath.ZERO_TOLERANCE): Boolean = FastMath.isApproxEqual(q1.w, q2.w, tolerance) &&
FastMath.isApproxEqual(q1.x, q2.x, tolerance) &&
FastMath.isApproxEqual(q1.y, q2.y, tolerance) &&
FastMath.isApproxEqual(q1.z, q2.z, tolerance)
fun assertQuatEquals(expected: Quaternion, actual: Quaternion, tolerance: Float = FastMath.ZERO_TOLERANCE, message: String? = null) {
if (!quatApproxEqual(expected, actual, tolerance)) {
AssertionFailureBuilder.assertionFailure().message(message)
.expected(expected).actual(actual).buildAndThrow()
}
}
fun assertQuatNotEquals(expected: Quaternion, actual: Quaternion, tolerance: Float = FastMath.ZERO_TOLERANCE, message: String? = null) {
if (quatApproxEqual(expected, actual, tolerance)) {
AssertionFailureBuilder.assertionFailure().message(message)
.expected(expected).actual(actual).buildAndThrow()
}
}
fun vectorApproxEqual(v1: Vector3, v2: Vector3, tolerance: Float = FastMath.ZERO_TOLERANCE): Boolean = FastMath.isApproxEqual(v1.x, v2.x, tolerance) &&
FastMath.isApproxEqual(v1.y, v2.y, tolerance) &&
FastMath.isApproxEqual(v1.z, v2.z, tolerance)
fun assertVectorEquals(expected: Vector3, actual: Vector3, tolerance: Float = FastMath.ZERO_TOLERANCE, message: String? = null) {
if (!vectorApproxEqual(expected, actual, tolerance)) {
AssertionFailureBuilder.assertionFailure().message(message)
.expected(expected).actual(actual).buildAndThrow()
}
}
fun assertVectorNotEquals(expected: Vector3, actual: Vector3, tolerance: Float = FastMath.ZERO_TOLERANCE, message: String? = null) {
if (vectorApproxEqual(expected, actual, tolerance)) {
AssertionFailureBuilder.assertionFailure().message(message)
.expected(expected).actual(actual).buildAndThrow()
}
}
}
@@ -15,6 +15,7 @@ import dev.slimevr.desktop.platform.SteamVRBridge
import dev.slimevr.desktop.platform.linux.UnixSocketBridge
import dev.slimevr.desktop.platform.linux.UnixSocketRpcBridge
import dev.slimevr.desktop.platform.windows.WindowsNamedPipeBridge
import dev.slimevr.desktop.platform.windows.WindowsNamedPipeRpcBridge
import dev.slimevr.desktop.serial.DesktopSerialHandler
import dev.slimevr.desktop.tracking.trackers.hid.DesktopHIDManager
import dev.slimevr.tracking.trackers.Tracker
@@ -57,8 +58,8 @@ fun main(args: Array<String>) {
val isLinux = OperatingSystem.currentPlatform == OperatingSystem.LINUX
options.addOption("h", "help", false, "Show help")
options.addOption("V", "version", false, "Show version")
options.addOption("i", "install", true, "Run the driver install")
options.addOption("s", "steam", true, "Run the server in steam mode")
options.addOption("i", "install", false, "Run the driver install")
options.addOption("s", "steam", false, "Run the server in steam mode")
if (isLinux) {
options.addOption("u", "no-udev", false, "Skip checking if udev rules are installed")
}
@@ -211,18 +212,26 @@ fun provideBridges(
FastList(),
),
)
yield(
WindowsNamedPipeRpcBridge(
server,
"""\\.\pipe\SlimeVRRpc""",
),
)
}
OperatingSystem.LINUX -> {
var linuxBridge: SteamVRBridge? = null
try {
linuxBridge = UnixSocketBridge(
server,
"steamvr",
"SteamVR Driver Bridge",
Paths.get(OperatingSystem.socketDirectory, "SlimeVRDriver")
.toString(),
computedTrackers,
yield(
UnixSocketBridge(
server,
"steamvr",
"SteamVR Driver Bridge",
Paths.get(OperatingSystem.socketDirectory, "SlimeVRDriver")
.toString(),
computedTrackers,
),
)
} catch (ex: Exception) {
LogManager.severe(
@@ -230,19 +239,7 @@ fun provideBridges(
ex,
)
}
if (linuxBridge != null) {
// Close the named socket on shutdown, or otherwise it's not going to get removed
Runtime.getRuntime().addShutdownHook(
Thread {
try {
(linuxBridge as? UnixSocketBridge)?.close()
} catch (e: Exception) {
throw RuntimeException(e)
}
},
)
yield(linuxBridge)
}
yield(
UnixSocketBridge(
server,
@@ -9,7 +9,6 @@ class Linux {
fun updateLinux() {
updateLinuxSteamVRDriver()
feeder()
}
fun updateLinuxSteamVRDriver() {
@@ -33,28 +32,7 @@ class Linux {
LogManager.info("SteamVR driver successfully installed")
}
fun feeder() {
executeShellCommand("chmod", "+x", "$path/$LINUX_FEEDER_DIRECTORY/SlimeVR-Feeder-App")
val command = if (featureFlags.steam) {
arrayOf("steam-runtime-launch-client", "--alongside-steam", "--", "$path/$LINUX_FEEDER_DIRECTORY/SlimeVR-Feeder-App", "--install")
} else {
arrayOf("$path/$LINUX_FEEDER_DIRECTORY/SlimeVR-Feeder-App", "--install")
}
val feederOutput = executeShellCommand(*command)
if (feederOutput == null) {
LogManager.warning("Error installing feeder")
return
}
if (feederOutput.lowercase().contains("manifest is not installed")) {
LogManager.warning("Could not install feeder application")
} else {
LogManager.info("Successfully installed feeder application")
}
}
companion object {
private const val LINUX_STEAM_DRIVER_DIRECTORY = "slimevr-openvr-driver-x64-linux"
private const val LINUX_FEEDER_DIRECTORY = "SlimeVR-Feeder-App-Linux"
}
}
@@ -10,20 +10,6 @@ class Windows {
fun updateWindows() {
steamVRDriver()
feeder()
}
fun feeder() {
val feederOutput = executeShellCommand("${path}\\${WINDOWS_FEEDER_DIRECTORY}\\SlimeVR-Feeder-App.exe", "--install")
if (feederOutput == null) {
LogManager.warning("Error installing feeder")
return
}
if (feederOutput.lowercase().contains("manifest is not installed")) {
LogManager.warning("Could not install feeder application")
} else {
LogManager.info("Successfully installed feeder application")
}
}
fun steamVRDriver() {
@@ -57,6 +43,5 @@ class Windows {
companion object {
private const val WINDOWS_STEAMVR_DRIVER_DIRECTORY = "slimevr-openvr-driver-win64"
private const val WINDOWS_FEEDER_DIRECTORY = "SlimeVR-Feeder-App-win64"
}
}
@@ -46,7 +46,7 @@ abstract class ProtobufBridge(@JvmField protected val bridgeName: String) : ISte
@BridgeThread
protected abstract fun sendMessageReal(message: ProtobufMessage?): Boolean
private var remoteProtocolVersion: Int = 0
protected var remoteProtocolVersion: Int = 0
@BridgeThread
protected fun messageReceived(message: ProtobufMessage) {
@@ -295,6 +295,6 @@ abstract class ProtobufBridge(@JvmField protected val bridgeName: String) : ISte
companion object {
private const val resetSourceNamePrefix = "ProtobufBridge"
private const val PROTOCOL_VERSION = 1
private const val PROTOCOL_VERSION = 2
}
}
@@ -4,6 +4,7 @@ import dev.slimevr.VRServer
import dev.slimevr.VRServer.Companion.getNextLocalTrackerId
import dev.slimevr.VRServer.Companion.instance
import dev.slimevr.bridge.BridgeThread
import dev.slimevr.bridge.ISteamVRBridge
import dev.slimevr.config.BridgeConfig
import dev.slimevr.desktop.platform.ProtobufMessages.*
import dev.slimevr.protocol.rpc.settings.RPCSettingsHandler
@@ -14,7 +15,83 @@ import dev.slimevr.tracking.trackers.TrackerRole
import dev.slimevr.tracking.trackers.TrackerRole.Companion.getById
import dev.slimevr.tracking.trackers.TrackerUtils.getTrackerForSkeleton
import dev.slimevr.util.ann.VRServerThread
import io.eiren.util.OperatingSystem
import io.eiren.util.collections.FastList
import io.eiren.util.logging.LogManager
import java.nio.file.Path
import kotlin.io.path.Path
import kotlin.io.path.exists
class BindingsProviderManager : Runnable {
private var process: Process? = null
private var watcherThread: Thread? = null
private fun getBinaryPath(): Path? {
// First we want to try to find it in the working directory, its location on
// Steam/Windows/portable.
val binaryName = if (OperatingSystem.currentPlatform == OperatingSystem.WINDOWS) {
"SlimeVR-Bindings-Provider.exe"
} else {
"slimevr-bindings-provider"
}
val workingDir = System.getProperty("user.dir")!!
val binaryPath = Path(workingDir, binaryName)
if (binaryPath.exists()) return binaryPath
// Then look through PATH to find the binary.
// PATH shouldn't be null, but if it is just gracefully fail
val path = System.getenv("PATH") ?: return null
val pathSeparator = System.getProperty("path.separator")!!
for (path in path.split(pathSeparator)) {
val binaryPath = Path(path, binaryName)
if (binaryPath.exists()) return binaryPath
}
// :(
return null
}
fun start() {
check(process == null && watcherThread == null) {
"BindingsProviderManager already running"
}
val binaryPath = getBinaryPath() ?: throw RuntimeException("Unable to find bindings provider binary")
process = ProcessBuilder(binaryPath.toString())
.redirectErrorStream(true)
.start()
LogManager.info("[BindingsProviderManager] Started process")
watcherThread = Thread(this, "Bindings provider watcher")
watcherThread!!.start()
}
fun stop() {
process?.let {
it.destroy()
}
process = null
watcherThread?.interrupt()
watcherThread = null
}
override fun run() {
try {
val interval = 1000L / 30L
while (process?.isAlive == true) {
Thread.sleep(interval)
}
val exitCode = process?.exitValue()
if (exitCode != null) {
LogManager.info("[BindingsProviderManager] Process has exited with exit code $exitCode")
} else {
LogManager.info("[BindingsProviderManager] Process has exited")
}
} catch (_: InterruptedException) {
// Ignore it
}
}
}
abstract class SteamVRBridge(
protected val server: VRServer,
@@ -25,6 +102,7 @@ abstract class SteamVRBridge(
) : ProtobufBridge(bridgeName),
Runnable {
protected val runnerThread: Thread = Thread(this, threadName)
private var bindingsProviderManager: BindingsProviderManager? = null
protected val config: BridgeConfig = server.configManager.vrConfig.getBridge(bridgeSettingsKey)
var connected: Boolean = false
@@ -40,6 +118,13 @@ abstract class SteamVRBridge(
runnerThread.start()
}
@VRServerThread
override fun stopBridge() {
bindingsProviderManager?.stop()
bindingsProviderManager = null
runnerThread.interrupt()
}
@VRServerThread
override fun getShareSetting(role: TrackerRole): Boolean {
for (tr in shareableTrackers) {
@@ -150,10 +235,10 @@ abstract class SteamVRBridge(
// Display name, needsReset and isHmd
val displayName: String = trackerAdded.trackerName
val isHmd = trackerAdded.trackerId == 0
// trackerPosition
val role = getById(trackerAdded.trackerRole)
val isHmd = trackerAdded.trackerId == 0
val trackerPosition = if (role != null) {
getByTrackerRole(role)
} else {
@@ -181,6 +266,33 @@ abstract class SteamVRBridge(
return tracker
}
@VRServerThread
override fun versionReceived(versionMessage: Version) {
super.versionReceived(versionMessage)
if (bridgeSettingsKey == "steamvr" && remoteProtocolVersion >= 2) {
instance.queueTask {
// Shut off the feeder bridge if the connected driver is recent enough
val bridge = instance.getVRBridge {
it is ISteamVRBridge && it.getBridgeConfigKey() == "steamvr_feeder"
} as? SteamVRBridge
bridge?.let {
LogManager.info("[$bridgeName] Driver version is new enough, deactivating feeder bridge")
instance.removeVRBridge(it)
}
// Start the bindings utility when the driver starts up
if (bindingsProviderManager == null) {
bindingsProviderManager = BindingsProviderManager()
}
try {
bindingsProviderManager!!.start()
} catch (e: Exception) {
LogManager.warning("[$bridgeName] Failed to start bindings provider", e)
}
}
}
}
// Battery Status
@VRServerThread
override fun writeBatteryUpdate(localTracker: Tracker) {
@@ -412,6 +524,7 @@ abstract class SteamVRBridge(
@BridgeThread
protected fun reportDisconnected() {
bindingsProviderManager?.stop()
connected = false
}
@@ -16,10 +16,7 @@ import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.channels.*;
import java.util.List;
@@ -30,6 +27,7 @@ public class UnixSocketBridge extends SteamVRBridge implements AutoCloseable {
private final ByteBuffer dst = ByteBuffer.allocate(2048).order(ByteOrder.LITTLE_ENDIAN);
private final ByteBuffer src = ByteBuffer.allocate(2048).order(ByteOrder.LITTLE_ENDIAN);
private File socketFile;
private ServerSocketChannel server;
private SocketChannel channel;
private Selector selector;
@@ -47,7 +45,7 @@ public class UnixSocketBridge extends SteamVRBridge implements AutoCloseable {
this.socketPath = socketPath;
this.socketAddress = UnixDomainSocketAddress.of(socketPath);
File socketFile = new File(socketPath);
socketFile = new File(socketPath);
if (socketFile.exists()) {
if (SocketUtils.isSocketInUse(socketPath)) {
throw new RuntimeException(
@@ -68,7 +66,7 @@ public class UnixSocketBridge extends SteamVRBridge implements AutoCloseable {
public void run() {
try {
this.server = createSocket();
while (true) {
while (!Thread.interrupted()) {
if (this.channel == null) {
reportDisconnected();
this.selector = Selector.open();
@@ -102,17 +100,23 @@ public class UnixSocketBridge extends SteamVRBridge implements AutoCloseable {
} catch (IOException ioError) {
this.resetChannel();
ioError.printStackTrace();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.sleep(10);
}
}
}
} catch (ClosedByInterruptException | InterruptedException e) {
// Exit the thread gracefully.
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
LogManager.severe("[" + bridgeName + "] Exception in runner thread", e);
} finally {
if (this.channel != null) {
try {
this.resetChannel();
} catch (IOException e) {
// Ignore the exception, we're shutting down anyway.
}
}
this.socketFile.delete();
}
}
@@ -92,6 +92,12 @@ public class UnixSocketRpcBridge implements dev.slimevr.bridge.Bridge,
this.runnerThread.start();
}
@Override
@VRServerThread
public void stopBridge() {
this.runnerThread.interrupt();
}
@Override
@BridgeThread
public void run() {
@@ -0,0 +1,371 @@
package dev.slimevr.desktop.platform.windows;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.*;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.W32APIOptions;
import io.eiren.util.logging.LogManager;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
interface Kernel32IO extends Kernel32 {
Kernel32IO INSTANCE = Native.load("kernel32", Kernel32IO.class, W32APIOptions.DEFAULT_OPTIONS);
boolean GetOverlappedResult(
/* [in] */ HANDLE hFile,
/* [in] */ WinBase.OVERLAPPED lpOverlapped,
/* [out] */ IntByReference lpNumberOfBytesTransferred,
/* [in] */ boolean bWait
);
}
public class WindowsNamedPipe implements AutoCloseable {
private static final Kernel32 k32 = Kernel32.INSTANCE;
private static final Kernel32IO k32io = Kernel32IO.INSTANCE;
private static final Advapi32 adv32 = Advapi32.INSTANCE;
public interface PipeMessageReader {
void onMessage(PipeConnection conn, ByteBuffer buf);
}
public static class PipeConnection implements AutoCloseable {
private final String pipeName;
private WinNT.HANDLE handle;
private PipeState state;
protected WinNT.HANDLE openEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE readEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE writeEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE rxEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE wakeEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE[] events = new WinNT.HANDLE[] { openEvent, rxEvent, wakeEvent };
private final WinBase.OVERLAPPED overlappedOpen = new WinBase.OVERLAPPED();
private final WinBase.OVERLAPPED overlappedWrite = new WinBase.OVERLAPPED();
private final WinBase.OVERLAPPED overlappedRead = new WinBase.OVERLAPPED();
private final WinBase.OVERLAPPED overlappedWait = new WinBase.OVERLAPPED();
private final ByteBuffer buf = ByteBuffer.allocate(2048);
private final IntByReference bytesWritten = new IntByReference(0);
private final IntByReference bytesAvailable = new IntByReference(0);
private final IntByReference bytesRead = new IntByReference(0);
private boolean pendingWait = false;
PipeConnection(String pipeName, WinNT.HANDLE pipeHandle) {
this.pipeName = pipeName;
this.handle = pipeHandle;
this.state = PipeState.CREATED;
// Kick off pipe connection.
tryConnect();
}
protected void tryConnect() {
overlappedOpen.clear();
overlappedOpen.hEvent = openEvent;
boolean ok = k32.ConnectNamedPipe(handle, overlappedOpen);
int err = k32.GetLastError();
if (!ok && err != WinError.ERROR_IO_PENDING) {
if (!k32io.GetOverlappedResult(handle, overlappedOpen, bytesRead, true)) {
setError("ConnectNamedPipe failed: " + err);
}
}
}
// Returns true when:
// Pipe has just been opened.
// Pipe is open and we got data.
public boolean update(PipeMessageReader reader) {
switch (state) {
case ERROR: {
// Do nothing.
return false;
}
case CREATED: {
// Check if any events are signaled.
int evIdx = k32.WaitForMultipleObjects(events.length, events, false, 0);
if (evIdx == WinError.WAIT_TIMEOUT) {
// Do nothing if timed out.
return false;
}
if (evIdx == WinBase.WAIT_FAILED) {
setError("Wait failed: " + k32.GetLastError());
}
// Did open succeed?
if (evIdx == 0) {
LogManager
.info("[WindowsNamedPipeConnection] Pipe " + pipeName + " opened");
state = PipeState.OPEN;
return true;
}
break;
}
case OPEN: {
// Did we get data?
if (waitForData(0)) {
return tryRead(reader);
}
break;
}
}
return false;
}
@Override
public void close() {
if (state == PipeState.OPEN)
disconnect();
if (wakeEvent != null) {
k32.CloseHandle(wakeEvent);
wakeEvent = null;
}
if (rxEvent != null) {
k32.CloseHandle(rxEvent);
rxEvent = null;
}
if (writeEvent != null) {
k32.CloseHandle(writeEvent);
writeEvent = null;
}
if (readEvent != null) {
k32.CloseHandle(readEvent);
readEvent = null;
}
if (openEvent != null) {
k32.CloseHandle(openEvent);
openEvent = null;
}
if (handle != null) {
k32.CloseHandle(handle);
handle = null;
}
}
public void setError(String err) {
pendingWait = false;
state = PipeState.ERROR;
LogManager
.severe("[WindowsNamedPipeConnection] Error on pipe " + pipeName + ": " + err);
}
// Wake up immediately from waitForData.
// Could be used by the caller to pump a message queue immediately.
public void wakeUp() {
k32.SetEvent(wakeEvent);
}
// Try to wait timeoutMs for something to be written to the pipe.
public boolean waitForData(int timeoutMs) {
if (state != PipeState.OPEN)
return false;
if (!pendingWait) {
overlappedWait.clear();
overlappedWait.hEvent = rxEvent;
boolean immediate = k32.ReadFile(handle, null, 0, null, overlappedWait);
int err = k32.GetLastError();
if (!immediate && err != WinError.ERROR_IO_PENDING) {
if (err == WinError.ERROR_BROKEN_PIPE || err == WinError.ERROR_NO_DATA) {
setError("Pipe closed");
} else {
setError("ReadFile failed: " + err);
}
return false;
}
pendingWait = true;
}
// Did we get data?
int evIdx = k32.WaitForMultipleObjects(events.length, events, false, timeoutMs);
if (evIdx == 1) {
// events[0] == overlappedWait.hEvent == rxEvent
pendingWait = false;
return true;
}
return false;
}
// Send a message to the pipe.
public boolean sendBuffer(byte[] buffer, int len) {
overlappedWrite.clear();
overlappedWrite.hEvent = writeEvent;
boolean immediate = k32
.WriteFile(handle, buffer, len, null, overlappedWrite);
int err = k32.GetLastError();
if (!immediate && err != WinError.ERROR_IO_PENDING) {
setError("WriteFile failed: " + err);
return false;
}
if (!k32io.GetOverlappedResult(handle, overlappedWrite, bytesWritten, true)) {
setError(
"sendMessageReal/GetOverlappedResult failed: " + k32.GetLastError()
);
return false;
}
if (bytesWritten.getValue() != len) {
setError("Bytes written " + bytesWritten.getValue() + ", expected " + len);
return false;
}
return true;
}
// Try to read messages from the buffer into reader.
protected boolean tryRead(PipeMessageReader reader) {
if (state != PipeState.OPEN) {
return false;
}
boolean anyReceived = false;
buf.clear();
while (k32.PeekNamedPipe(handle, buf.array(), 4, null, bytesAvailable, null)) {
if (bytesAvailable.getValue() < 4) {
return anyReceived; // Wait for more data
}
buf.position(0);
buf.order(ByteOrder.LITTLE_ENDIAN);
int messageLength = buf.getInt();
if (messageLength > 1024) { // Overflow
setError("Pipe overflow. Message length: " + messageLength);
return anyReceived;
}
if (bytesAvailable.getValue() < messageLength) {
return anyReceived; // Wait for more data
}
overlappedRead.clear();
overlappedRead.hEvent = readEvent;
buf.position(0);
boolean immediate = k32
.ReadFile(handle, buf.array(), messageLength, null, overlappedRead);
int err = k32.GetLastError();
if (!immediate && err != WinError.ERROR_IO_PENDING) {
setError("ReadFile failed: " + err);
return anyReceived;
}
if (!k32io.GetOverlappedResult(handle, overlappedRead, bytesRead, true)) {
setError(
"updatePipe/GetOverlappedResult failed: " + k32.GetLastError()
);
return anyReceived;
}
if (bytesRead.getValue() != messageLength) {
setError(
"Bytes read " + bytesRead.getValue() + ", expected " + messageLength
);
return anyReceived;
}
buf.clear();
buf.position(4); // skip size
buf.limit(messageLength);
reader.onMessage(this, buf);
anyReceived = true;
if (state != PipeState.OPEN)
return anyReceived;
}
int err = k32.GetLastError();
if (err == WinError.ERROR_BROKEN_PIPE) {
setError("Pipe closed");
} else {
setError("Pipe error: " + err);
}
return anyReceived;
}
public void disconnect() {
if (!k32.DisconnectNamedPipe(handle)) {
LogManager
.warning(
"[WindowsNamedPipeConnection] Disconnect failed: " + k32.GetLastError()
);
}
state = PipeState.CREATED;
tryConnect();
}
public PipeState getState() {
return state;
}
}
protected final String pipeName;
private final PipeConnection[] pipeConnections;
public WindowsNamedPipe(String pipeName, int maxConnections) throws IOException {
this.pipeName = pipeName;
this.pipeConnections = new PipeConnection[maxConnections];
try {
WinNT.SECURITY_DESCRIPTOR descriptor = new WinNT.SECURITY_DESCRIPTOR(64 * 1024);
adv32.InitializeSecurityDescriptor(descriptor, WinNT.SECURITY_DESCRIPTOR_REVISION);
adv32.SetSecurityDescriptorDacl(descriptor, true, null, false);
adv32
.SetSecurityDescriptorControl(
descriptor,
(short) WinNT.SE_DACL_PROTECTED,
(short) WinNT.SE_DACL_PROTECTED
);
WinBase.SECURITY_ATTRIBUTES attributes = new WinBase.SECURITY_ATTRIBUTES();
attributes.lpSecurityDescriptor = descriptor.getPointer();
attributes.bInheritHandle = false;
for (int i = 0; i < maxConnections; i++) {
WinNT.HANDLE pipeHandle = k32
.CreateNamedPipe(
pipeName,
WinBase.PIPE_ACCESS_DUPLEX | WinNT.FILE_FLAG_OVERLAPPED, // dwOpenMode
WinBase.PIPE_TYPE_BYTE | WinBase.PIPE_READMODE_BYTE | WinBase.PIPE_WAIT, // dwPipeMode
maxConnections, // nMaxInstances,
1024 * 16, // nOutBufferSize,
1024 * 16, // nInBufferSize,
0, // nDefaultTimeOut,
attributes // lpSecurityAttributes
);
if (WinBase.INVALID_HANDLE_VALUE.equals(pipeHandle)) {
throw new IOException(
"Failed to open " + pipeName + " pipe: " + k32.GetLastError()
);
}
this.pipeConnections[i] = new PipeConnection(pipeName, pipeHandle);
}
LogManager.info("[WindowsNamedPipe] Pipe " + pipeName + " created");
} catch (IOException e) {
for (PipeConnection conn : this.pipeConnections) {
if (conn != null)
conn.close();
}
throw e;
}
}
public PipeConnection tryAccept() {
for (PipeConnection conn : this.pipeConnections) {
if (conn.getState() == PipeState.CREATED && conn.update(null)) {
// We got the pipe.
return conn;
}
}
return null;
}
@Override
public void close() {
for (PipeConnection pipeConnection : this.pipeConnections) {
pipeConnection.close();
}
}
}
@@ -2,11 +2,6 @@ package dev.slimevr.desktop.platform.windows;
import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.*;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.W32APIOptions;
import dev.slimevr.VRServer;
import dev.slimevr.bridge.BridgeThread;
import dev.slimevr.desktop.platform.ProtobufMessages.ProtobufMessage;
@@ -17,44 +12,17 @@ import io.eiren.util.logging.LogManager;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
interface Kernel32IO extends Kernel32 {
Kernel32IO INSTANCE = Native.load("kernel32", Kernel32IO.class, W32APIOptions.DEFAULT_OPTIONS);
boolean GetOverlappedResult(
/* [in] */ HANDLE hFile,
/* [in] */ WinBase.OVERLAPPED lpOverlapped,
/* [out] */ IntByReference lpNumberOfBytesTransferred,
/* [in] */ boolean bWait
);
}
public class WindowsNamedPipeBridge extends SteamVRBridge {
private static final Kernel32 k32 = Kernel32.INSTANCE;
private static final Kernel32IO k32io = Kernel32IO.INSTANCE;
private static final Advapi32 adv32 = Advapi32.INSTANCE;
public class WindowsNamedPipeBridge extends SteamVRBridge
implements WindowsNamedPipe.PipeMessageReader {
protected final String pipeName;
protected final String bridgeSettingsKey;
private final byte[] buffArray = new byte[2048];
protected WindowsPipe pipe;
protected WinNT.HANDLE openEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE readEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE writeEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE rxEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE txEvent = k32.CreateEvent(null, false, false, null);
protected WinNT.HANDLE[] events = new WinNT.HANDLE[] { rxEvent, txEvent };
private final WinBase.OVERLAPPED overlappedOpen = new WinBase.OVERLAPPED();
private final WinBase.OVERLAPPED overlappedWrite = new WinBase.OVERLAPPED();
private final WinBase.OVERLAPPED overlappedRead = new WinBase.OVERLAPPED();
private final WinBase.OVERLAPPED overlappedWait = new WinBase.OVERLAPPED();
private final IntByReference bytesWritten = new IntByReference(0);
private final IntByReference bytesAvailable = new IntByReference(0);
private final IntByReference bytesRead = new IntByReference(0);
private boolean pendingWait = false;
protected WindowsNamedPipe pipe = null;
protected WindowsNamedPipe.PipeConnection connection = null;
private final byte[] buf = new byte[2048];
public WindowsNamedPipeBridge(
VRServer server,
@@ -63,266 +31,118 @@ public class WindowsNamedPipeBridge extends SteamVRBridge {
String pipeName,
List<Tracker> shareableTrackers
) {
super(server, "Named pipe thread", bridgeName, bridgeSettingsKey, shareableTrackers);
super(
server,
bridgeName + " named pipe thread",
bridgeName,
bridgeSettingsKey,
shareableTrackers
);
this.pipeName = pipeName;
this.bridgeSettingsKey = bridgeSettingsKey;
overlappedWait.hEvent = rxEvent;
}
@Override
@BridgeThread
public void run() {
try {
createPipe();
while (true) {
pipe = new WindowsNamedPipe(this.pipeName, 1);
while (!Thread.interrupted()) {
boolean pipesUpdated = false;
if (pipe.state == PipeState.CREATED) {
if (connection == null) {
// Report that our pipe is disconnected right now
reportDisconnected();
tryOpeningPipe(pipe);
if ((connection = pipe.tryAccept()) != null)
VRServer.Companion.getInstance().queueTask(this::reconnected);
}
if (pipe.state == PipeState.OPEN) {
pipesUpdated = updatePipe();
if (pipesUpdated) {
reportConnected();
if (connection != null) {
if (connection.getState() == PipeState.OPEN) {
pipesUpdated = connection.update(this);
if (pipesUpdated) {
reportConnected();
}
updateMessageQueue();
}
if (connection.getState() == PipeState.ERROR) {
connection.disconnect();
connection = null;
disconnected();
}
updateMessageQueue();
}
if (pipe.state == PipeState.ERROR) {
resetPipe();
}
if (!pipesUpdated) {
if (pipe.state == PipeState.OPEN) {
waitForData(10);
if (connection != null && connection.getState() == PipeState.OPEN) {
connection.waitForData(10);
} else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.sleep(10);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
LogManager.severe("[" + bridgeName + "] Exception in runner thread", e);
} catch (InterruptedException e) {
// Exit the thread gracefully.
} finally {
LogManager.info("[" + bridgeName + "] Bridge thread exiting");
if (pipe != null) {
pipe.close();
pipe = null;
}
}
}
@Override
@ThreadSafe
protected void signalSend() {
k32.SetEvent(txEvent);
if (connection != null)
connection.wakeUp();
}
@BridgeThread
private void waitForData(int timeoutMs) {
if (pipe.state != PipeState.OPEN)
@Override
public void onMessage(WindowsNamedPipe.PipeConnection connection, ByteBuffer buf) {
if (this.connection != connection) {
LogManager
.severe("[" + bridgeName + "] Got message from connection we don't know about");
return;
if (!pendingWait) {
k32.ReadFile(pipe.pipeHandle, null, 0, null, overlappedWait);
pendingWait = true;
}
int evIdx = k32.WaitForMultipleObjects(events.length, events, false, timeoutMs);
if (evIdx == 0) {
// events[0] == overlappedWait.hEvent == rxEvent
pendingWait = false;
try {
ProtobufMessage message = ProtobufMessage
.parser()
.parseFrom(buf);
messageReceived(message);
} catch (InvalidProtocolBufferException parseEx) {
LogManager.severe("[" + bridgeName + "] Failed to parse message", parseEx);
connection.setError("Failed to parse message");
}
}
@Override
@BridgeThread
protected boolean sendMessageReal(ProtobufMessage message) {
if (pipe.state != PipeState.OPEN) {
if (connection == null || connection.getState() != PipeState.OPEN) {
return false;
}
try {
int size = message.getSerializedSize();
CodedOutputStream os = CodedOutputStream.newInstance(buffArray, 4, size);
CodedOutputStream os = CodedOutputStream.newInstance(buf, 4, size);
message.writeTo(os);
size += 4;
buffArray[0] = (byte) (size & 0xFF);
buffArray[1] = (byte) ((size >> 8) & 0xFF);
buffArray[2] = (byte) ((size >> 16) & 0xFF);
buffArray[3] = (byte) ((size >> 24) & 0xFF);
overlappedWrite.clear();
overlappedWrite.hEvent = writeEvent;
boolean immediate = k32
.WriteFile(pipe.pipeHandle, buffArray, size, null, overlappedWrite);
int err = k32.GetLastError();
if (!immediate && err != WinError.ERROR_IO_PENDING) {
setPipeError("WriteFile failed: " + err);
return false;
}
buf[0] = (byte) (size & 0xFF);
buf[1] = (byte) ((size >> 8) & 0xFF);
buf[2] = (byte) ((size >> 16) & 0xFF);
buf[3] = (byte) ((size >> 24) & 0xFF);
if (!k32io.GetOverlappedResult(pipe.pipeHandle, overlappedWrite, bytesWritten, true)) {
setPipeError(
"sendMessageReal/GetOverlappedResult failed: " + k32.GetLastError()
);
return false;
}
if (bytesWritten.getValue() != size) {
setPipeError("Bytes written " + bytesWritten.getValue() + ", expected " + size);
return false;
}
return true;
return connection.sendBuffer(buf, size);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private boolean updatePipe() throws IOException {
if (pipe.state != PipeState.OPEN) {
return false;
}
boolean readAnything = false;
while (k32.PeekNamedPipe(pipe.pipeHandle, buffArray, 4, null, bytesAvailable, null)) {
if (bytesAvailable.getValue() < 4) {
return readAnything; // Wait for more data
}
int messageLength = (Byte.toUnsignedInt(buffArray[3]) << 24)
| (Byte.toUnsignedInt(buffArray[2]) << 16)
| (Byte.toUnsignedInt(buffArray[1]) << 8)
| Byte.toUnsignedInt(buffArray[0]);
if (messageLength > 1024) { // Overflow
setPipeError("Pipe overflow. Message length: " + messageLength);
return readAnything;
}
if (bytesAvailable.getValue() < messageLength) {
return readAnything; // Wait for more data
}
overlappedRead.clear();
overlappedRead.hEvent = readEvent;
boolean immediate = k32
.ReadFile(pipe.pipeHandle, buffArray, messageLength, null, overlappedRead);
int err = k32.GetLastError();
if (!immediate && err != WinError.ERROR_IO_PENDING) {
setPipeError("ReadFile failed: " + err);
return readAnything;
}
if (!k32io.GetOverlappedResult(pipe.pipeHandle, overlappedRead, bytesRead, true)) {
setPipeError(
"updatePipe/GetOverlappedResult failed: " + k32.GetLastError()
);
return readAnything;
}
if (bytesRead.getValue() != messageLength) {
setPipeError(
"Bytes read " + bytesRead.getValue() + ", expected " + messageLength
);
return readAnything;
}
try {
ProtobufMessage message = ProtobufMessage
.parser()
.parseFrom(buffArray, 4, messageLength - 4);
messageReceived(message);
readAnything = true;
} catch (InvalidProtocolBufferException parseEx) {
parseEx.printStackTrace();
setPipeError("Failed to parse message: " + parseEx.getMessage());
return readAnything;
}
}
int err = k32.GetLastError();
if (err == WinError.ERROR_BROKEN_PIPE) {
setPipeError("Pipe closed");
} else {
setPipeError("Pipe error: " + err);
}
return readAnything;
}
private void setPipeError(String message) {
pipe.state = PipeState.ERROR;
LogManager.severe("[" + bridgeName + "] " + message);
}
private void resetPipe() {
WindowsPipe.safeDisconnect(pipe);
pipe.state = PipeState.CREATED;
VRServer.Companion.getInstance().queueTask(this::disconnected);
}
private void createPipe() throws IOException {
try {
WinNT.SECURITY_DESCRIPTOR descriptor = new WinNT.SECURITY_DESCRIPTOR(64 * 1024);
adv32.InitializeSecurityDescriptor(descriptor, WinNT.SECURITY_DESCRIPTOR_REVISION);
adv32.SetSecurityDescriptorDacl(descriptor, true, null, false);
adv32
.SetSecurityDescriptorControl(
descriptor,
(short) WinNT.SE_DACL_PROTECTED,
(short) WinNT.SE_DACL_PROTECTED
);
WinBase.SECURITY_ATTRIBUTES attributes = new WinBase.SECURITY_ATTRIBUTES();
attributes.lpSecurityDescriptor = descriptor.getPointer();
attributes.bInheritHandle = false;
pipe = new WindowsPipe(
k32
.CreateNamedPipe(
pipeName,
WinBase.PIPE_ACCESS_DUPLEX | WinNT.FILE_FLAG_OVERLAPPED, // dwOpenMode
WinBase.PIPE_TYPE_BYTE | WinBase.PIPE_READMODE_BYTE | WinBase.PIPE_WAIT, // dwPipeMode
1, // nMaxInstances,
1024 * 16, // nOutBufferSize,
1024 * 16, // nInBufferSize,
0, // nDefaultTimeOut,
attributes // lpSecurityAttributes
),
pipeName
);
LogManager.info("[" + bridgeName + "] Pipe " + pipe.name + " created");
if (WinBase.INVALID_HANDLE_VALUE.equals(pipe.pipeHandle)) {
throw new IOException("Can't open " + pipeName + " pipe: " + k32.GetLastError());
}
LogManager.info("[" + bridgeName + "] Pipes are created");
} catch (IOException e) {
WindowsPipe.safeDisconnect(pipe);
throw e;
}
}
private boolean tryOpeningPipe(WindowsPipe pipe) {
overlappedOpen.clear();
overlappedOpen.hEvent = openEvent;
boolean ok = k32.ConnectNamedPipe(pipe.pipeHandle, overlappedOpen);
int err = k32.GetLastError();
if (!ok && err != WinError.ERROR_PIPE_CONNECTED) {
if (err != WinError.ERROR_IO_PENDING) {
setPipeError("ConnectNamedPipe failed: " + err);
return false;
}
if (!k32io.GetOverlappedResult(pipe.pipeHandle, overlappedOpen, bytesRead, true)) {
setPipeError(
"tryOpeningPipe/GetOverlappedResult failed: " + k32.GetLastError()
);
return false;
}
}
pipe.state = PipeState.OPEN;
LogManager.info("[" + bridgeName + "] Pipe " + pipe.name + " is open");
VRServer.Companion.getInstance().queueTask(this::reconnected);
return true;
}
@Override
public boolean isConnected() {
return pipe != null && pipe.state == PipeState.OPEN;
return connection != null && connection.getState() == PipeState.OPEN;
}
@NotNull
@@ -0,0 +1,135 @@
package dev.slimevr.desktop.platform.windows;
import dev.slimevr.VRServer;
import dev.slimevr.bridge.BridgeThread;
import dev.slimevr.protocol.GenericConnection;
import dev.slimevr.protocol.ProtocolAPI;
import dev.slimevr.tracking.trackers.Tracker;
import dev.slimevr.util.ann.VRServerThread;
import io.eiren.util.collections.FastList;
import io.eiren.util.logging.LogManager;
import java.io.IOException;
import java.nio.ByteBuffer;
public class WindowsNamedPipeRpcBridge implements WindowsNamedPipe.PipeMessageReader,
dev.slimevr.bridge.Bridge, dev.slimevr.protocol.ProtocolAPIServer, Runnable, AutoCloseable {
private static final int maxConnections = 16;
private final Thread runnerThread = new Thread(this, "Named pipe RPC thread");
private final String pipePath;
private final ProtocolAPI protocolAPI;
private WindowsNamedPipe pipe;
private FastList<WindowsNamedPipeRpcConnection> connections = new FastList(maxConnections);
public WindowsNamedPipeRpcBridge(VRServer server, String pipePath) {
this.pipePath = pipePath;
this.protocolAPI = server.protocolAPI;
server.protocolAPI.registerAPIServer(this);
}
@Override
@BridgeThread
public void run() {
try {
this.pipe = new WindowsNamedPipe(pipePath, maxConnections);
FastList<WindowsNamedPipeRpcConnection> removedConnections = new FastList(
maxConnections
);
while (true) {
WindowsNamedPipe.PipeConnection newConnection = this.pipe.tryAccept();
if (newConnection != null) {
this.connections.add(new WindowsNamedPipeRpcConnection(newConnection));
}
for (WindowsNamedPipeRpcConnection connection : this.connections) {
if (connection.getState() == PipeState.OPEN) {
connection.update(this);
}
if (connection.getState() == PipeState.ERROR) {
connection.disconnect();
removedConnections.add(connection);
}
}
this.connections.removeAll(removedConnections);
removedConnections.clear();
Thread.sleep(2);
}
} catch (IOException e) {
LogManager.severe("[SolarXR RPC Bridge] Exception in runner thread", e);
} catch (InterruptedException e) {
// Exit the thread gracefully.
} finally {
if (this.pipe != null) {
this.pipe.close();
this.pipe = null;
}
}
}
@Override
@BridgeThread
public void onMessage(WindowsNamedPipe.PipeConnection conn, ByteBuffer buf) {
for (WindowsNamedPipeRpcConnection connection : this.connections) {
if (connection.getConnection() == conn) {
this.protocolAPI.onMessage(connection, buf);
return;
}
}
LogManager.severe("[SolarXR RPC Bridge] Got message from connection we don't know about");
}
@Override
@VRServerThread
public void dataRead() {
}
@Override
@VRServerThread
public void dataWrite() {
}
@Override
@VRServerThread
public void addSharedTracker(Tracker tracker) {
}
@Override
@VRServerThread
public void removeSharedTracker(Tracker tracker) {
}
@Override
@VRServerThread
public void startBridge() {
this.runnerThread.start();
}
@Override
@VRServerThread
public void stopBridge() {
this.runnerThread.interrupt();
}
@Override
public void close() {
this.connections.clear();
if (this.pipe != null)
this.pipe.close();
}
@Override
public boolean isConnected() {
return !this.connections.isEmpty();
}
@Override
public java.util.stream.Stream<GenericConnection> getApiConnections() {
return this.connections.stream().map(conn -> (GenericConnection) conn);
}
}
@@ -0,0 +1,62 @@
package dev.slimevr.desktop.platform.windows;
import dev.slimevr.protocol.ConnectionContext;
import dev.slimevr.protocol.GenericConnection;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.UUID;
public class WindowsNamedPipeRpcConnection implements GenericConnection {
private final UUID id;
private final ConnectionContext context;
private final WindowsNamedPipe.PipeConnection connection;
WindowsNamedPipeRpcConnection(WindowsNamedPipe.PipeConnection connection) {
this.id = UUID.randomUUID();
this.context = new ConnectionContext();
this.connection = connection;
}
@Override
public UUID getConnectionId() {
return id;
}
@Override
public ConnectionContext getContext() {
return this.context;
}
public boolean update(WindowsNamedPipe.PipeMessageReader reader) {
return this.connection.update(reader);
}
public void disconnect() {
this.connection.disconnect();
}
public PipeState getState() {
return this.connection.getState();
}
public WindowsNamedPipe.PipeConnection getConnection() {
return this.connection;
}
@Override
public void send(ByteBuffer bytes) {
if (this.connection.getState() != PipeState.OPEN)
return;
ByteBuffer src = ByteBuffer.allocate(4 + bytes.remaining());
src.order(ByteOrder.LITTLE_ENDIAN);
src.putInt(4 + bytes.remaining());
src.put(bytes);
src.flip();
synchronized (this) {
this.connection.sendBuffer(bytes.array(), bytes.remaining());
}
}
}