From 25ba150e51c841df84cd07af29ca46c447d499b2 Mon Sep 17 00:00:00 2001 From: Sapphire Date: Sun, 26 Apr 2026 17:06:35 -0500 Subject: [PATCH] Bindings provider bug fixes + reformat (#1823) --- .github/CODEOWNERS | 2 + bindings-provider/.clang-format | 297 ++++++++++++++++++++ bindings-provider/src/logger.cpp | 7 +- bindings-provider/src/logger.hpp | 100 +++---- bindings-provider/src/main.cpp | 436 +++++++++++++++-------------- bindings-provider/src/paths.cpp | 32 +-- bindings-provider/src/solarxr.cpp | 183 ++++++------ bindings-provider/src/solarxr.hpp | 13 +- bindings-provider/src/vr_utils.cpp | 97 ++++--- 9 files changed, 751 insertions(+), 416 deletions(-) create mode 100644 bindings-provider/.clang-format diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 970b297dc..17bf3f9bc 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -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 diff --git a/bindings-provider/.clang-format b/bindings-provider/.clang-format new file mode 100644 index 000000000..479a6b9c3 --- /dev/null +++ b/bindings-provider/.clang-format @@ -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 +... + diff --git a/bindings-provider/src/logger.cpp b/bindings-provider/src/logger.cpp index 703ad4e2a..91db4dc33 100644 --- a/bindings-provider/src/logger.cpp +++ b/bindings-provider/src/logger.cpp @@ -10,13 +10,12 @@ 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) + , should_log_to_std_streams(GetConsoleWindow() != nullptr) #endif { } Logger &Logger::get() { - static Logger logger; - return logger; + static Logger logger; + return logger; } diff --git a/bindings-provider/src/logger.hpp b/bindings-provider/src/logger.hpp index 4f0abe3af..4d098d015 100644 --- a/bindings-provider/src/logger.hpp +++ b/bindings-provider/src/logger.hpp @@ -9,69 +9,69 @@ class Logger { private: - std::ofstream log_stream; + std::ofstream log_stream; #ifdef _WIN32 - bool should_log_to_std_streams; + bool should_log_to_std_streams; #endif - template - void log(std::string_view suffix, std::format_string fmt, - Args &&...args) { - auto now = std::chrono::system_clock::now(); - auto time_t = std::chrono::system_clock::to_time_t(now); + template + void log(std::string_view suffix, std::format_string 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)...); + auto s = std::format(fmt, std::forward(args)...); #ifdef _WIN32 - if (should_log_to_std_streams) { + if (should_log_to_std_streams) { #endif - if constexpr (important) - std::cerr << suffix << ' ' << s << '\n'; - else - std::cout << suffix << ' ' << s << '\n'; + 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'; } -#endif - - log_stream << std::put_time(std::localtime(&time_t), "[%F %T]") // - << ' ' << suffix << ' ' << s << '\n'; - } public: - Logger(); + Logger(); - template - void debug(std::format_string fmt, Args &&...args) { + template + void debug(std::format_string fmt, Args &&...args) { #ifndef NDEBUG - log("[DEBUG]", fmt, std::forward(args)...); + log("[DEBUG]", fmt, std::forward(args)...); #endif - } - - template - void info(std::format_string fmt, Args &&...args) { - log("[INFO]", fmt, std::forward(args)...); - } - - template - void warning(std::format_string fmt, Args &&...args) { - log("[WARN]", fmt, std::forward(args)...); - } - - template - void error(std::format_string fmt, Args &&...args) { - log("[ERROR]", fmt, std::forward(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(); + template + void info(std::format_string fmt, Args &&...args) { + log("[INFO]", fmt, std::forward(args)...); + } + + template + void warning(std::format_string fmt, Args &&...args) { + log("[WARN]", fmt, std::forward(args)...); + } + + template + void error(std::format_string fmt, Args &&...args) { + log("[ERROR]", fmt, std::forward(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(); }; diff --git a/bindings-provider/src/main.cpp b/bindings-provider/src/main.cpp index f6d8cf92a..bd3da0c67 100644 --- a/bindings-provider/src/main.cpp +++ b/bindings-provider/src/main.cpp @@ -21,254 +21,268 @@ using namespace solarxr_protocol; static void shutdown_vr(vr::IVRSystem *_sys) { vr::VR_Shutdown(); } static void onYawReset(SolarXRConnection &conn) { - flatbuffers::FlatBufferBuilder fbb; + 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 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); + 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; + 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 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); + 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; + 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 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); + 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; + 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 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); + 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; + 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()); + 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); + 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; + Logger::get().info("Received signal {}", signal); + should_exit = 1; } int main() { - auto &logger = Logger::get(); + auto &logger = Logger::get(); - try { - SolarXRConnection conn; - std::unique_ptr sys{nullptr, - shutdown_vr}; + try { + SolarXRConnection conn; + std::unique_ptr 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 + // 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("")); - - 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; - } - - if (auto err = - input->SetActionManifestPath(actionManifestPath.string().data()); - 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>> - 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; + 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); } - 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; - } - } - 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)); - } + if (sys == nullptr or err != vr::VRInitError_None) { + logger.error("Failed to init OpenVR: {} ({})", + vr::VR_GetVRInitErrorAsSymbol(err), + vr::VR_GetVRInitErrorAsEnglishDescription(err)); + return 1; + } - 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); + logger.info("Initialised OpenVR, HMD model '{}'", + VRUtils::getStringProp(vr::k_unTrackedDeviceIndex_Hmd, + vr::Prop_ModelNumber_String) + .value_or("")); + + 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.warning("Failed to get action state for {} ({}): {}", name, - handle, std::to_underlying(err)); - continue; + logger.error("Failed to get main action set handle: {}", + std::to_underlying(err)); + return 1; } - if (action_data.bActive && action_data.bChanged && action_data.bState) { - logger.debug("Action {} triggered", name); - callback(conn); - } - } + std::map>> + 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) }, + }; - logger.flush(); - std::this_thread::sleep_for(interval); + 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.info("Main loop done"); - } catch (std::exception &ex) { - logger.error("Exception in main: {}", ex.what()); logger.flush(); - return 1; - } - - logger.flush(); - return 0; + return 0; } diff --git a/bindings-provider/src/paths.cpp b/bindings-provider/src/paths.cpp index 8d24426c3..7f33f2974 100644 --- a/bindings-provider/src/paths.cpp +++ b/bindings-provider/src/paths.cpp @@ -3,31 +3,31 @@ namespace fs = std::filesystem; fs::path Paths::getDataPath() { - fs::path basePath{}; + 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"); + 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"; - } + basePath = fs::path(homeDir) / ".local" / "share"; + } #elif defined(_WIN32) - { - const char *appData = getenv("APPDATA"); - if (appData == nullptr) - throw std::runtime_error("APPDATA is unset"); + { + const char *appData = getenv("APPDATA"); + if (appData == nullptr) + throw std::runtime_error("APPDATA is unset"); - basePath = appData; - } + basePath = appData; + } #else #error "Unsupported platform" #endif - return basePath / "dev.slimevr.SlimeVR"; + return basePath / "dev.slimevr.SlimeVR"; } fs::path Paths::getLogPath() { return Paths::getDataPath() / "logs"; } diff --git a/bindings-provider/src/solarxr.cpp b/bindings-provider/src/solarxr.cpp index 0cda24dc1..58f6ca4fe 100644 --- a/bindings-provider/src/solarxr.cpp +++ b/bindings-provider/src/solarxr.cpp @@ -15,74 +15,75 @@ namespace fs = std::filesystem; fs::path SolarXRConnection::getSocketPath() { - using namespace std::string_view_literals; + using namespace std::string_view_literals; #if defined(__linux__) -#define MAKE_SOCKET_PATH(PATH) \ - std::make_pair(PATH##sv, static_cast(getenv(PATH))) +#define MAKE_SOCKET_PATH(PATH) \ + std::make_pair(PATH##sv, static_cast(getenv(PATH))) - constexpr std::string_view socketName = "SlimeVRRpc"; - std::array, 4> socketPaths{ - MAKE_SOCKET_PATH("SLIMEVR_SOCKET_DIR"), - MAKE_SOCKET_PATH("XDG_RUNTIME_DIR"), - MAKE_SOCKET_PATH("TMPDIR"), - {"/tmp", "/tmp"}}; + constexpr std::string_view socketName = "SlimeVRRpc"; + std::array, 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; + 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); - } + 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"); + 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"); + 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()); + 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))); - } + 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(&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))); - } + if (connect(fd, reinterpret_cast(&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"); - } + 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())); - } + 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 @@ -90,50 +91,72 @@ SolarXRConnection::SolarXRConnection() { SolarXRConnection::~SolarXRConnection() { #if defined(__linux__) - if (fd != -1) - close(fd); + if (fd != -1) + close(fd); #elif defined(_WIN32) - if (pipe != INVALID_HANDLE_VALUE) - CloseHandle(pipe); + 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); + // 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, &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; - } + 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; - } + uint8_t tempBuf[2048]; + if (fbb.GetSize() > 2048 - 4) { + Logger::get().warning("Message is too big for temporary buffer"); + return; + } - *reinterpret_cast(&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; - } + *reinterpret_cast(&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 diff --git a/bindings-provider/src/solarxr.hpp b/bindings-provider/src/solarxr.hpp index 1384c4027..98e478322 100644 --- a/bindings-provider/src/solarxr.hpp +++ b/bindings-provider/src/solarxr.hpp @@ -12,19 +12,20 @@ class SolarXRConnection { private: #if defined(__linux__) - int fd{-1}; + int fd{ -1 }; #elif defined(_WIN32) - HANDLE pipe{INVALID_HANDLE_VALUE}; + HANDLE pipe{ INVALID_HANDLE_VALUE }; #else #error "Unsupported platform" #endif - static std::filesystem::path getSocketPath(); + static std::filesystem::path getSocketPath(); public: - SolarXRConnection() noexcept(false); + SolarXRConnection() noexcept(false); - ~SolarXRConnection(); + ~SolarXRConnection(); - void sendMsg(flatbuffers::FlatBufferBuilder &fbb); + bool connected(); + void sendMsg(flatbuffers::FlatBufferBuilder &fbb); }; diff --git a/bindings-provider/src/vr_utils.cpp b/bindings-provider/src/vr_utils.cpp index 189552d2d..590c67251 100644 --- a/bindings-provider/src/vr_utils.cpp +++ b/bindings-provider/src/vr_utils.cpp @@ -13,61 +13,60 @@ namespace fs = std::filesystem; std::optional VRUtils::getStringProp(vr::TrackedDeviceIndex_t deviceIndex, vr::ETrackedDeviceProperty prop) { - vr::IVRSystem *sys = vr::VRSystem(); - vr::ETrackedPropertyError err{vr::TrackedProp_Success}; + 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; - } + 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; - } + 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; + return s; } std::tuple 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; + 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())); } - } - return {manifestDir / requiredFiles.at(0).first, - manifestDir / requiredFiles.at(1).first}; + 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 }; }