Compare commits

..
5 Commits
Author SHA1 Message Date
gitea 410c505099 Actualiser .github/workflows/APK-Release.yml
Build / Linux (map[packages:extra-cmake-modules libarchive-dev libboost-all-dev libkf6coreaddons-dev libkf6qqc2desktopstyle-dev libkf6iconthemes-dev libkirigami-dev librsvg2-dev nlohmann-json3-dev qcoro-qt6-dev qml6-module-org-kde-kirigamiaddons-formcard prese… (push) Waiting to run
Build / Linux (map[packages:libboost-all-dev libsystemd-dev preset:server-tracing]) (push) Waiting to run
Build / Linux (map[packages:libboost-all-dev libsystemd-dev preset:server]) (push) Waiting to run
Build / Linux (map[packages:libboost-all-dev preset:server-no-systemd]) (push) Waiting to run
Build / Linux (map[packages:libboost-all-dev wireshark-dev preset:dissector-no-system-boost]) (push) Waiting to run
Build / Linux (map[packages:libharfbuzz-dev libfreetype-dev libavcodec-dev libavutil-dev libswscale-dev librsvg2-bin gettext libcurl4-openssl-dev libfontconfig-dev libpipewire-0.3-dev preset:client-no-system-boost]) (push) Waiting to run
Build / Linux (map[packages:libsystemd-dev preset:server-no-system-boost]) (push) Waiting to run
Build / Steam Frame (push) Waiting to run
Build / Create release (push) Blocked by required conditions
Build / Sync fork downstream (push) Blocked by required conditions
Build / Linux server (flatpak) (push) Skipped
Build / Test Nix package and devshell (push) Skipped
Build / Android (Debug) (push) Skipped
Build / Android (DebugWithValidationLayer) (push) Skipped
Build / Android (Oculus) (push) Skipped
Build / Android (Release) (push) Skipped
Build / Build Ubuntu package (plucky) (push) Skipped
Format / Formatting check (client) (push) Skipped
Format / Formatting check (common) (push) Skipped
Format / Formatting check (dashboard) (push) Skipped
Format / Formatting check (server) (push) Skipped
Format / Formatting check (tools/wireshark) (push) Skipped
Locales / Locale check (push) Skipped
2026-11-28 22:09:37 +00:00
Vindicus999 50924ddd5c Updating cron settings since Github is dropping them out 2026-10-17 20:18:06 -04:00
Vindicus999 20296a7913 Update APK-Release.yml 2026-09-29 16:16:25 -04:00
Vindicus999 1ea133c5e2 Update APK-Release.yml 2026-09-29 15:37:32 -04:00
Vindicus999 6b4aa7460e Updating stuff for steam frame 2026-09-29 15:22:03 -04:00
291 changed files with 17964 additions and 39992 deletions
+34 -5
View File
@@ -9,10 +9,7 @@ body:
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is.
placeholder: |
Please describe the bug here...
*** Do NOT use AI to generate a bug report ***
Write down what is wrong, attach logs and screenshots when relevant.
placeholder: Please describe the bug here...
validations:
required: true
@@ -25,6 +22,12 @@ body:
2. Click on '...'
3. See error
- type: input
attributes:
label: Expected behavior
description: A clear and concise description of what you expected to happen.
placeholder: Please describe what you expected to happen.
- type: input
attributes:
label: WiVRn Version
@@ -39,6 +42,20 @@ body:
description: Describe how WiVRn and OpenComposite/xrizer were installed
placeholder: flatpak --user, flatpak, AUR, Gentoo/Guru, built from sources...
- type: textarea
attributes:
label: Server Config
description: |
Provide the content of `config.json` for the server.
Located in `${XDG_CONFIG_HOME-${HOME}/.config}/wivrn/config.json`
or `~/.var/app/io.github.wivrn.wivrn/config/wivrn/config.json` for the flatpak version
placeholder: |
{
"encoders": [
{"codec": "h264"}
]
}
- type: textarea
attributes:
label: Server Logs
@@ -47,6 +64,18 @@ body:
Add the output of the wivrn-server here.
If more than a few lines, prefer file attachment.
- type: dropdown
id: gpu
attributes:
label: What GPU did the bug occur on?
options:
- NVIDIA
- AMD
- Intel
- Other
validations:
required: true
- type: textarea
attributes:
label: Vulkan Info
@@ -78,5 +107,5 @@ body:
attributes:
label: ADB Logs
description: Provide the output of `adb logcat` command.
render: text
render: plain
placeholder: Attach the output of adb logcat as a file.
-6
View File
@@ -1,6 +0,0 @@
version: "1"
rules:
- base: master
upstream: WiVRn:master
mergeMethod: hardreset
+80 -98
View File
@@ -6,12 +6,80 @@ on:
env:
BUILD_TYPE: RelWithDebInfo
CSS: images/wivrn-${{(github.ref_type == 'tag' && 'release') || 'nightly'}}.css
jobs:
build-steam-frame:
name: Steam Frame
runs-on: ubuntu-24.04-arm
if: ${{ vars.APK_ONLY != '' }}
container:
image: registry.gitlab.steamos.cloud/steamrt/steamrt4/sdk/arm64:4.0.20260805.254769
volumes:
- ${{github.workspace}}/install:/tmp/install
steps:
- uses: actions/checkout@v6
with:
repository: 'gitea/WiVRn'
ref: ${{ github.sha }}
fetch-depth: 0
fetch-tags: true
- name: Apt dependencies
uses: awalsh128/cache-apt-pkgs-action@v1.6.1
with:
packages: librsvg2-bin npm
- name: ccache
uses: hendrikmuhs/ccache-action@v1.2.23
with:
key: steam-frame
job-summary: ""
- uses: actions/cache@v5
with:
key: cmake-frame
path: |
${{github.workspace}}/cmake-fetch/*-subbuild/*-populate-prefix/src/*.tar.*
${{github.workspace}}/cmake-fetch/*-subbuild/*-populate-prefix/src/*.zip
${{github.workspace}}/cmake-fetch/*.tar.*
${{github.workspace}}/cmake-fetch/*.tgz
${{github.workspace}}/cmake-fetch/*-src/.git
- name: Install dependencies
run: |
wget https://github.com/KhronosGroup/KTX-Software/releases/download/v4.4.2/KTX-Software-4.4.2-Linux-arm64.deb
sudo dpkg --install KTX-Software-4.4.2-Linux-arm64.deb
npm install --global @gltf-transform/cli@4.1.1
- name: Configure CMake
run: >
cmake -B "$GITHUB_WORKSPACE/build"
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
-DWIVRN_CSS=${{env.CSS}}
-DFETCHCONTENT_BASE_DIR="$GITHUB_WORKSPACE/cmake-fetch"
-DCMAKE_C_COMPILER_LAUNCHER=ccache
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache
-DCMAKE_INSTALL_PREFIX=/usr
--preset frame
- name: Build
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
cd "$GITHUB_WORKSPACE/build"
DESTDIR="$GITHUB_WORKSPACE/install" ninja install
- name: Archive
uses: actions/upload-artifact@v7
with:
name: wivrn-frame-client.zip
path: install/usr
if-no-files-found: error
retention-days: 30
build-android-only:
name: Android
runs-on: ubuntu-24.04-full
runs-on: ubuntu-24.04
if: ${{ vars.APK_ONLY != '' }}
strategy:
@@ -19,18 +87,13 @@ jobs:
buildtype: ['Release', 'Debug', 'DebugWithValidationLayer']
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
with:
# Checkout from upstream instead of WiVRn-APK to ensure the GIT_DESC variable is set correctly
repository: 'gitea/WiVRn'
ref: ${{ github.sha }}
fetch-depth: 0
- name: Install CMake
run: |
apt-get update
apt-get install -y cmake build-essential
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944
with:
@@ -40,7 +103,7 @@ jobs:
- name: Install dependencies
run: |
sudo apt-get update && sudo apt-get install -y glslang-tools librsvg2-bin gettext npm
sudo apt-get update && sudo apt-get install glslang-tools librsvg2-bin gettext npm
wget https://github.com/KhronosGroup/KTX-Software/releases/download/v4.4.0/KTX-Software-4.4.0-Linux-x86_64.deb
sudo dpkg --install KTX-Software-4.4.0-Linux-x86_64.deb
npm install --global @gltf-transform/cli@4.1.1
@@ -64,12 +127,6 @@ jobs:
echo signingKeyPassword="$APK_SIGNINGKEYPASSWORD" > gradle.properties
echo "$APK_KEYSTORE_BASE64" | base64 --decode --ignore-garbage > ks.keystore
# - name: Setup Java
# uses: actions/setup-java@v6
# with:
# distribution: temurin
# java-version: '25'
- name: Build
run: |
chmod +x gradlew
@@ -98,77 +155,10 @@ jobs:
path: debug/**/*.so
retention-days: 7
# build-steam-frame:
# name: Steam Frame
# runs-on: ubuntu-24.04-arm
# if: ${{ vars.APK_ONLY != '' }}
# container:
# image: registry.gitlab.steamos.cloud/steamrt/steamrt4/sdk/arm64:4.0.20260805.254769
# volumes:
# - ${{github.workspace}}/install:/tmp/install
#
# steps:
# - uses: actions/checkout@v6
# with:
# fetch-depth: 0
# fetch-tags: true
#
# - name: Apt dependencies
# uses: awalsh128/cache-apt-pkgs-action@v1.6.1
# with:
# packages: librsvg2-bin npm
#
# - name: ccache
# uses: hendrikmuhs/ccache-action@v1.2.23
# with:
# key: steam-frame
# job-summary: ""
#
# - uses: actions/cache@v5
# with:
# key: cmake-frame
# path: |
# ${{github.workspace}}/cmake-fetch/*-subbuild/*-populate-prefix/src/*.tar.*
# ${{github.workspace}}/cmake-fetch/*-subbuild/*-populate-prefix/src/*.zip
# ${{github.workspace}}/cmake-fetch/*.tar.*
# ${{github.workspace}}/cmake-fetch/*.tgz
# ${{github.workspace}}/cmake-fetch/*-src/.git
#
# - name: Install dependencies
# run: |
# wget https://github.com/KhronosGroup/KTX-Software/releases/download/v4.4.2/KTX-Software-4.4.2-Linux-arm64.deb
# sudo dpkg --install KTX-Software-4.4.2-Linux-arm64.deb
# npm install --global @gltf-transform/cli@4.1.1
#
# - name: Configure CMake
# run: >
# cmake -B "$GITHUB_WORKSPACE/build"
# -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
# -DWIVRN_CSS=${{env.CSS}}
# -DFETCHCONTENT_BASE_DIR="$GITHUB_WORKSPACE/cmake-fetch"
# -DCMAKE_C_COMPILER_LAUNCHER=ccache
# -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
# -DCMAKE_INSTALL_PREFIX=/usr
# --preset frame
#
# - name: Build
# run: |
# git config --global --add safe.directory "$GITHUB_WORKSPACE"
# cd "$GITHUB_WORKSPACE/build"
# DESTDIR="$GITHUB_WORKSPACE/install" ninja install
#
# - name: Archive
# uses: actions/upload-artifact@v7
# with:
# name: wivrn-frame-client.zip
# path: install/usr
# if-no-files-found: error
# retention-days: 30
release:
name: Create APK release
runs-on: ubuntu-24.04
needs: build-android-only
needs: [build-android-only, build-steam-frame]
if: ${{ vars.APK_ONLY != '' }}
steps:
@@ -179,13 +169,12 @@ jobs:
pattern: 'apk-*'
merge-multiple: true
# - name: Rename APK artifacts
# run: |
# cd apk
# for f in *.apk; do
# BASENAME=`echo ${f}|awk -F '-APK-' '{print $2}'`
# mv "${f}" "org.meumeu.wivrn-${BASENAME}"
# done
- name: Download Steam Frame artifact
uses: actions/download-artifact@v4
with:
path: install/usr
pattern: 'wivrn-frame-client.zip'
merge-multiple: true
- name: Download APK debug artifacts
uses: actions/download-artifact@v4
@@ -199,13 +188,6 @@ jobs:
cd symbols
zip -r ../debug-symbols.zip .
# - name: Download Steam Frame artifacts
# uses: actions/download-artifact@v4
# with:
# path: install/usr
# pattern: 'wivrn-frame-client.zip'
# merge-multiple: true
- name: APK Release
uses: softprops/action-gh-release@v2
with:
@@ -216,6 +198,6 @@ jobs:
prerelease: false
fail_on_unmatched_files: true
files: |
install/usr/wivrn-frame-client.zip
apk/*.apk
debug-symbols.zip
+71 -10
View File
@@ -7,6 +7,7 @@ on:
env:
BUILD_TYPE: Release
SERVER_DEPS: libx264-dev libavcodec-dev libavutil-dev libbsd-dev libavahi-client-dev libavahi-glib-dev libeigen3-dev nlohmann-json3-dev librsvg2-dev libdrm-dev libglib2.0-dev-bin libpipewire-0.3-dev libcli11-dev libnotify-dev libarchive-dev libudev-dev
CSS: images/wivrn-${{(github.ref_type == 'tag' && 'release') || 'nightly'}}.css
jobs:
build-linux:
@@ -19,7 +20,7 @@ jobs:
matrix:
config:
- preset: 'client-no-system-boost'
packages: libharfbuzz-dev libfreetype-dev libavcodec-dev libavutil-dev libswscale-dev librsvg2-bin gettext libcurl4-openssl-dev libfontconfig-dev
packages: libharfbuzz-dev libfreetype-dev libavcodec-dev libavutil-dev libswscale-dev librsvg2-bin gettext libcurl4-openssl-dev libfontconfig-dev libpipewire-0.3-dev
- preset: 'dashboard'
packages: extra-cmake-modules libarchive-dev libboost-all-dev libkf6coreaddons-dev libkf6qqc2desktopstyle-dev libkf6iconthemes-dev libkirigami-dev librsvg2-dev nlohmann-json3-dev qcoro-qt6-dev qml6-module-org-kde-kirigamiaddons-formcard
- preset: 'dissector-no-system-boost'
@@ -117,6 +118,73 @@ jobs:
draft: true
files: server-build-deps.tar.xz
build-steam-frame:
name: Steam Frame
runs-on: ubuntu-24.04-arm
if: ${{ vars.APK_ONLY == '' }}
container:
image: registry.gitlab.steamos.cloud/steamrt/steamrt4/sdk/arm64:4.0.20260805.254769
volumes:
- ${{github.workspace}}/install:/tmp/install
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
fetch-tags: true
- name: Apt dependencies
uses: awalsh128/cache-apt-pkgs-action@v1.6.1
with:
packages: librsvg2-bin npm
- name: ccache
uses: hendrikmuhs/ccache-action@v1.2.23
with:
key: steam-frame
job-summary: ""
- uses: actions/cache@v5
with:
key: cmake-frame
path: |
${{github.workspace}}/cmake-fetch/*-subbuild/*-populate-prefix/src/*.tar.*
${{github.workspace}}/cmake-fetch/*-subbuild/*-populate-prefix/src/*.zip
${{github.workspace}}/cmake-fetch/*.tar.*
${{github.workspace}}/cmake-fetch/*.tgz
${{github.workspace}}/cmake-fetch/*-src/.git
- name: Install dependencies
run: |
wget https://github.com/KhronosGroup/KTX-Software/releases/download/v4.4.2/KTX-Software-4.4.2-Linux-arm64.deb
sudo dpkg --install KTX-Software-4.4.2-Linux-arm64.deb
npm install --global @gltf-transform/cli@4.1.1
- name: Configure CMake
run: >
cmake -B "$GITHUB_WORKSPACE/build"
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
-DWIVRN_CSS=${{env.CSS}}
-DFETCHCONTENT_BASE_DIR="$GITHUB_WORKSPACE/cmake-fetch"
-DCMAKE_C_COMPILER_LAUNCHER=ccache
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache
-DCMAKE_INSTALL_PREFIX=/usr
--preset frame
- name: Build
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
cd "$GITHUB_WORKSPACE/build"
DESTDIR="$GITHUB_WORKSPACE/install" ninja install
- name: Archive
uses: actions/upload-artifact@v7
with:
name: wivrn-frame-client.zip
path: install/usr
if-no-files-found: error
retention-days: 30
build-server-flatpak:
name: Linux server (flatpak)
runs-on: ubuntu-24.04
@@ -262,22 +330,15 @@ jobs:
fi
fi
if [ ${{ github.ref_type }} = 'tag' ]
then
CSS=images/wivrn-release.css
else
CSS=images/wivrn-nightly.css
fi
echo Setting version $VERSION and version code $VERSION_CODE in manifest
echo Using stylesheet $CSS and name $APPNAME
echo Using stylesheet ${{env.CSS}} and name $APPNAME
chmod +x gradlew
./gradlew \
-Pwivrn_version=$VERSION \
-Pwivrn_versionCode=$VERSION_CODE \
-Psuffix=$SUFFIX \
-Pwivrn_css=$CSS \
-Pwivrn_css=${{env.CSS}} \
-Pwivrn_app_name="$APPNAME" \
-Pwivrn_compress_glb=ON \
-Pfetchcontent_base_dir=${{github.workspace}}/cmake-fetch \
+1 -19
View File
@@ -15,27 +15,9 @@ jobs:
- 'common'
- 'tools/wireshark'
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v4
- name: Run clang-format style check for C/C++/Protobuf programs.
uses: jidicula/clang-format-action@v4.16.0
with:
clang-format-version: '21'
check-path: ${{ matrix.path }}
python-format-check:
name: Python lint (ruff)
runs-on: ubuntu-24.04
if: ${{ vars.APK_ONLY == '' }}
steps:
- uses: actions/checkout@v6
# Scope set by `include` in ruff.toml.
- name: Run ruff lint check
uses: astral-sh/ruff-action@v3
with:
version: "0.16.0"
args: "check"
- name: Run ruff format check
uses: astral-sh/ruff-action@v3
with:
version: "0.16.0"
args: "format --check"
+2 -12
View File
@@ -6,27 +6,17 @@ jobs:
runs-on: ubuntu-24.04
if: ${{ vars.APK_ONLY == '' }}
steps:
- uses: actions/checkout@v6
- name: Apt dependencies
uses: awalsh128/cache-apt-pkgs-action@v1.6.1
with:
packages: gettext
- uses: actions/checkout@v4
- name: Install dependencies
run: |
sudo apt-get update && sudo apt-get install gettext
pip install polib PyGithub
- name: Check that .po files are up to date
env:
GH_TOKEN: ${{ github.token }}
run: |
if [[ "${{github.ref}}" == 'refs/heads/master' ]] ; then
tools/check_po.py --manage-issues --github-repository "${{ github.repository }}" --github-token "${{ github.token }}"
elif [[ "${{github.base_ref}}" != "" ]] ; then
FILES=$(gh api repos/${{github.repository}}/pulls/${{github.event.pull_request.number}}/files | jq --raw-output '[.[].filename | select(. | startswith("locale/"))] | join(",")')
echo "Locale files changed by pull request: ${FILES}"
tools/check_po.py --fail-on "${FILES}"
else
tools/check_po.py
fi
+7 -5
View File
@@ -8,7 +8,7 @@ env:
on:
workflow_dispatch:
schedule:
- cron: '0 0 * * *'
- cron: '18 2 * * *'
jobs:
build:
@@ -32,12 +32,14 @@ jobs:
- name: Update sync branch
run: |
git checkout -B master upstream/master
git push origin master --force
git config --global user.email "sneed@feedandse.edu"
git config --global user.name "Sneed Chuckinson"
git checkout -B sync upstream/master
git push origin sync --force
- name: Copy master -> apk-build
run: |
git checkout -B apk-build master
git checkout -B apk-build sync
git push origin apk-build --force
- name: Apply sneed changes
@@ -46,4 +48,4 @@ jobs:
- name: Push apk build
run: |
git push origin build --force
git push origin apk-build --force
-2
View File
@@ -11,13 +11,11 @@ build/
build-*/
**/result
__pycache__/
*.so
a.out
*.pgm
*.zip
*.keystore
*.pftrace
gradle.properties
local.properties
compile_commands.json
-1
View File
@@ -30,7 +30,6 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Required for WiFi locking, see https://developer.android.com/reference/android/net/wifi/WifiManager.WifiLock -->
+35 -37
View File
@@ -23,18 +23,11 @@ include(FetchContent)
include(ExternalProject)
include(GNUInstallDirs)
set(GIT_TAG "" CACHE STRING "Build for a tag (from git if empty)")
set(GIT_DESC "" CACHE STRING "Version to show in UI (from git if empty, exclusive with GIT_TAG)")
set(GIT_COMMIT "" CACHE STRING "Git SHA used to fetch client APK (from git if empty, exclusive with GIT_TAG)")
if (GIT_TAG AND (GIT_DESC OR GIT_COMMIT))
message(FATAL_ERROR "cannot use GIT_DESC or GIT_COMMIT when using GIT_TAG")
endif()
option(WIVRN_USE_SYSTEM_FREETYPE "Use system FreeType" ON)
option(WIVRN_USE_SYSTEM_BOOST "Use system Boost headers" ON)
option(WIVRN_USE_SYSTEM_OPENXR "Use system OpenXR headers" ON)
option(WIVRN_USE_SYSTEM_LIBKTX "Use system KTX-Software library" ON)
option(WIVRN_USE_SYSTEMD "Use libsystemd" ON)
option(WIVRN_COMPRESS_GLB "Compress textures in GLB files with gltf-transform" OFF)
option(WIVRN_USE_ANDROID_VALIDATION_LAYER "Download the android version of the Vulkan validation layer" OFF)
option(WIVRN_USE_ANDROID_BIN_LIBKTX "Download the prebuilt libktx for android" OFF)
@@ -48,7 +41,6 @@ option(WIVRN_BUILD_TEST "Build test binaries" OFF)
option(WIVRN_WERROR "Treat warnings as errors" OFF)
option(WIVRN_OPTIMIZE_SHADERS "Run spirv-opt on compiled shaders" ON)
option(WIVRN_DEBUG_SHADERS "Compile shaders with debug information" OFF)
option(WIVRN_ADDRESS_SANITIZER "Use address sanitizer" OFF)
if(WIVRN_OPTIMIZE_SHADERS AND WIVRN_DEBUG_SHADERS)
message(FATAL_ERROR "WIVRN_OPTIMIZE_SHADERS and WIVRN_DEBUG_SHADERS are incompatible")
@@ -59,15 +51,10 @@ option(WIVRN_USE_VAAPI "Enable vaapi (AMD/Intel) hardware encoder" ON)
option(WIVRN_USE_VULKAN_ENCODE "Enable vulkan video encoder" ON)
option(WIVRN_USE_X264 "Enable x264 software encoder" ON)
option(WIVRN_USE_PERFETTO "Enable Perfetto tracing via the Perfetto SDK (server only)" OFF)
option(WIVRN_TRACE_MONADO "Also instrument Monado (percetto) under the same WIVRN_TRACING switch; pulls in a second Perfetto runtime, system backend only. Requires WIVRN_USE_PERFETTO" OFF)
if(WIVRN_TRACE_MONADO AND NOT WIVRN_USE_PERFETTO)
message(FATAL_ERROR "WIVRN_TRACE_MONADO=ON requires WIVRN_USE_PERFETTO=ON")
endif()
option(WIVRN_USE_PIPEWIRE "Enable pipewire backend" ON)
option(WIVRN_USE_PULSEAUDIO "Enable pulseaudio backend" OFF)
set(OVR_COMPAT_SEARCH_PATH "/opt/xrizer:/usr/local/lib/OpenComposite:/usr/lib/OpenComposite:/opt/OpenComposite:/opt/opencomposite:/opt/VapoR:/usr/local/lib/VapoR"
set(OVR_COMPAT_SEARCH_PATH "/opt/xrizer:/usr/local/lib/OpenComposite:/usr/lib/OpenComposite:/opt/OpenComposite:/opt/opencomposite"
CACHE STRING "List of places to search for the OpenVR compatibility layer, separated by :")
option(WIVRN_FEATURE_DEBUG_GUI "Enable Monado debug GUI" OFF)
@@ -89,7 +76,7 @@ option(WIVRN_OPENXR_MANIFEST_ABI "Generate an ABI specific OpenXR manifest")
option(ENABLE_COLOURED_OUTPUT "Always produce ANSI-coloured output (GNU/Clang only)." ON)
set(WIVRN_ENVIRONMENTS_URL "https://github.com/Vindicus999/WiVRn-environments/releases/latest/download/index.json" CACHE STRING "URL hosting the custom environments json file")
set(WIVRN_ENVIRONMENTS_URL "https://github.com/WiVRn/WiVRn-environments/releases/latest/download/index.json" CACHE STRING "URL hosting the custom environments json file")
if (WIVRN_BUILD_CLIENT OR WIVRN_BUILD_SERVER OR WIVRN_BUILD_DASHBOARD OR WIVRN_BUILD_DISSECTOR)
set(NEED_COMMON TRUE)
@@ -114,7 +101,7 @@ endif()
include(VulkanVersion)
if (WIVRN_USE_SYSTEM_BOOST AND NEED_COMMON)
if (WIVRN_BUILD_DISSECTOR OR WIVRN_BUILD_CLIENT)
if (WIVRN_BUILD_DISSECTOR)
find_package(Boost 1.84.0 REQUIRED COMPONENTS locale url iostreams)
else()
find_package(Boost 1.75.0 REQUIRED COMPONENTS locale url iostreams)
@@ -123,8 +110,8 @@ endif()
if (WIVRN_BUILD_SERVER)
find_program(GDBUS_CODEGEN gdbus-codegen REQUIRED)
if (Vulkan_VERSION VERSION_LESS "1.4.304")
message(FATAL_ERROR "Vulkan version must be at least 1.4.304, found ${Vulkan_VERSION}")
if (Vulkan_VERSION VERSION_LESS "1.3.261")
message(FATAL_ERROR "Vulkan version must be at least 1.3.261, found ${Vulkan_VERSION}")
endif()
if (NOT WIVRN_USE_NVENC AND NOT WIVRN_USE_VAAPI AND NOT WIVRN_USE_X264 AND NOT WIVRN_USE_VULKAN_ENCODE)
@@ -136,14 +123,28 @@ if (WIVRN_BUILD_SERVER)
pkg_check_modules(LIBDRM REQUIRED IMPORTED_TARGET libdrm)
endif()
if (WIVRN_USE_VULKAN_ENCODE)
if (Vulkan_VERSION VERSION_LESS 1.3.283)
message(FATAL_ERROR "Vulkan video encode requires 1.3.283, found ${Vulkan_VERSION}")
endif()
endif()
if (WIVRN_USE_X264)
pkg_check_modules(X264 REQUIRED IMPORTED_TARGET x264)
endif()
if (WIVRN_USE_SYSTEMD)
pkg_check_modules(SYSTEMD REQUIRED IMPORTED_TARGET libsystemd)
endif()
if (WIVRN_USE_PIPEWIRE)
pkg_check_modules(libpipewire REQUIRED IMPORTED_TARGET libpipewire-0.3)
endif()
if (WIVRN_USE_PULSEAUDIO)
pkg_check_modules(libpulse REQUIRED IMPORTED_TARGET libpulse)
endif()
pkg_check_modules(AVAHI REQUIRED IMPORTED_TARGET avahi-client avahi-glib)
find_package(Eigen3 REQUIRED)
find_package(nlohmann_json REQUIRED)
@@ -184,7 +185,7 @@ endif()
if (WIVRN_BUILD_CLIENT)
find_program(RSVG_CONVERT rsvg-convert REQUIRED)
find_program(KTX ktx REQUIRED)
find_program(TOKTX toktx REQUIRED)
if (WIVRN_COMPRESS_GLB)
find_program(GLTF_TRANSFORM gltf-transform REQUIRED)
@@ -200,7 +201,7 @@ if (WIVRN_BUILD_CLIENT AND NOT ANDROID)
find_package(Fontconfig REQUIRED)
if (WIVRN_USE_SYSTEM_OPENXR)
find_package(OpenXR 1.1.58 REQUIRED)
find_package(OpenXR 1.1.53 REQUIRED)
endif()
if (WIVRN_USE_SYSTEM_LIBKTX)
@@ -238,8 +239,8 @@ FetchContent_Declare(fastgltf EXCLUDE_FROM_ALL SYSTEM URL https://github.co
URL_HASH SHA256=0bb564e127b14c22f062db50f89381dd2e0a20dbaf4987ca138a4ae8728712f9)
FetchContent_Declare(glm EXCLUDE_FROM_ALL SYSTEM URL https://github.com/g-truc/glm/releases/download/1.0.2/glm-1.0.2.zip
URL_HASH SHA256=77fff075c5ab0caf076fade41558c5458d9a242aba2b2076bb72008bdb51a35e)
FetchContent_Declare(openxr_loader EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/OpenXR-SDK/archive/refs/tags/release-1.1.58.tar.gz
URL_HASH SHA256=815b933219c398314366c289221526428418d799205a73a9640c97ca4242602b)
FetchContent_Declare(openxr_loader EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/OpenXR-SDK/archive/refs/tags/release-1.1.54.tar.gz
URL_HASH SHA256=2055688081066e37238be996534f349420ac52ed34f8514836704232121ee7f3)
FetchContent_Declare(spdlog EXCLUDE_FROM_ALL SYSTEM URL https://github.com/gabime/spdlog/archive/refs/tags/v1.16.0.tar.gz
URL_HASH SHA256=8741753e488a78dd0d0024c980e1fb5b5c85888447e309d9cb9d949bdb52aa3e)
FetchContent_Declare(stb EXCLUDE_FROM_ALL SYSTEM URL https://github.com/nothings/stb/archive/013ac3beddff3dbffafd5177e7972067cd2b5083.zip
@@ -249,17 +250,17 @@ set(KTX_VERSION_FULL "v${KTX_VERSION}")
FetchContent_Declare(libktx EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/KTX-Software/archive/refs/tags/${KTX_VERSION_FULL}.tar.gz
URL_HASH SHA256=9412cb45045a503005acd47d98f9e8b47154634a50b4df21e17a1dfa8971d323
)
FetchContent_Declare(implot EXCLUDE_FROM_ALL SYSTEM URL https://github.com/epezent/implot/releases/download/v1.0/implot-v1.0.tar.gz
URL_HASH SHA256=20ca14d5a46f36a650746096c74eba8bea99c9432cd3c877343b96b17a6ae566)
FetchContent_Declare(implot EXCLUDE_FROM_ALL SYSTEM URL https://github.com/epezent/implot/archive/3da8bd34299965d3b0ab124df743fe3e076fa222.zip
URL_HASH SHA256=e9b439a94aa6f09fcf12ed9c2cd784efe5e99e96242122aa683e690b29f7a59f)
file(GLOB IMGUI_PATCHES CONFIGURE_DEPENDS patches/imgui/*)
FetchContent_Declare(imgui EXCLUDE_FROM_ALL SYSTEM URL https://github.com/ocornut/imgui/archive/refs/tags/v1.92.9.tar.gz
URL_HASH SHA256=af97ed649182c39314320514a672b82008ab462b9293fe23d37b30bfa5d05519
FetchContent_Declare(imgui EXCLUDE_FROM_ALL SYSTEM URL https://github.com/ocornut/imgui/archive/refs/tags/v1.92.5.tar.gz
URL_HASH SHA256=0eb50fe9aeba1a51f96b5843c7f630a32ed2e9362d693c61b87e4fa870cf826d
PATCH_COMMAND ${CMAKE_CURRENT_LIST_DIR}/patches/apply.sh ${IMGUI_PATCHES}
)
FetchContent_Declare(uni-algo EXCLUDE_FROM_ALL SYSTEM URL https://github.com/uni-algo/uni-algo/archive/v1.2.0.tar.gz
URL_HASH SHA256=f2a1539cd8635bc6088d05144a73ecfe7b4d74ee0361fabed6f87f9f19e74ca9)
FetchContent_Declare(entt EXCLUDE_FROM_ALL SYSTEM URL https://github.com/skypjack/entt/archive/refs/tags/v4.0.0.tar.gz
URL_HASH SHA256=32a2ff2c72cb047dfd57306006ef238820b70da7c6ce4e7e8a507ac63365212e)
FetchContent_Declare(entt EXCLUDE_FROM_ALL SYSTEM URL https://github.com/skypjack/entt/archive/refs/tags/v3.16.0.tar.gz
URL_HASH SHA256=7d7b4037b737992342049ffab14f22fa10243e01664f8c3a0657aa247ac52f71)
FetchContent_Declare(curl EXCLUDE_FROM_ALL SYSTEM URL https://github.com/curl/curl/releases/download/curl-8_17_0/curl-8.17.0.tar.xz
URL_HASH SHA256=955f6e729ad6b3566260e8fef68620e76ba3c31acf0a18524416a185acf77992)
FetchContent_Declare(spirv-reflect EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/SPIRV-Reflect/archive/refs/tags/vulkan-sdk-1.4.328.1.tar.gz
@@ -284,7 +285,6 @@ add_custom_target(wivrn-version ALL
-D OUTPUT_FILE=${CMAKE_BINARY_DIR}/version.cpp
-D INPUT_FILE_1=${CMAKE_CURRENT_SOURCE_DIR}/server/u_git_tag.cpp.in
-D OUTPUT_FILE_1=${CMAKE_BINARY_DIR}/u_git_tag.cpp
-D GIT_TAG="${GIT_TAG}"
-D GIT_DESC="${GIT_DESC}"
-D GIT_COMMIT="${GIT_COMMIT}"
-P ${CMAKE_SOURCE_DIR}/cmake/GitVersion.cmake
@@ -302,7 +302,6 @@ if (WIVRN_BUILD_CLIENT)
endif()
if (WIVRN_BUILD_SERVER OR WIVRN_BUILD_SERVER_LIBRARY)
find_package(Python3 REQUIRED Interpreter)
add_subdirectory(server)
if (WIVRN_BUILD_SERVER)
@@ -314,6 +313,10 @@ if (WIVRN_BUILD_SERVER OR WIVRN_BUILD_SERVER_LIBRARY)
message(STATUS "")
message(STATUS "Audio backends:")
message(STATUS "\tPipewire : ${WIVRN_USE_PIPEWIRE}")
message(STATUS "\tPulseaudio: ${WIVRN_USE_PULSEAUDIO}")
message(STATUS "")
message(STATUS "Optional features:")
message(STATUS "\tsystemd: ${WIVRN_USE_SYSTEMD}")
endif()
endif()
@@ -343,10 +346,5 @@ foreach(TARGET_NAME wivrn wivrn-server wivrn-dashboard wivrn-common wivrn-dissec
target_compile_options(${TARGET_NAME} PRIVATE -Werror)
endif()
if (WIVRN_ADDRESS_SANITIZER AND NOT ${TARGET_NAME} STREQUAL wivrn-dissector)
target_compile_options(${TARGET_NAME} PRIVATE -fsanitize=address -fno-omit-frame-pointer)
target_link_options(${TARGET_NAME} PRIVATE -fsanitize=address)
endif()
endif()
endforeach()
+1 -28
View File
@@ -9,7 +9,6 @@
{
"name": "base",
"hidden": true,
"generator": "Ninja",
"cacheVariables": {
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
"CMAKE_INTERPROCEDURAL_OPTIMIZATION": "ON",
@@ -26,6 +25,7 @@
"WIVRN_USE_NVENC": "ON",
"WIVRN_USE_SYSTEMD": "ON",
"WIVRN_USE_SYSTEM_BOOST": "ON",
"WIVRN_USE_PULSEAUDIO": "ON",
"WIVRN_USE_PIPEWIRE": "ON",
"WIVRN_WERROR": "ON"
}
@@ -65,24 +65,6 @@
"WIVRN_BUILD_WIVRNCTL": "ON"
}
},
{
"name": "server-tracing",
"displayName": "Server with Perfetto tracing",
"inherits": "server",
"binaryDir": "${sourceDir}/build-server-tracing",
"cacheVariables": {
"WIVRN_USE_PERFETTO": "ON"
}
},
{
"name": "server-tracing-monado",
"displayName": "Server with Perfetto tracing (incl. Monado)",
"inherits": "server-tracing",
"binaryDir": "${sourceDir}/build-server-tracing-monado",
"cacheVariables": {
"WIVRN_TRACE_MONADO": "ON"
}
},
{
"name": "dashboard",
"displayName": "Dashboard only",
@@ -131,15 +113,6 @@
"WIVRN_USE_SYSTEMD": "OFF"
}
},
{
"name": "client-no-system-boost",
"displayName": "Client only (no system Boost)",
"inherits": "client",
"binaryDir": "${sourceDir}/build-client-no-system-boost",
"cacheVariables": {
"WIVRN_USE_SYSTEM_BOOST": "OFF"
}
},
{
"name": "server-no-system-boost",
"displayName": "Server only (no system Boost)",
+32 -42
View File
@@ -42,18 +42,15 @@ We recommend using native packages if available for your distribution:
- [Arch User Repository](https://aur.archlinux.org/packages/wivrn-dashboard)
- [Fedora](https://packages.fedoraproject.org/pkgs/wivrn/wivrn/)
- [Gentoo Guru](https://gitweb.gentoo.org/repo/proj/guru.git/tree/media-libs/wivrn)
- [NixOS](https://search.nixos.org/packages?show=wivrn)
- [Ubuntu PPA](https://launchpad.net/~lvra/+archive/ubuntu/wivrn)
- [NixOS](https://search.nixos.org/packages?channel=25.11&show=wivrn)
For OpenVR and Steam compatibility, you also need a compatibility library such as [xrizer](https://github.com/Supreeeme/xrizer/) or [OpenComposite](https://gitlab.com/znixian/OpenOVR/).
For OpenVR and Steam compatibility, you also need a [compatibility library](#openvr-and-steam-games) such as xrizer or OpenComposite.
A Flatpak is available on Flathub for all distributions:
A flatpak is available on Flathub for all distributions:
[![Flathub](https://flathub.org/api/badge)](https://flathub.org/apps/io.github.wivrn.wivrn)
The Flatpak contains both xrizer and OpenComposite.
Note that due to Flatpak sandboxing, some features such as support for SteamVR tracked (Lighthouse) devices, or virtual gamepad/keyboard/input devices forwarded from the headset, may not be available.
Note that due to flatpak sandboxing some features may not be available such as Lighthouse tracked devices.
## Headset Client/App
@@ -79,42 +76,34 @@ Avahi must be running:
systemctl enable --now avahi-daemon
```
On SteamOS, the Avahi configuration needs to be modified to allow user services such as WiVRn to publish services on the network; see https://github.com/WiVRn/WiVRn/issues/1001#issuecomment-4940906113 for instructions on how to do so.
- If a firewall is installed, open port 5353/UDP for Avahi and ports 9757/UDP+TCP for WiVRn.
- For example, if using UFW run `ufw allow 5353/udp` and `ufw allow 9757`.
### Start the PC server process
The graphical frontend is listed as "WiVRn server" in the application list, and is `wivrn-dashboard` on command line. On first start, a wizard will guide you through the initial steps.
### Running
- On your computer, run "WiVRn server" application, or `wivrn-dashboard` from the command line. It will show the setup wizard the first time you launch it.
- On your headset, run WiVRn from the App Library. If you are using a Meta Quest and you have installed it from an APK instead of the Meta Store, it should be in the "unknown sources" section.
- You should now see your computer in the list: click connect, the screen will show "Connection ready. Start a VR application on <i>\[your computer's name\]</i>".
The actual server for headless usage is `wivrn-server`. When installed through your distribution's package manager, a systemd user service named `wivrn` is also installed, which can be enabled to automatically start on login with `systemctl --user enable --now wivrn`.
You can now stream an OpenXR application from your computer to your headset. For Steam games, you may also need to set the launch options to be able to use WiVRn. The server/dashboard will tell you how to do this if required.
- Right-click on the game you want to play in VR in Steam and click "Properties".
- In the "General" tab, enter the launch options that the WiVRn server/dashboard gave you inside the "Launch Options" setting.
For Steam games, depending on the installation method, you may need to set launch options in the Steam properties for each game you want to run. Either the dashboard or command line output will display the launch command if it is required.
You can set an application to be started automatically when your headset is connected, in the dashboard settings or [manually](docs/configuration.md#application).
### Start the headset application
On the headset, when installed from the store, simply start `WiVRn`. If you installed the app via the dashboard, or manually via `adb`, it will be in an "unknown sources" section.
On first start, it will ask if you want to enable some features such as microphone, hand tracking, eye tracking, etc., as they will require permissions to be granted. It is possible to grant those later from the Settings tab.
It is highly recommended to use default settings and only tweak them if you experience issues.
### Connect to the server
The headset application will start on a server list. Your computer should be visible and have a connect button. Simply click it to start streaming.
When the headset is connected, wivrn-server sets the OpenXR and OpenVR configuration to use WiVRn. Thus, applications will only be able to run in VR once the headset connection is established. The configuration is reverted once the connection ends and all running VR applications are closed.
The headset connection also triggers the creation of a virtual speaker and, if enabled in the headset app settings, a microphone. You will have to set them as the default output and input devices in your system audio configuration. This setting persists to future sessions until you change the defaults to other devices.
### Start an application
### Application list
When the headset is connected and no XR application is running, it will show an application launcher. Applications in that list are sourced from:
- Steam games that are flagged as VR. Steam may need to be restarted for the list to be updated when new games are installed.
- .desktop files that contain `X-WiVRn-VR` in the `Categories` section. Files are searched in [standard locations](https://specifications.freedesktop.org/desktop-entry/latest/file-naming.html#desktop-file-id) which usually include `~/.local/share/applications` and `/usr/share/applications/`.
You can set an application to be started automatically when your headset is connected, in the dashboard settings or [manually](docs/configuration.md#application).
### OpenVR and Steam games
## Steam Flatpak
Flatpak applications are only able to access the Flatpak version of WiVRn.
The flatpak includes [OpenComposite](https://gitlab.com/znixian/OpenOVR/) and [xrizer](https://github.com/Supreeeme/xrizer/), used to translate the OpenVR API to OpenXR. see [SteamVR](docs/steamvr.md) for details.
If using Wine/Proton, it will probe for OpenVR at startup, This means even for OpenXR applications, OpenComposite or xrizer is required.
When a headset connects, wivrn-server sets the OpenVR runtime to xrizer unless manually configured differently.
### Steam Flatpak
If you're using the Steam Flatpak, you'll need to grant read only access to the following paths:
```bash
@@ -129,7 +118,11 @@ flatpak override \
When using a user installation of flatpak Steam, use `override --user` instead of `override`.
The same overrides should work for other VR applications distributed as Flatpaks.
### Audio
When the headset is connected, WiVRn will create a virtual output device simply named "WiVRn. You must manually set this audio output to enabled/default. Please note that in `pavucontrol` it will appear as a virtual device.
To enable microphone, you first have to enable it on the settings tab on the VR headset (and give permission when prompted). It should appear as a virtual input device named "WiVRn(microphone)", and needs to be assigned as the input device (same way as output device).
# Building
@@ -137,7 +130,9 @@ See [building](docs/building.md) for building the [dashboard](docs/building.md#d
# Configuration
Most settings are controlled through the headset app, while the server has configuration for items that are specific to the server. Use the dashboard to edit the latter, or see [configuration](docs/configuration.md) for editing it manually.
Configuration can be done from the dashboard.
See [configuration](docs/configuration.md) for editing the configuration manually.
# Troubleshooting
<details><summary>My computer is not seen by the headset</summary>
@@ -152,7 +147,7 @@ If the server list is empty in the headset app:
- If you have a firewall, check that port 9757 (UDP and TCP) is open
- The server and client must be the same version.</details>
<details><summary>How do I use a wired connection manually?</summary>
<details><summary>How do I use a wired connection?</summary>
- Make sure the WiVRn Server is installed and running on your computer
- Make sure you have the WiVRn app installed on your headset
@@ -170,14 +165,9 @@ If the server list is empty in the headset app:
<details><summary>How do I see server logs when using the dashboard?</summary>
- Click **Troubleshoot > Open server logs**
- Or, navigate to `${XDG_STATE_HOME}/wivrn/wivrn-dashboard`
- In other words, on common setups, the dashboard writes logs to `~/.local/state/wivrn/wivrn-dashboard`
- For WiVRn Flatpak, the dashboard writes logs to `~/.var/app/io.github.wivrn.wivrn/.local/state/wivrn/wivrn-dashboard`</details>
<details><summary>My NVIDIA GPU P-State is limited to P2 instead of reaching the highest P0 while using the NVIDIA NVENC encoder</summary>
- See [nvenc](docs/nvenc.md) for troubleshooting.</details>
- Click Troubleshoot > Open server logs, or
- Navigate to `${XDG_STATE_HOME}/wivrn/wivrn-dashboard` (with fallback to `${HOME}/.local/state` for `${XDG_STATE_HOME}`, or
- For flatpak, navigate to `${HOME}/.var/app/io.github.wivrn.wivrn/.local/state/wivrn/wivrn-dashboard`.</details>
<details><summary>I have high motion latency, black borders following my view, hear corrupted audio or see a corrupted, pixelated image</summary>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 856 B

After

Width:  |  Height:  |  Size: 930 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 292 B

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
+4 -17
View File
@@ -92,11 +92,11 @@ tasks.register("generatePngs", GeneratePngsTask) {
}
}
def use_asan = project.hasProperty('wivrn_address_sanitizer') && wivrn_address_sanitizer == 'ON'
android {
namespace = "org.meumeu.wivrn"
ndkVersion = "29.0.14206865"
ndkVersion = "28.2.13676358"
lint {
disable += "ExpiredTargetSdkVersion"
@@ -117,20 +117,16 @@ android {
def compressGlb = project.hasProperty('wivrn_compress_glb') ? wivrn_compress_glb : 'OFF'
def fetchcontentBaseDir = project.hasProperty('fetchcontent_base_dir') ? ['-DFETCHCONTENT_BASE_DIR=' + fetchcontent_base_dir] : []
def asan = use_asan ? 'ON': 'OFF'
def stl = use_asan ? 'c++_shared' : "c++_static"
externalNativeBuild {
def css = project.hasProperty('wivrn_css') ? project.wivrn_css: "images/wivrn-local.css"
cmake {
arguments = ['-DANDROID_TOOLCHAIN=clang',
'-DANDROID_STL=' + stl,
'-DANDROID_STL=c++_static',
'-DCMAKE_ANDROID_NDK_VERSION=' + ndkVersion,
'-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON',
'-DCMAKE_EXPORT_COMPILE_COMMANDS=ON',
'-DCMAKE_ANDROID_ASSETS_DIRECTORIES=' + layout.buildDirectory.dir("assets").get().asFile,
'-DRESOURCES_DIRECTORIES=' + layout.buildDirectory.dir("resources").get().asFile,
'-DWIVRN_USE_SYSTEM_BOOST=OFF',
'-DWIVRN_USE_SYSTEM_FREETYPE=OFF',
'-DWIVRN_USE_ANDROID_BIN_LIBKTX=ON',
@@ -143,20 +139,13 @@ android {
'-DWIVRN_SHOW_IMGUI_DEMO_WINDOW=' + showImguiDemo,
'-DWIVRN_CLIENT_DEBUG_MENU=' + showDebugMenu,
'-DWIVRN_CSS=' + css,
'-DWIVRN_COMPRESS_GLB=' + compressGlb,
'-DWIVRN_ADDRESS_SANITIZER=' + asan,
] +
'-DWIVRN_COMPRESS_GLB=' + compressGlb] +
fetchcontentBaseDir
resValue "string", "app_name", project.hasProperty('wivrn_app_name') ? project.wivrn_app_name : "WiVRn Local"
abiFilters 'arm64-v8a'//, 'x86_64'
}
}
packaging {
jniLibs {
useLegacyPackaging = use_asan
}
}
}
signingConfigs {
@@ -237,7 +226,6 @@ android {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['client/java']
res.srcDirs = [ 'resources', layout.buildDirectory.dir('generated_resources') ]
resources.srcDirs = [layout.buildDirectory.dir('resources')]
assets.srcDirs = ['assets', layout.buildDirectory.dir("assets")]
}
@@ -255,6 +243,5 @@ android {
applicationVariants.all { variant ->
// It probably works with merge${variant.name.capitalize()}Assets too
tasks["generate${variant.name.capitalize()}Assets"].dependsOn "externalNativeBuild${variant.name.capitalize()}"
tasks["merge${variant.name.capitalize()}Resources"].dependsOn "externalNativeBuild${variant.name.capitalize()}"
}
}
+10 -20
View File
@@ -38,7 +38,6 @@ add_library(stb INTERFACE)
target_include_directories(stb INTERFACE ${stb_SOURCE_DIR})
if(ANDROID)
file(REMOVE_RECURSE ${RESOURCES_DIRECTORIES}/lib ${ANDROID_LIB_DIRECTORIES})
add_library(wivrn MODULE)
find_library(ANDROID_LIBRARY NAMES android REQUIRED)
@@ -81,23 +80,6 @@ if(ANDROID)
"decoder/android/*.cpp"
)
target_sources(wivrn PRIVATE ${PLATFORM_SOURCE})
if (WIVRN_ADDRESS_SANITIZER)
file(MAKE_DIRECTORY
${RESOURCES_DIRECTORIES}/lib/${CMAKE_ANDROID_ARCH_ABI}
${ANDROID_LIB_DIRECTORIES}/${CMAKE_ANDROID_ARCH_ABI})
file(GLOB _asan_location
${ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/lib/clang/*/lib/linux/libclang_rt.asan-${CMAKE_SYSTEM_PROCESSOR}-android.so
)
file(COPY
${_asan_location}
DESTINATION ${ANDROID_LIB_DIRECTORIES}/${CMAKE_ANDROID_ARCH_ABI}
)
file(COPY_FILE
${ANDROID_NDK}/wrap.sh/asan.sh
${RESOURCES_DIRECTORIES}/lib/${CMAKE_ANDROID_ARCH_ABI}/wrap.sh
)
endif()
else()
add_executable(wivrn)
@@ -124,6 +106,8 @@ endif()
#
target_compile_definitions(wivrn PRIVATE "XR_USE_TIMESPEC=1")
set_target_properties(wivrn PROPERTIES CXX_VISIBILITY_PRESET hidden)
file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS
"*.cpp"
"decoder/*.cpp"
@@ -160,7 +144,6 @@ target_link_libraries(wivrn
target_compile_definitions(wivrn PRIVATE -DXR_USE_GRAPHICS_API_VULKAN)
target_compile_definitions(wivrn PRIVATE -DVMA_STATS_STRING_ENABLED=0)
target_compile_definitions(wivrn PRIVATE -DGLM_ENABLE_EXPERIMENTAL)
target_compile_definitions(wivrn PRIVATE IMGUI_DEFINE_MATH_OPERATORS)
target_include_directories(wivrn PRIVATE .)
@@ -231,6 +214,9 @@ if(WIVRN_USE_ANDROID_VALIDATION_LAYER)
file(COPY
${FETCHCONTENT_BASE_DIR}/Vulkan-ValidationLayer/android-binaries-${VVL_VERSION}/${CMAKE_ANDROID_ARCH_ABI}
DESTINATION ${ANDROID_LIB_DIRECTORIES})
else()
# silence "Manually-specified variables were not used by the project" warning
set(_unused ${ANDROID_LIB_DIRECTORIES})
endif()
@@ -276,10 +262,14 @@ set(IMAGES_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../images)
set(ASSETS_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../assets-source)
wivrn_rasterize_svg(SOURCE ${IMAGES_SRC_DIR}/wivrn.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/wivrn.png WIDTH 540 HEIGHT 540 CSS ${WIVRN_CSS_ABS})
wivrn_rasterize_svg(SOURCE ${IMAGES_SRC_DIR}/wivrn-pride.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/wivrn-pride.png WIDTH 540 HEIGHT 540 CSS ${WIVRN_CSS_ABS})
wivrn_rasterize_svg(SOURCE ${IMAGES_SRC_DIR}/wivrn-christmas.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/wivrn-christmas.png WIDTH 540 HEIGHT 540 CSS ${WIVRN_CSS_ABS})
wivrn_rasterize_svg(SOURCE ${ASSETS_SRC_DIR}/passthrough.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/passthrough.png WIDTH 256 HEIGHT 256)
wivrn_rasterize_svg(SOURCE ${ASSETS_SRC_DIR}/default-environment.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/default-environment.png WIDTH 256 HEIGHT 256)
wivrn_generate_ktx( SOURCE ${CMAKE_CURRENT_BINARY_DIR}/wivrn.png DESTINATION ${ASSETS_DIR}/wivrn.ktx2 TARGET wivrn)
wivrn_generate_ktx( SOURCE ${CMAKE_CURRENT_BINARY_DIR}/wivrn-pride.png DESTINATION ${ASSETS_DIR}/wivrn-pride.ktx2 TARGET wivrn)
wivrn_generate_ktx( SOURCE ${CMAKE_CURRENT_BINARY_DIR}/wivrn-christmas.png DESTINATION ${ASSETS_DIR}/wivrn-christmas.ktx2 TARGET wivrn)
wivrn_generate_ktx( SOURCE ${ASSETS_SRC_DIR}/default_icon.png DESTINATION ${ASSETS_DIR}/default_icon.ktx2 TARGET wivrn)
wivrn_generate_ktx( SOURCE ${CMAKE_CURRENT_BINARY_DIR}/passthrough.png DESTINATION ${ASSETS_DIR}/passthrough.ktx2 TARGET wivrn)
wivrn_generate_ktx( SOURCE ${CMAKE_CURRENT_BINARY_DIR}/default-environment.png DESTINATION ${ASSETS_DIR}/default-environment.ktx2 TARGET wivrn)
@@ -300,7 +290,7 @@ wivrn_webxr_controller(PROFILE pico-4 DESTINATION ${ASSETS_DIR}
wivrn_webxr_controller(PROFILE pico-4u DESTINATION ${ASSETS_DIR}/controllers TARGET wivrn)
wivrn_webxr_controller(PROFILE pico-neo3 DESTINATION ${ASSETS_DIR}/controllers TARGET wivrn)
wivrn_webxr_controller(PROFILE samsung-galaxyxr DESTINATION ${ASSETS_DIR}/controllers TARGET wivrn)
wivrn_webxr_controller(PROFILE yvr-touch-v2 DESTINATION ${ASSETS_DIR}/controllers TARGET wivrn)
# Add the VR splash screen (only used on Quest)
if(ANDROID)
+1 -1
View File
@@ -35,7 +35,7 @@ battery_status get_battery_status()
return last_status;
}
extern "C" void Java_org_meumeu_wivrn_BroadcastReceiver_onReceive(JNIEnv * env, jobject instance, jobject ctxt_obj, jobject intent_obj)
extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_BroadcastReceiver_onReceive(JNIEnv * env, jobject instance, jobject ctxt_obj, jobject intent_obj)
{
jni::jni_thread::setup_thread(env);
jni::object<"android/content/Intent"> intent{intent_obj};
+4 -1
View File
@@ -2,7 +2,10 @@ LIBAPP {
global:
ANativeActivity_onCreate;
android_main;
Java_org_meumeu_wivrn*;
Java_org_meumeu_wivrn_BroadcastReceiver_onReceive;
Java_org_meumeu_wivrn_MainActivity_onRequestPermissionsResult;
Java_org_meumeu_wivrn_MainActivity_onActivityResult;
Java_org_meumeu_wivrn_MainActivity_onNewIntent;
local:
*;
};
+1 -8
View File
@@ -249,13 +249,10 @@ bool android_hid::input_handler::handle_input(scene * current_scene, AInputEvent
{
const int32_t type = AInputEvent_getType(event);
const int32_t src = AInputEvent_getSource(event);
const int32_t dev = AInputEvent_getDeviceId(event);
if (type == AINPUT_EVENT_TYPE_KEY)
{
// Gamepad input is read through the OpenXR microsoft/xbox_controller profile, not here.
if ((src & AINPUT_SOURCE_GAMEPAD) == AINPUT_SOURCE_GAMEPAD)
return false;
int32_t flags = AKeyEvent_getFlags(event);
if ((flags & AKEY_EVENT_FLAG_SOFT_KEYBOARD) != 0)
return false; // ignore soft keyboards
@@ -291,10 +288,6 @@ bool android_hid::input_handler::handle_input(scene * current_scene, AInputEvent
if (type == AINPUT_EVENT_TYPE_MOTION)
{
// Gamepad axes are read through the OpenXR microsoft/xbox_controller profile, not here.
if ((src & AINPUT_SOURCE_JOYSTICK) == AINPUT_SOURCE_JOYSTICK)
return false;
// don't care about absolute mouse due to mapping difficulties
if ((src & AINPUT_SOURCE_MOUSE_RELATIVE) == 0)
return false;
+1 -1
View File
@@ -59,7 +59,7 @@ jni::object<"android/net/Uri"> intent::get_uri()
return obj.call<jni::object<"android/net/Uri">>("getData");
}
extern "C" void Java_org_meumeu_wivrn_MainActivity_onActivityResult(JNIEnv * env, jobject instance, int request_code, int result_code, jobject data_obj)
extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onActivityResult(JNIEnv * env, jobject instance, int request_code, int result_code, jobject data_obj)
{
auto it = callbacks.find(request_code);
if (it == callbacks.end())
-11
View File
@@ -89,7 +89,6 @@ struct Void
struct Int
{
constexpr static auto static_field = &_JNIEnv::GetStaticIntField;
constexpr static auto obj_field = &_JNIEnv::GetIntField;
constexpr static const auto call_method = &_JNIEnv::CallIntMethod;
constexpr static const auto call_static_method = &_JNIEnv::CallStaticIntMethod;
@@ -278,7 +277,6 @@ struct object
}
std::unique_ptr<std::remove_pointer_t<jobject>, details::deleter> self;
constexpr static auto obj_field = &_JNIEnv::GetObjectField;
constexpr static const auto call_method = &_JNIEnv::CallObjectMethod;
constexpr static const auto call_static_method = &_JNIEnv::CallStaticObjectMethod;
@@ -337,14 +335,6 @@ struct object
handles));
}
template <typename T>
T field(const std::string & name)
{
auto & env = jni_thread::env();
jfieldID id = env.GetFieldID(klass(), name.c_str(), T::type().c_str());
return T((env.*T::obj_field)(*this, id));
}
jobject handle() const
{
return *this;
@@ -384,7 +374,6 @@ struct string : public string_t
{
using string_t::type;
constexpr static auto static_field = &_JNIEnv::GetStaticObjectField;
constexpr static auto obj_field = &_JNIEnv::GetObjectField;
operator jstring()
{
+1 -1
View File
@@ -93,7 +93,7 @@ void request_permission(const char * permission, std::function<void(bool)> callb
}
}
extern "C" void Java_org_meumeu_wivrn_MainActivity_onRequestPermissionsResult(
extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onRequestPermissionsResult(
JNIEnv * env,
jobject instance,
int requestCode,
-61
View File
@@ -1,61 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "application.h"
#include "jni.h"
#include <atomic>
#include <spdlog/spdlog.h>
std::atomic_bool link_properties_changed = false;
extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onAvailable(JNIEnv * env, jobject instance, jobject network)
{
spdlog::info("NetworkInfoCallback_onAvailable");
}
extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onBlockedStatusChanged(JNIEnv * env, jobject instance, jobject network, jboolean blocked)
{
spdlog::info("NetworkInfoCallback_onBlockedStatusChanged");
}
extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onCapabilitiesChanged(JNIEnv * env, jobject instance, jobject network, jobject caps)
{
spdlog::info("NetworkInfoCallback_onCapabitilitiesChanged");
}
extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onLinkPropertiesChanged(JNIEnv * env, jobject instance, jobject network, jobject jprops)
{
link_properties_changed = true;
}
extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onLosing(JNIEnv * env, jobject instance, jobject network, jint ms)
{
spdlog::info("NetworkInfoCallback_onLosing");
}
extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onLost(JNIEnv * env, jobject instance, jobject network)
{
spdlog::info("NetworkInfoCallback_onLost");
link_properties_changed = true;
}
extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onUnavailable(JNIEnv * env, jobject instance)
{
spdlog::info("NetworkInfoCallback_onUnavailable");
application::get_config().usb_network = false;
}
bool usb_link_properties_changed()
{
return link_properties_changed.exchange(false);
}
+50 -160
View File
@@ -19,6 +19,7 @@
#include "application.h"
#include "hardware.h"
#include "openxr/openxr.h"
#include "scene.h"
#include "spdlog/common.h"
@@ -34,12 +35,12 @@
#include "xr/check.h"
#include "xr/htc_exts.h"
#include "xr/htc_face_tracker.h"
#include "xr/meta_body_tracking_fidelity.h"
#include "xr/to_string.h"
#include <algorithm>
#include <boost/locale.hpp>
#include <boost/url/parse.hpp>
#include <chrono>
#include <cstring>
#include <ctype.h>
#include <exception>
#include <magic_enum.hpp>
@@ -477,47 +478,6 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/squeeze/value",
},
},
interaction_profile{
.profile_name = "/interaction_profiles/yvr/touch_controller_yvr",
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
"/user/hand/left/input/grip/pose",
"/user/hand/left/input/aim/pose",
"/user/hand/right/input/grip/pose",
"/user/hand/right/input/aim/pose",
"/user/hand/left/input/x/click",
"/user/hand/left/input/x/touch",
"/user/hand/left/input/y/click",
"/user/hand/left/input/y/touch",
"/user/hand/left/input/menu/click",
"/user/hand/left/input/squeeze/value",
"/user/hand/left/input/squeeze/click",
"/user/hand/left/input/trigger/value",
"/user/hand/left/input/trigger/touch",
"/user/hand/left/input/thumbstick",
"/user/hand/left/input/thumbstick/click",
"/user/hand/left/input/thumbstick/touch",
"/user/hand/left/input/thumbrest/touch",
"/user/hand/right/input/a/click",
"/user/hand/right/input/a/touch",
"/user/hand/right/input/b/click",
"/user/hand/right/input/b/touch",
"/user/hand/right/input/system/click",
"/user/hand/right/input/squeeze/value",
"/user/hand/right/input/squeeze/click",
"/user/hand/right/input/trigger/value",
"/user/hand/right/input/trigger/touch",
"/user/hand/right/input/thumbstick",
"/user/hand/right/input/thumbstick/click",
"/user/hand/right/input/thumbstick/touch",
"/user/hand/right/input/thumbrest/touch",
},
},
interaction_profile{
.profile_name = "/interaction_profiles/htc/vive_focus3_controller",
.required_extensions = {XR_HTC_VIVE_FOCUS3_CONTROLLER_INTERACTION_EXTENSION_NAME},
@@ -603,35 +563,6 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/eyes_ext/input/gaze_ext/pose",
},
},
interaction_profile{
.profile_name = "/interaction_profiles/microsoft/xbox_controller",
.input_sources = {
"/user/gamepad/input/menu/click",
"/user/gamepad/input/view/click",
"/user/gamepad/input/a/click",
"/user/gamepad/input/b/click",
"/user/gamepad/input/x/click",
"/user/gamepad/input/y/click",
"/user/gamepad/input/dpad_up/click",
"/user/gamepad/input/dpad_down/click",
"/user/gamepad/input/dpad_left/click",
"/user/gamepad/input/dpad_right/click",
"/user/gamepad/input/shoulder_left/click",
"/user/gamepad/input/shoulder_right/click",
"/user/gamepad/input/thumbstick_left/click",
"/user/gamepad/input/thumbstick_right/click",
"/user/gamepad/input/trigger_left/value",
"/user/gamepad/input/trigger_right/value",
"/user/gamepad/input/thumbstick_left/x",
"/user/gamepad/input/thumbstick_left/y",
"/user/gamepad/input/thumbstick_right/x",
"/user/gamepad/input/thumbstick_right/y",
"/user/gamepad/output/haptic_left",
"/user/gamepad/output/haptic_right",
"/user/gamepad/output/haptic_left_trigger",
"/user/gamepad/output/haptic_right_trigger",
},
},
};
static const std::pair<std::string_view, XrActionType> action_suffixes[] =
@@ -664,15 +595,11 @@ static const std::pair<std::string_view, XrActionType> action_suffixes[] =
{"/ready_ext", XR_ACTION_TYPE_BOOLEAN_INPUT},
// Output paths
{"/haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_trigger", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_trigger_fb", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_thumb", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_thumb_fb", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_left", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_right", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_left_trigger", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_right_trigger",XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_trigger", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_trigger_fb",XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_thumb", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_thumb_fb", XR_ACTION_TYPE_VIBRATION_OUTPUT},
// clang-format on
};
@@ -822,13 +749,17 @@ void application::initialize_vulkan()
instance_extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
}
if (!strcmp(i.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) and get_hmd_traits().vk_debug_ext_allowed)
if (!strcmp(i.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) and
guess_model() != model::oculus_quest) // Quest 1 lies, the extension won't load
{
debug_utils_found = true;
instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
#endif
}
std::ranges::sort(extensions);
for (const auto & [extension_name, spec_version]: extensions)
spdlog::info(" {} (version {})", extension_name, spec_version);
vk_device_extensions.push_back(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME);
vk_device_extensions.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
@@ -850,19 +781,6 @@ void application::initialize_vulkan()
instance_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME);
#endif
std::ranges::sort(extensions);
for (const auto & [extension_name, spec_version]: extensions)
{
if (runtime_hmd_traits.blacklisted_extensions.contains(extension_name))
{
spdlog::info(" {} (version {}) (blacklisted)", extension_name, spec_version);
if (std::ranges::find(instance_extensions, extension_name) != instance_extensions.end())
throw std::runtime_error("Required Vulkan instance extension is blacklisted");
}
else
spdlog::info(" {} (version {})", extension_name, spec_version);
}
vk::ApplicationInfo application_info{
.pApplicationName = app_info.name.c_str(),
.applicationVersion = (uint32_t)app_info.version,
@@ -922,19 +840,9 @@ void application::initialize_vulkan()
spdlog::info("Available Vulkan device extensions:");
for (const auto & [extension_name, spec_version]: extensions)
{
if (runtime_hmd_traits.blacklisted_extensions.contains(extension_name))
{
spdlog::info(" {} (version {}) (blacklisted)", extension_name, spec_version);
if (std::ranges::find(vk_device_extensions, extension_name) != instance_extensions.end())
throw std::runtime_error("Required Vulkan device extension is blacklisted");
}
else
{
spdlog::info(" {} (version {})", extension_name, spec_version);
if (auto it = optional_device_extensions.find(extension_name); it != optional_device_extensions.end())
vk_device_extensions.push_back(it->data());
}
spdlog::info(" {} (version {})", extension_name, spec_version);
if (auto it = optional_device_extensions.find(extension_name); it != optional_device_extensions.end())
vk_device_extensions.push_back(it->data());
}
spdlog::info("Initializing Vulkan with device {}", physical_device_properties.deviceName.data());
@@ -1098,8 +1006,21 @@ void application::initialize_actions()
profile.available = std::ranges::all_of(profile.required_extensions, [&](auto & ext) { return xr_instance.has_extension(ext); }) and
profile.min_version <= api_version;
if (profile.profile_name.ends_with("khr/simple_controller") and not get_hmd_traits().bind_simple_controller)
profile.available = false;
if (profile.profile_name.ends_with("khr/simple_controller"))
{
switch (guess_model())
{
// Quest hand tracking creates a fake khr/simple_controller when hand tracking
// is enabled, this messes with native hand tracking
case model::meta_quest_3:
case model::meta_quest_pro:
case model::meta_quest_3s:
case model::oculus_quest_2:
profile.available = false;
default:
break;
}
}
if (!profile.available)
continue;
@@ -1107,8 +1028,21 @@ void application::initialize_actions()
// Patch profile to add grip_surface or palm_ext
bool add_palms = true;
if (profile.profile_name.ends_with("ext/hand_interaction_ext"))
add_palms = get_hmd_traits().hand_interaction_grip_surface;
{
switch (guess_model())
{
// Quest breaks spec and does not support grip_surface for ext/hand_interaction_ext
case model::meta_quest_3:
case model::meta_quest_pro:
case model::meta_quest_3s:
case model::oculus_quest_2:
case model::oculus_quest:
add_palms = false;
break;
default:
break;
}
}
if (add_palms)
{
if ((api_version >= XR_MAKE_VERSION(1, 1, 0) or xr_instance.has_extension(XR_KHR_MAINTENANCE1_EXTENSION_NAME)) //
@@ -1278,7 +1212,6 @@ void application::initialize_actions()
void application::initialize()
{
runtime_hmd_traits.init();
// LogLayersAndExtensions
assert(!xr_instance);
std::vector<const char *> xr_extensions{
@@ -1297,7 +1230,6 @@ void application::initialize()
XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME,
XR_EXT_HAND_INTERACTION_EXTENSION_NAME,
XR_EXT_HAND_TRACKING_EXTENSION_NAME,
XR_FB_HAND_TRACKING_MESH_EXTENSION_NAME,
XR_EXT_PALM_POSE_EXTENSION_NAME,
XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME,
XR_EXT_USER_PRESENCE_EXTENSION_NAME,
@@ -1332,7 +1264,7 @@ void application::initialize()
auto it = std::find_if(opt_extensions.begin(),
opt_extensions.end(),
[&ext](const char * i) { return strcmp(i, ext.extensionName) == 0; });
if (it != opt_extensions.end() and not runtime_hmd_traits.blacklisted_extensions.contains(ext.extensionName))
if (it != opt_extensions.end())
xr_extensions.push_back(*it);
}
@@ -1404,12 +1336,7 @@ void application::initialize()
spaces[size_t(xr::spaces::view)] = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_VIEW);
spaces[size_t(xr::spaces::world)] = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_STAGE);
config.emplace(xr_system_id, xr_session, application::get_config_path() / "client.json");
default_config.emplace(xr_system_id, xr_session);
#ifdef __ANDROID__
set_usb_networking(config->usb_network);
#endif
config.emplace(xr_system_id, xr_session);
// HTC face tracker fails if created later
// we can destroy it right away, it actually stores static handles
@@ -1491,7 +1418,7 @@ std::pair<XrAction, XrActionType> application::get_action(std::string_view reque
}
#ifdef __ANDROID__
extern "C" void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj)
extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj)
{
jni::jni_thread::setup_thread(env);
jni::object<"android/content/Intent"> intent{intent_obj};
@@ -1681,9 +1608,6 @@ void application::cleanup()
#ifdef __ANDROID__
jni::jni_thread::detach();
app_info.native_app->onAppCmd = nullptr;
app_info.native_app->onInputEvent = nullptr;
app_info.native_app->userData = nullptr;
#endif
}
@@ -1779,10 +1703,8 @@ void application::run()
while (ALooper_pollOnce(100, nullptr, &events, (void **)&source) >= 0)
{
// Process this event.
if (source == nullptr)
continue;
source->process(app_info.native_app, source);
if (source != nullptr)
source->process(app_info.native_app, source);
}
if (app_info.native_app->destroyRequested)
@@ -1834,38 +1756,6 @@ void application::push_scene(std::shared_ptr<scene> s)
instance().scene_stack.push_back(std::move(s));
}
#ifdef __ANDROID__
void application::set_usb_networking(bool enabled)
{
jni::object<""> act(app_info.native_app->activity->clazz);
auto app = act.call<jni::object<"android/app/Application">>("getApplication");
auto ctx = app.call<jni::object<"android/content/Context">>("getApplicationContext");
auto system_service = ctx.call<jni::object<"java/lang/Object">>("getSystemService", jni::string("connectivity"));
auto cb = act.field<jni::object<"android/net/ConnectivityManager$NetworkCallback">>("netcb");
try
{
if (enabled)
{
auto req = jni::new_object<"android/net/NetworkRequest$Builder">()
.call<jni::object<"android/net/NetworkRequest$Builder">>("removeCapability", jni::Int(12) /*NET_CAPABILITY_INTERNET*/)
.call<jni::object<"android/net/NetworkRequest$Builder">>("removeCapability", jni::Int(14) /*NET_CAPABILITY_TRUSTED*/)
.call<jni::object<"android/net/NetworkRequest$Builder">>("addTransportType", jni::Int(8) /*TRANSPORT_USB*/)
.call<jni::object<"android/net/NetworkRequest">>("build");
// system_service.call<void>("requestNetwork", req, jni::new_object<"org/meumeu/wivrn/NetworkInfoCallback">());
system_service.call<void>("requestNetwork", req, cb);
}
else
{
system_service.call<void>("unregisterNetworkCallback", cb);
}
}
catch (...)
{}
}
#endif
void application::poll_actions()
{
std::array<XrActionSet, 2> action_sets{
+8 -30
View File
@@ -25,7 +25,6 @@
#endif
#include "configuration.h"
#include "hmd_traits.h"
#include "utils/singleton.h"
#include "utils/thread_safe.h"
#include "vk/vk_allocator.h"
@@ -55,7 +54,7 @@
class scene;
#ifdef __ANDROID__
extern "C" void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj);
extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj);
#endif
struct application_info
@@ -75,9 +74,8 @@ class application : public singleton<application>
{
friend class scene;
private:
#ifdef __ANDROID__
friend void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj);
friend __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj);
#endif
application_info app_info;
@@ -156,11 +154,9 @@ private:
std::chrono::nanoseconds last_scene_cpu_time;
std::optional<configuration> config;
std::optional<configuration> default_config;
boost::locale::generator gen;
boost::locale::gnu_gettext::messages_info messages_info;
hmd_traits runtime_hmd_traits;
private:
void loop();
@@ -207,11 +203,6 @@ public:
{
return instance().app_info.native_app;
}
static android_hid::input_handler & get_input_handler()
{
return instance().input_handler;
}
#endif
static bool is_session_running()
@@ -312,10 +303,6 @@ public:
return *instance().wifi;
}
#ifdef __ANDROID__
void set_usb_networking(bool enabled);
#endif
static void ignore_debug_reports_for(void * object)
{
#ifndef NDEBUG
@@ -335,9 +322,8 @@ public:
template <typename T>
static void set_debug_reports_name(const T & object, std::string name)
{
if (not vk_allocator::instance().has_debug_utils)
return;
// #ifndef NDEBUG
// if (instance().debug_utils_found)
const vk::DebugUtilsObjectNameInfoEXT name_info{
.objectType = T::objectType,
.objectHandle = (uint64_t)(typename T::NativeType)object,
@@ -345,6 +331,10 @@ public:
};
instance().vk_device.setDebugUtilsObjectNameEXT(name_info);
// printf("set_debug_reports_name %p, %s\n", object, name.c_str());
// instance().debug_report_object_name[(uint64_t)object] = std::move(name);
// #endif
}
static thread_safe<vk::raii::Queue> & get_queue()
@@ -412,12 +402,6 @@ public:
return instance().openxr_post_processing_supported;
}
static const hmd_traits & get_hmd_traits()
{
assert(instance().runtime_hmd_traits.is_initialized());
return instance().runtime_hmd_traits;
}
static auto & get_generic_trackers()
{
return instance().generic_trackers;
@@ -434,12 +418,6 @@ public:
return *instance().config;
}
static configuration & get_default_config()
{
assert(instance().default_config);
return *instance().default_config;
}
static XrSessionState get_session_state()
{
return instance().session_state;
+6 -2
View File
@@ -80,7 +80,11 @@ int32_t wivrn::android::audio::speaker_data_cb(AAudioStream * stream, void * use
{
// Buffer underrun: add 5ms buffer
size_t target_buffer_size = frame_size * AAudioStream_getSampleRate(stream) * 0.005;
#if __cpp_lib_shared_ptr_arrays >= 201707L
self->speaker_tmp.data.c = std::make_shared<uint8_t[]>(target_buffer_size, 0);
#else
self->speaker_tmp.data.c.reset(new uint8_t[target_buffer_size]());
#endif
self->speaker_tmp.payload = std::span(self->speaker_tmp.data.c.get(), target_buffer_size);
self->buffer_size_bytes += target_buffer_size;
spdlog::debug("Audio sync: underrun, add {} bytes buffer",
@@ -155,9 +159,9 @@ void wivrn::android::audio::build_microphone(AAudioStreamBuilder * builder, int3
AAudioStreamBuilder_setSharingMode(builder, AAUDIO_SHARING_MODE_EXCLUSIVE);
AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_I16);
if (application::get_config().mic_unprocessed_audio)
{
AAudioStreamBuilder_setInputPreset(builder, AAUDIO_INPUT_PRESET_UNPROCESSED);
else
AAudioStreamBuilder_setInputPreset(builder, AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION);
}
AAudioStreamBuilder_setDataCallback(builder, &microphone_data_cb, this);
AAudioStreamBuilder_setErrorCallback(builder, &microphone_error_cb, this);
+146 -213
View File
@@ -24,11 +24,7 @@
#include "wivrn_packets.h"
#include <fstream>
#include <functional>
#include <magic_enum.hpp>
#include <string_view>
#include <type_traits>
#include <vector>
#ifdef __ANDROID__
#include "android/permissions.h"
@@ -37,121 +33,6 @@
// If no refresh rate is configured, don't select a too high one
static const float max_default_rate = 100;
// key <-> member serialization descriptor for scalar settings (see config_fields()).
// The few settings that aren't scalars are handled explicitly in save()/load().
struct config_field
{
std::function<void(std::ostream &, const configuration &)> save;
std::function<void(simdjson::dom::element, configuration &)> load;
};
namespace
{
template <typename>
inline constexpr bool is_optional_v = false;
template <typename T>
inline constexpr bool is_optional_v<std::optional<T>> = true;
template <typename T>
struct remove_optional
{
using type = T;
};
template <typename T>
struct remove_optional<std::optional<T>>
{
using type = T;
};
std::ostream & operator<<(std::ostream & stream, feature f)
{
return stream << "\"" << magic_enum::enum_name(f) << "\"";
}
template <typename T>
void write_value(std::ostream & json, const T & value)
{
if constexpr (std::is_same_v<T, bool>)
json << std::boolalpha << value;
else if constexpr (std::is_same_v<T, std::string>)
json << json_string(value);
else if constexpr (std::is_enum_v<T>)
json << json_string(magic_enum::enum_name(value));
else if constexpr (std::is_integral_v<T>)
json << (uint64_t)value;
else // floating point
json << value;
}
template <typename T>
std::optional<T> read_value(simdjson::simdjson_result<simdjson::dom::element> val)
{
if constexpr (std::is_same_v<T, bool>)
{
if (val.is_bool())
return val.get_bool();
}
else if constexpr (std::is_same_v<T, std::string>)
{
if (val.is_string())
return std::string(std::string_view(val.get_string().value()));
}
else if constexpr (std::is_enum_v<T>)
{
if (val.is_string())
{
auto name = val.get_string().value();
for (const auto & [e, n]: magic_enum::enum_entries<T>())
if (name == n)
return e;
}
}
else if constexpr (std::is_integral_v<T>)
{
if (val.is_uint64())
return (T)val.get_uint64();
if (val.is_int64() and int64_t(val.get_int64()) >= 0)
return (T)val.get_int64();
}
else // floating point
{
if (val.is_double())
return (T)val.get_double();
if (val.is_int64())
return (T)val.get_int64();
if (val.is_uint64())
return (T)val.get_uint64();
}
return std::nullopt;
}
// build a field for a plain member: bool / float / integral / std::string / enum,
// optionally wrapped in std::optional (only written when set)
template <typename T>
config_field scalar(const char * key, T configuration::* member)
{
return {
.save = [key, member](std::ostream & json, const configuration & c) {
if constexpr (is_optional_v<T>)
{
if (c.*member)
{
json << ",\"" << key << "\":";
write_value(json, *(c.*member));
}
}
else
{
json << ",\"" << key << "\":";
write_value(json, c.*member);
} },
.load = [key, member](simdjson::dom::element root, configuration & c) {
if (auto v = read_value<typename remove_optional<T>::type>(root[key]))
c.*member = *v; },
};
}
} // namespace
bool configuration::check_feature(feature f) const
{
{
@@ -189,7 +70,7 @@ bool configuration::check_feature(feature f) const
}
}
#ifdef __ANDROID__
return check_permission(application::get_hmd_traits().permission_name(f));
return check_permission(permission_name(f));
#else
return true;
#endif
@@ -200,7 +81,7 @@ void configuration::set_feature(feature f, bool state)
#ifdef __ANDROID__
if (state)
{
request_permission(application::get_hmd_traits().permission_name(f), [this, f](bool granted) {
request_permission(permission_name(f), [this, f](bool granted) {
{
std::lock_guard lock(mutex);
features[f] = granted;
@@ -222,24 +103,42 @@ configuration::configuration(xr::system & system, xr::session & session)
{
passthrough_enabled = system.passthrough_supported() == xr::passthrough_type::color;
features[feature::hand_tracking] = system.hand_tracking_supported();
switch (guess_model())
{
case model::oculus_quest:
case model::oculus_quest_2:
case model::meta_quest_pro:
case model::meta_quest_3:
case model::meta_quest_3s:
high_power_mode = false;
break;
case model::pico_neo_3:
case model::pico_4:
case model::pico_4s:
case model::pico_4_pro:
case model::pico_4_enterprise:
case model::htc_vive_focus_3:
case model::htc_vive_xr_elite:
case model::htc_vive_focus_vision:
case model::lynx_r1:
case model::samsung_galaxy_xr:
case model::unknown:
high_power_mode = true;
break;
}
const auto & rates = session.get_refresh_rates();
preferred_refresh_rate = rates.empty() ? 0 : rates[0];
for (auto rate: rates)
{
if (rate >= max_default_rate)
break;
preferred_refresh_rate = rate;
}
}
configuration::configuration(xr::system & system, xr::session & session, const std::filesystem::path & config_path) :
configuration(system, session)
{
try
{
simdjson::dom::parser parser;
simdjson::dom::element root = parser.load(config_path.native());
simdjson::dom::element root = parser.load((application::get_config_path() / "client.json").native());
for (simdjson::dom::object i: simdjson::dom::array(root["servers"]))
{
server_data data{
@@ -258,53 +157,92 @@ configuration::configuration(xr::system & system, xr::session & session, const s
servers.emplace(data.service.txt["cookie"], data);
}
float default_refresh_rate = preferred_refresh_rate;
for (const auto & f: config_fields())
f.load(root, *this);
// refresh rate must be supported by this headset, otherwise fall back to the default
const auto & rates = session.get_refresh_rates();
if (preferred_refresh_rate != 0 and not utils::contains(rates, preferred_refresh_rate))
preferred_refresh_rate = default_refresh_rate;
if (auto val = root["body_parts"]; val.is_object())
if (auto val = root["preferred_refresh_rate"]; val.is_double())
{
for (const auto & [b, name]: magic_enum::enum_entries<wivrn::from_headset::body_part_mask>())
{
const auto & body_part = val[name];
if (!body_part.is_bool())
continue;
float f = val.get_double();
if (f == 0 or utils::contains(rates, f))
preferred_refresh_rate = f;
}
if (body_part.get_bool())
if (auto val = root["minimum_refresh_rate"]; val.is_double())
minimum_refresh_rate = val.get_double();
if (auto val = root["resolution_scale"]; val.is_double())
resolution_scale = val.get_double();
if (auto val = root["stream_scale"]; val.is_double())
stream_scale = val.get_double();
if (auto val = root["codec"]; val.is_string())
{
const auto codec_str = val.get_string().value();
for (const auto & [c, name]: magic_enum::enum_entries<wivrn::video_codec>())
{
if (codec_str == name)
{
body_part_mask |= std::to_underlying(b);
}
else
{
body_part_mask &= ~std::to_underlying(b);
codec = c;
}
}
}
// nested object
if (auto val = root["openxr_post_processing"]; val.is_object())
{
auto obj = val.get_object();
openxr_post_processing = {};
if (auto v = obj["super_sampling"]; v.is_int64())
openxr_post_processing.super_sampling = v.get_int64();
if (auto v = obj["sharpening"]; v.is_int64())
openxr_post_processing.sharpening = v.get_int64();
}
if (auto val = root["bit_depth"]; val.is_uint64())
bit_depth = val.get_uint64();
// feature flags, keyed by enum name
for (const auto & [f, name]: magic_enum::enum_entries<feature>())
if (auto val = root["bitrate_bps"]; val.is_number())
bitrate_bps = val.get_uint64();
if (auto val = root["enable_stream_gui"]; val.is_bool())
enable_stream_gui = val.get_bool();
if (auto val = root["openxr_post_processing"]; val.is_object())
parse_openxr_post_processing_options(val.get_object());
if (auto val = root["passthrough_enabled"]; val.is_bool())
passthrough_enabled = val.get_bool();
if (auto val = root["mic_unprocessed_audio"]; val.is_bool())
mic_unprocessed_audio = val.get_bool();
if (auto val = root["fb_lower_body"]; val.is_bool())
fb_lower_body = val.get_bool();
if (auto val = root["fb_hip"]; val.is_bool())
fb_hip = val.get_bool();
if (auto val = root["virtual_keyboard_layout"]; val.is_string())
virtual_keyboard_layout = val.get_string().value();
for (const auto & [i, name]: magic_enum::enum_entries<feature>())
{
if (auto val = root[name]; val.is_bool())
features[f] = val.get_bool();
features[i] = val.get_bool();
}
if (system.passthrough_supported() == xr::passthrough_type::none)
passthrough_enabled = false;
if (auto val = root["override_foveation_enable"]; val.is_bool())
override_foveation_enable = val.get_bool();
if (auto val = root["override_foveation_pitch"]; val.is_double())
override_foveation_pitch = val.get_double();
if (auto val = root["override_foveation_distance"]; val.is_double())
override_foveation_distance = val.get_double();
if (auto val = root["first_run"]; val.is_bool())
first_run = val.get_bool();
if (auto val = root["locale"]; val.is_string())
locale = val.get_string().value();
if (auto val = root["environment_model"]; val.is_string())
environment_model = (std::string_view)val.get_string();
if (auto val = root["high_power_mode"]; val.is_bool())
high_power_mode = val.get_bool();
if (auto val = root["extended_config"]; val.is_bool())
extended_config = val.get_bool();
}
catch (std::exception & e)
{
@@ -312,43 +250,27 @@ configuration::configuration(xr::system & system, xr::session & session, const s
}
}
const std::vector<config_field> & configuration::config_fields()
void configuration::parse_openxr_post_processing_options(simdjson::simdjson_result<simdjson::dom::object> openxr_post_processing_root)
{
static const std::vector<config_field> fields = {
scalar("resolution_scale", &configuration::resolution_scale),
scalar("bitrate_bps", &configuration::bitrate_bps),
scalar("enable_stream_gui", &configuration::enable_stream_gui),
scalar("app_list_view", &configuration::app_list_view),
scalar("app_icon_size", &configuration::app_icon_size),
scalar("theme_preset", &configuration::theme_preset),
scalar("theme_accent", &configuration::theme_accent),
scalar("theme_rounding", &configuration::theme_rounding),
scalar("theme_card_rounding", &configuration::theme_card_rounding),
scalar("theme_font_scale", &configuration::theme_font_scale),
scalar("theme_background_alpha", &configuration::theme_background_alpha),
scalar("passthrough_enabled", &configuration::passthrough_enabled),
scalar("mic_unprocessed_audio", &configuration::mic_unprocessed_audio),
scalar("forward_keyboard", &configuration::forward_keyboard),
scalar("forward_mouse", &configuration::forward_mouse),
scalar("forward_gamepad", &configuration::forward_gamepad),
scalar("virtual_keyboard_layout", &configuration::virtual_keyboard_layout),
scalar("override_foveation_enable", &configuration::override_foveation_enable),
scalar("override_foveation_pitch", &configuration::override_foveation_pitch),
scalar("override_foveation_distance", &configuration::override_foveation_distance),
scalar("first_run", &configuration::first_run),
scalar("locale", &configuration::locale),
scalar("environment_model", &configuration::environment_model),
scalar("high_power_mode", &configuration::high_power_mode),
scalar("fps_divider", &configuration::fps_divider),
scalar("extended_config", &configuration::extended_config),
scalar("preferred_refresh_rate", &configuration::preferred_refresh_rate),
scalar("minimum_refresh_rate", &configuration::minimum_refresh_rate),
scalar("stream_scale", &configuration::stream_scale),
scalar("codec", &configuration::codec),
scalar("bit_depth", &configuration::bit_depth),
scalar("usb_network", &configuration::usb_network),
};
return fields;
openxr_post_processing = {};
if (auto val = openxr_post_processing_root["super_sampling"]; val.is_int64())
openxr_post_processing.super_sampling = val.get_int64();
if (auto val = openxr_post_processing_root["sharpening"]; val.is_int64())
openxr_post_processing.sharpening = val.get_int64();
}
static std::ostream & operator<<(std::ostream & stream, feature f)
{
return stream << "\"" << magic_enum::enum_name(f) << "\"";
}
static std::ostream & write_openxr_post_processing(std::ofstream & stream, const configuration::openxr_post_processing_settings & openxr_post_processing)
{
stream << "{\"super_sampling\":" << openxr_post_processing.super_sampling;
stream << ",\"sharpening\":" << openxr_post_processing.sharpening;
stream << "}";
return stream;
}
void configuration::save()
@@ -380,18 +302,34 @@ void configuration::save()
std::ofstream json(application::get_config_path() / "client.json");
json << "{\"servers\":[" << servers_str << "]";
for (const auto & f: config_fields())
f.save(json, *this);
// nested object
json << ",\"openxr_post_processing\":{\"super_sampling\":" << openxr_post_processing.super_sampling;
json << ",\"sharpening\":" << openxr_post_processing.sharpening << "}";
// feature flags, keyed by enum name
json << ",\"preferred_refresh_rate\":" << preferred_refresh_rate;
if (minimum_refresh_rate)
json << ",\"minimum_refresh_rate\":" << *minimum_refresh_rate;
json << ",\"resolution_scale\":" << resolution_scale;
if (stream_scale)
json << ",\"stream_scale\":" << *stream_scale;
if (codec)
json << ",\"codec\":" << json_string(magic_enum::enum_name(*codec));
json << ",\"bit_depth\":" << (uint64_t)bit_depth;
json << ",\"bitrate_bps\":" << bitrate_bps;
json << ",\"openxr_post_processing\":";
write_openxr_post_processing(json, openxr_post_processing);
json << ",\"passthrough_enabled\":" << std::boolalpha << passthrough_enabled;
json << ",\"mic_unprocessed_audio\":" << std::boolalpha << mic_unprocessed_audio;
json << ",\"fb_lower_body\":" << std::boolalpha << fb_lower_body;
json << ",\"fb_hip\":" << std::boolalpha << fb_hip;
json << ",\"enable_stream_gui\":" << std::boolalpha << enable_stream_gui;
for (auto & [key, value]: features)
json << "," << key << ":" << std::boolalpha << value;
json << ",\"virtual_keyboard_layout\":" << json_string(virtual_keyboard_layout);
json << ",\"override_foveation_enable\":" << std::boolalpha << override_foveation_enable;
json << ",\"override_foveation_pitch\":" << override_foveation_pitch;
json << ",\"override_foveation_distance\":" << override_foveation_distance;
json << ",\"first_run\":" << std::boolalpha << first_run;
json << ",\"locale\":" << json_string(locale);
json << ",\"environment_model\":" << json_string(environment_model);
json << ",\"high_power_mode\":" << std::boolalpha << high_power_mode;
json << ",\"extended_config\":" << std::boolalpha << extended_config;
json << "}";
}
@@ -404,11 +342,6 @@ float configuration::get_stream_scale() const
{
if (stream_scale)
return *stream_scale;
return get_default_stream_scale();
}
float configuration::get_default_stream_scale() const
{
if (check_feature(feature::eye_gaze))
return 0.3;
return 0.5;
+8 -49
View File
@@ -19,18 +19,15 @@
#pragma once
#include "hardware.h"
#include "wivrn_discover.h"
#include "wivrn_packets.h"
#include <filesystem>
#include <map>
#include <mutex>
#include <optional>
#include <simdjson.h>
#include <string>
#include <type_traits>
#include <vector>
#include <openxr/openxr.h>
namespace xr
{
@@ -38,18 +35,6 @@ class session;
class system;
} // namespace xr
// key <-> member serialization descriptor, defined in configuration.cpp
struct config_field;
enum class feature
{
microphone,
hand_tracking,
eye_gaze,
face_tracking,
body_tracking,
};
class configuration
{
public:
@@ -66,7 +51,7 @@ public:
std::map<std::string, server_data> servers;
float preferred_refresh_rate = 0;
std::optional<float> minimum_refresh_rate;
float resolution_scale = 1.2;
float resolution_scale = 1.0;
std::optional<wivrn::video_codec> codec;
uint32_t bitrate_bps = 50'000'000;
uint8_t bit_depth = 10;
@@ -74,27 +59,11 @@ public:
bool passthrough_enabled = false;
bool mic_unprocessed_audio = false;
// Input forwarding, per device. Off by default; only effective if the server permits it.
bool forward_keyboard = false;
bool forward_mouse = false;
bool forward_gamepad = false;
std::underlying_type_t<wivrn::from_headset::body_part_mask> body_part_mask = ~0;
bool fb_lower_body = false;
bool fb_hip = true;
bool enable_stream_gui = true;
// application launcher: list vs grid, and grid icon size, 0 small 1 medium 2 large
bool app_list_view = false;
uint32_t app_icon_size = 0;
// interface theme, defaults match the built-in "Dark" preset and "Blue" accent
std::string theme_preset = "Dark";
std::string theme_accent = "Blue";
float theme_rounding = 8;
float theme_card_rounding = 14;
float theme_font_scale = 1.0;
float theme_background_alpha = 0.75;
// XR_FB_composition_layer_settings extension flags
struct openxr_post_processing_settings
{
@@ -111,10 +80,7 @@ public:
float override_foveation_pitch = -10 * M_PI / 180;
float override_foveation_distance = 3;
bool high_power_mode = true;
uint32_t fps_divider = 1;
bool usb_network = false;
bool high_power_mode;
// Allow unsafe config values
bool extended_config = false;
@@ -131,26 +97,19 @@ private:
std::map<feature, bool> features;
std::optional<float> stream_scale;
// table of scalar settings shared by save()/load(); non-scalar settings are explicit
static const std::vector<config_field> & config_fields();
void parse_openxr_post_processing_options(simdjson::simdjson_result<simdjson::dom::object> root);
public:
configuration(xr::system &, xr::session &);
configuration(xr::system &, xr::session &, const std::filesystem::path &);
configuration() = default;
void save();
void set_stream_scale(float);
float get_stream_scale() const;
float get_default_stream_scale() const;
uint32_t max_bitrate(bool extended) const
{
return extended ? 800'000'000u : 200'000'000u;
}
uint32_t max_bitrate() const
{
return max_bitrate(extended_config);
return extended_config ? 800'000'000u : 200'000'000u;
}
};
+25 -19
View File
@@ -64,13 +64,6 @@ constexpr float pointer_fading_distance = 40;
// Pointer color
constexpr uint32_t pointer_color = 0x40ffffff;
constexpr uint32_t pointer_color_border = 0xff000000;
// offset of a popup layer in front of its main GUI panel
constexpr glm::vec3 popup_position = {0, 0, 0.05};
// world-space offset of a hover tooltip layer from the hovered item
constexpr glm::vec3 tooltip_distance = {0, 0.004, 0.005};
} // namespace constants::gui
namespace constants::lobby
@@ -85,6 +78,7 @@ constexpr auto gui_pitches = std::to_array<std::pair<float, float>>({
{90, 78},
});
constexpr float keyboard_pitch = -0.6;
constexpr glm::vec3 popup_position = {0, 0, 0.05};
constexpr glm::vec3 keyboard_position = {0, -0.3, 0.1};
// Position of the near plane
@@ -105,6 +99,10 @@ constexpr float initial_gui_distance = 0.5;
// Skybox color
constexpr XrColor4f sky_color = {0, 0.25, 0.5, 1};
// Dimming scale/bias when a popup window is shown
constexpr XrColor4f dimming_scale = {0.5, 0.5, 0.5, 1};
constexpr XrColor4f dimming_bias = {0.25, 0.25, 0.25, 0};
// Z-indices of composition layers
constexpr int zindex_passthrough = -2;
constexpr int zindex_lobby = -1;
@@ -125,16 +123,24 @@ constexpr ImVec4 urgent_border_color = {8.f, .6f, 0.f, .8f};
// Dimming for the streamed video when the GUI is interactable
constexpr float dimming_scale = 0.4;
constexpr float dimming_bias = 0.01;
constexpr float gui_max_foveation_speed = 2; // Maximum speed (@ 1m) when changing the foveation distance with the thumbstick
constexpr float gui_min_foveation_distance = 0.5;
constexpr float gui_max_foveation_distance = 100;
constexpr float gui_min_foveation_pitch = -M_PI / 3;
constexpr float gui_max_foveation_pitch = M_PI / 3;
constexpr float gui_max_layer_speed = 10; // Maximum speed (@ 1m) when changing the GUI distance with the thumbstick
constexpr float gui_min_layer_distance = 0.5;
constexpr float gui_max_layer_distance = 3;
} // namespace constants::stream
namespace constants::style
{
constexpr ImVec2 window_padding = {20, 20};
constexpr float window_border_size = 2;
constexpr float window_rounding = 10;
constexpr ImVec2 tooltip_padding = {5, 5};
constexpr float tooltip_rounding = 0;
constexpr glm::vec3 tooltip_distance = {0, 0.004, 0.005};
constexpr ImVec2 button_size = {220, 80};
constexpr ImVec2 icon_button_size = {80, 80};
constexpr float connection_popup_width = 1000;
constexpr ImVec2 pin_entry_key_size = {90, 70};
constexpr ImVec2 pin_entry_item_spacing = {10, 10};
constexpr float pin_entry_popup_width = 3 * pin_entry_key_size.x + 2 * pin_entry_item_spacing.x;
} // namespace constants::style
+1 -3
View File
@@ -140,7 +140,7 @@ decoder::decoder(
// latency mode
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_WIDTH, width);
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_HEIGHT, height);
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_OPERATING_RATE, std::ceil(description.frame_rate));
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_OPERATING_RATE, std::ceil(description.fps));
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_PRIORITY, 0);
media_codec.reset(AMediaCodec_createDecoderByType(mime(description.codec[stream_index])));
@@ -195,8 +195,6 @@ decoder::decoder(
decoder::~decoder()
{
if (image_reader)
AImageReader_setImageListener(image_reader.get(), nullptr);
if (media_codec)
{
AMediaCodec_stop(media_codec.get());
+467
View File
@@ -0,0 +1,467 @@
/*
* WiVRn VR streaming
* Copyright (C) 2023 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2023 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "hardware.h"
#include <cstdlib>
#include <glm/ext/quaternion_trigonometric.hpp>
#include <stdexcept>
#include <string>
#include <spdlog/spdlog.h>
#ifdef __ANDROID__
#include "utils/wrap_lambda.h"
#include <sys/system_properties.h>
static std::string get_property(const char * property)
{
auto info = __system_property_find(property);
std::string result;
wrap_lambda cb = [&result](const char * name, const char * value, uint32_t serial) {
result = value;
};
__system_property_read_callback(info, cb.userdata_first(), cb);
return result;
}
#endif
static model guess_model_()
{
#ifdef __ANDROID__
const auto device = get_property("ro.product.device");
const auto manufacturer = get_property("ro.product.manufacturer");
const auto model = get_property("ro.product.model");
spdlog::info("Guessing HMD model from:");
spdlog::info(" ro.product.device = \"{}\":", device);
spdlog::info(" ro.product.manufacturer = \"{}\":", manufacturer);
spdlog::info(" ro.product.model = \"{}\":", model);
if (device == "monterey")
return model::oculus_quest;
if (device == "hollywood")
return model::oculus_quest_2;
if (device == "seacliff")
return model::meta_quest_pro;
if (device == "eureka")
return model::meta_quest_3;
if (device == "panther")
return model::meta_quest_3s;
if (model == "Lynx-R1")
return model::lynx_r1;
if (manufacturer == "Pico")
{
const auto pico_model = get_property("pxr.vendorhw.product.model");
spdlog::info(" pxr.vendorhw.product.model = \"{}\":", pico_model);
if (pico_model == "Pico Neo 3")
return model::pico_neo_3;
if (pico_model == "PICO 4")
return model::pico_4;
if (pico_model == "PICO 4 Ultra")
return model::pico_4s;
if (pico_model == "PICO 4 Pro")
return model::pico_4_pro;
if (pico_model == "PICO 4 Enterprise")
return model::pico_4_enterprise;
spdlog::info("manufacturer={}, model={}, device={}, pico_model={} assuming Pico 4", manufacturer, model, device, pico_model);
return model::pico_4;
}
if (manufacturer == "HTC")
{
if (model == "VIVE Focus 3")
return model::htc_vive_focus_3;
if (model == "VIVE Focus Vision")
return model::htc_vive_focus_vision;
if (model == "VIVE XR Series")
return model::htc_vive_xr_elite;
}
if (manufacturer == "samsung")
{
if (model == "SM-I610")
return model::samsung_galaxy_xr;
}
spdlog::info("Unknown model, manufacturer={}, model={}, device={}", manufacturer, model, device);
#endif
return model::unknown;
}
model guess_model()
{
static model m = guess_model_();
return m;
}
std::string model_name()
{
#ifdef __ANDROID__
const auto manufacturer = get_property("ro.product.manufacturer");
const auto model = get_property("ro.product.model");
return manufacturer + " " + model;
#else
return "Unknown headset";
#endif
}
static XrViewConfigurationView scale_view(XrViewConfigurationView view, uint32_t width)
{
double ratio = double(width) / view.recommendedImageRectWidth;
view.recommendedImageRectWidth = width;
view.recommendedImageRectHeight *= ratio;
spdlog::info("Using panel size: {}x{}", view.recommendedImageRectWidth, view.recommendedImageRectHeight);
return view;
}
XrViewConfigurationView override_view(XrViewConfigurationView view, model m)
{
// Standalone headsets tend to report a lower resolution
// as the GPU can't handle full res.
// Return the panel resolution instead.
spdlog::debug("Recommended image size: {}x{}", view.recommendedImageRectWidth, view.recommendedImageRectHeight);
switch (m)
{
case model::oculus_quest:
return scale_view(view, 1440);
case model::oculus_quest_2:
case model::meta_quest_3s:
return scale_view(view, 1832);
case model::meta_quest_pro:
return scale_view(view, 1800);
case model::meta_quest_3:
return scale_view(view, 2064);
case model::pico_neo_3:
return scale_view(view, 1832);
case model::pico_4:
case model::pico_4s:
case model::pico_4_pro:
case model::pico_4_enterprise:
return scale_view(view, 2160);
case model::htc_vive_focus_3:
case model::htc_vive_focus_vision:
return scale_view(view, 2448);
case model::htc_vive_xr_elite:
return scale_view(view, 1920);
case model::samsung_galaxy_xr:
return scale_view(view, 3552);
case model::lynx_r1:
case model::unknown:
return view;
}
throw std::range_error("invalid model " + std::to_string((int)m));
}
bool need_srgb_conversion(model m)
{
switch (m)
{
case model::lynx_r1:
return false;
case model::oculus_quest:
case model::oculus_quest_2:
case model::meta_quest_pro:
case model::meta_quest_3:
case model::meta_quest_3s:
case model::pico_neo_3:
case model::pico_4:
case model::pico_4s:
case model::pico_4_pro:
case model::pico_4_enterprise:
case model::htc_vive_focus_3:
case model::htc_vive_focus_vision:
case model::htc_vive_xr_elite:
case model::samsung_galaxy_xr:
case model::unknown:
return true;
}
throw std::range_error("invalid model " + std::to_string((int)m));
}
const char * permission_name(feature f)
{
switch (f)
{
case feature::microphone:
return "android.permission.RECORD_AUDIO";
case feature::hand_tracking:
switch (guess_model())
{
case model::samsung_galaxy_xr:
return "android.permission.HAND_TRACKING";
case model::oculus_quest:
case model::oculus_quest_2:
case model::meta_quest_pro:
case model::meta_quest_3:
case model::meta_quest_3s:
case model::pico_neo_3:
case model::pico_4:
case model::pico_4s:
case model::pico_4_pro:
case model::pico_4_enterprise:
case model::htc_vive_focus_3:
case model::htc_vive_focus_vision:
case model::htc_vive_xr_elite:
case model::lynx_r1:
case model::unknown:
break;
}
return nullptr;
case feature::eye_gaze:
switch (guess_model())
{
case model::oculus_quest:
case model::oculus_quest_2:
case model::meta_quest_pro:
case model::meta_quest_3:
case model::meta_quest_3s:
return "com.oculus.permission.EYE_TRACKING";
case model::pico_neo_3:
case model::pico_4:
case model::pico_4s:
case model::pico_4_pro:
case model::pico_4_enterprise:
return "com.picovr.permission.EYE_TRACKING";
case model::samsung_galaxy_xr:
return "android.permission.EYE_TRACKING_FINE";
case model::htc_vive_focus_3:
case model::htc_vive_focus_vision:
case model::htc_vive_xr_elite:
case model::lynx_r1:
case model::unknown:
return nullptr;
}
__builtin_unreachable();
case feature::face_tracking:
switch (guess_model())
{
case model::oculus_quest:
case model::oculus_quest_2:
case model::meta_quest_pro:
case model::meta_quest_3:
case model::meta_quest_3s:
return "com.oculus.permission.FACE_TRACKING";
case model::pico_neo_3:
case model::pico_4:
case model::pico_4s:
case model::pico_4_pro:
case model::pico_4_enterprise:
return "com.picovr.permission.FACE_TRACKING";
case model::samsung_galaxy_xr:
return "android.permission.FACE_TRACKING";
case model::htc_vive_focus_3:
case model::htc_vive_focus_vision:
case model::htc_vive_xr_elite:
case model::lynx_r1:
case model::unknown:
return nullptr;
}
__builtin_unreachable();
case feature::body_tracking:
switch (guess_model())
{
case model::meta_quest_3:
case model::meta_quest_3s:
return "com.oculus.permission.BODY_TRACKING";
default:
return nullptr;
}
}
__builtin_unreachable();
}
std::string controller_name()
{
#ifndef __ANDROID__
const char * controller = std::getenv("WIVRN_CONTROLLER");
if (controller && strcmp(controller, ""))
return controller;
#endif
switch (guess_model())
{
case model::oculus_quest:
return "oculus-touch-v2";
case model::oculus_quest_2:
return "oculus-touch-v3";
case model::meta_quest_pro:
return "meta-quest-touch-pro";
case model::meta_quest_3:
case model::meta_quest_3s:
return "meta-quest-touch-plus";
case model::pico_neo_3:
return "pico-neo3";
case model::pico_4:
case model::pico_4_pro:
case model::pico_4_enterprise:
return "pico-4";
case model::pico_4s:
return "pico-4u";
case model::htc_vive_focus_3:
case model::htc_vive_focus_vision:
case model::htc_vive_xr_elite:
return "htc-vive-focus-3";
case model::samsung_galaxy_xr:
return "samsung-galaxyxr";
case model::lynx_r1:
case model::unknown:
return "generic-trigger-squeeze";
}
__builtin_unreachable();
}
std::pair<glm::vec3, glm::quat> controller_offset(std::string_view profile, xr::spaces space)
{
#ifndef __ANDROID__
if (const char * offset = [space]() -> const char * {
switch (space)
{
case xr::spaces::grip_left:
return std::getenv("WIVRN_GRIP_LEFT_OFFSET");
case xr::spaces::grip_right:
return std::getenv("WIVRN_GRIP_RIGHT_OFFSET");
case xr::spaces::aim_left:
return std::getenv("WIVRN_AIM_LEFT_OFFSET");
case xr::spaces::aim_right:
return std::getenv("WIVRN_AIM_RIGHT_OFFSET");
default:
return nullptr;
}
}())
{
float x, y, z, yaw, pitch, roll;
if (sscanf(offset, "%f %f %f %f %f %f", &x, &y, &z, &yaw, &pitch, &roll) == 6)
{
return {{x, y, z},
glm::angleAxis(glm::radians(yaw), glm::vec3{0, 1, 0}) *
glm::angleAxis(glm::radians(pitch), glm::vec3{1, 0, 0}) *
glm::angleAxis(glm::radians(roll), glm::vec3{0, 0, 1})};
}
}
#endif
if (profile == "oculus-touch-v2")
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.006, -0.025}, glm::angleAxis(glm::radians(-15.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
return {{-0.010, 0, 0.02}, {1, 0, 0, 0}};
case xr::spaces::aim_right:
return {{0.010, 0, 0.02}, {1, 0, 0, 0}};
default:
break;
}
else if (profile == "meta-quest-touch-plus")
{
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.010, -0.025}, glm::angleAxis(glm::radians(-12.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
case xr::spaces::aim_right:
return {{0, 0, -0.03}, {1, 0, 0, 0}};
default:
break;
}
}
else if (profile == "htc-vive-focus-3")
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, 0.007, -0.030}, {1, 0, 0, 0}};
case xr::spaces::aim_left:
case xr::spaces::aim_right:
return {{0, -0.025, 0.005}, {1, 0, 0, 0}};
default:
break;
}
else if (profile == "pico-4" || profile == "pico-4s")
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.014, -0.048}, glm::angleAxis(glm::radians(-35.060f), glm::vec3{1, 0, 0})};
default:
break;
}
else if (profile == "pico-neo3")
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, 0.005, -0.051}, glm::angleAxis(glm::radians(-29.400f), glm::vec3{1, 0, 0})};
default:
break;
}
else if (profile == "samsung-galaxyxr")
switch (space)
{
case xr::spaces::grip_left:
return {{-0.005, 0.000, 0.035}, {1, 0, 0, 0}};
case xr::spaces::grip_right:
return {{0.005, 0.000, 0.035}, {1, 0, 0, 0}};
default:
break;
}
return {{0, 0, 0}, {1, 0, 0, 0}};
}
std::string controller_ray_model_name()
{
switch (guess_model())
{
case model::htc_vive_focus_3:
case model::htc_vive_focus_vision:
case model::htc_vive_xr_elite:
// XR Elite's runtime always assume alpha is unpremultiplied in the composition layers
// Assume it's the same for all HTC headsets
return "assets://ray-htc.glb";
default:
return "assets://ray.glb";
}
}
+69
View File
@@ -0,0 +1,69 @@
/*
* WiVRn VR streaming
* Copyright (C) 2023 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2023 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "xr/space.h"
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <string>
#include <utility>
#include <openxr/openxr.h>
enum class model
{
oculus_quest,
oculus_quest_2,
meta_quest_pro,
meta_quest_3,
meta_quest_3s,
pico_neo_3,
pico_4,
pico_4s,
pico_4_pro,
pico_4_enterprise,
htc_vive_focus_3,
htc_vive_xr_elite,
htc_vive_focus_vision,
lynx_r1,
samsung_galaxy_xr,
unknown
};
enum class feature
{
microphone,
hand_tracking,
eye_gaze,
face_tracking,
body_tracking,
};
model guess_model();
std::string model_name();
XrViewConfigurationView override_view(XrViewConfigurationView, model = guess_model());
bool need_srgb_conversion(model);
// Return nullptr if no permission is required
const char * permission_name(feature f);
std::string controller_name();
std::string controller_ray_model_name();
std::pair<glm::vec3, glm::quat> controller_offset(std::string_view profile, xr::spaces space);
-608
View File
@@ -1,608 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2023 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2023 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "hmd_traits.h"
#include "utils/overloaded.h"
#include "utils/strings.h"
#include "xr/to_string.h"
#include <boost/pfr.hpp>
#include <cassert>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <format>
#include <glm/ext/quaternion_trigonometric.hpp>
#include <limits>
#include <optional>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <spdlog/spdlog.h>
#ifdef __ANDROID__
#include "utils/wrap_lambda.h"
#include <sys/system_properties.h>
static std::optional<std::string> get_property(const char * property)
{
auto info = __system_property_find(property);
if (not info)
return std::nullopt;
std::string result;
wrap_lambda cb = [&result](const char * name, const char * value, uint32_t serial) {
result = value;
};
__system_property_read_callback(info, cb.userdata_first(), cb);
return result;
}
#endif
template <typename T>
std::optional<T> env(std::string_view name);
template <>
std::optional<std::string> env(std::string_view name)
{
#ifdef __ANDROID__
auto android_sysprop_name = std::format("debug.wivrn.{}", name);
return get_property(android_sysprop_name.c_str());
#else
std::string env_name = "WIVRN_";
env_name.reserve(env_name.size() + name.size());
for (const auto & c: name)
env_name += std::toupper(c);
const char * value = std::getenv(env_name.c_str());
if (value)
return value;
return std::nullopt;
#endif
}
template <>
std::optional<uint32_t> env(std::string_view name)
{
const auto value = env<std::string>(name);
if (not value)
return std::nullopt;
try
{
const unsigned long parsed = std::stoul(*value);
if (parsed > std::numeric_limits<uint32_t>::max())
return std::nullopt;
return static_cast<uint32_t>(parsed);
}
catch (std::runtime_error & e)
{
spdlog::warn("failed to parse {} (value: {}: {}", name, *value, e.what());
return std::nullopt;
}
}
template <>
std::optional<bool> env(std::string_view name)
{
const auto value = env<std::string>(name);
if (not value)
return std::nullopt;
if (strcmp(value->c_str(), "1") == 0 || strcasecmp(value->c_str(), "true") == 0 || strcasecmp(value->c_str(), "yes") == 0 || strcasecmp(value->c_str(), "on") == 0)
return true;
if (strcmp(value->c_str(), "0") == 0 || strcasecmp(value->c_str(), "false") == 0 || strcasecmp(value->c_str(), "no") == 0 || strcasecmp(value->c_str(), "off") == 0)
return false;
return std::nullopt;
}
template <>
std::optional<std::unordered_map<std::string, std::string>> env(std::string_view name)
{
const auto values = env<std::string>(name);
if (not values)
return std::nullopt;
std::unordered_map<std::string, std::string> map;
for (auto value: utils::split(*values, ","))
{
if (auto pos = value.find('='); pos != std::string::npos)
map.insert(std::make_pair(value.substr(0, pos), value.substr(pos + 1)));
}
return map;
}
template <>
std::optional<std::unordered_set<std::string>> env(std::string_view name)
{
const auto values = env<std::string>(name);
if (not values)
return std::nullopt;
return std::unordered_set<std::string>{std::from_range, utils::split(*values, ",")};
}
void hmd_traits::init()
{
#ifndef NDEBUG
assert(not initialized_);
initialized_ = true;
#endif
#ifdef __ANDROID__
const auto device = get_property("ro.product.device");
const auto manufacturer = get_property("ro.product.manufacturer");
const auto model = get_property("ro.product.model");
spdlog::info("Guessing HMD model from:");
spdlog::info(" ro.product.device = \"{}\":", device.value_or("<unset>"));
spdlog::info(" ro.product.manufacturer = \"{}\":", manufacturer.value_or("<unset>"));
spdlog::info(" ro.product.model = \"{}\":", model.value_or("<unset>"));
permissions[feature::microphone] = "android.permission.RECORD_AUDIO";
if (manufacturer == "Oculus")
{
permissions[feature::eye_gaze] = "com.oculus.permission.EYE_TRACKING";
permissions[feature::face_tracking] = "com.oculus.permission.FACE_TRACKING";
// Quest hand tracking creates a fake khr/simple_controller when hand tracking
// is enabled, this messes with native hand tracking
bind_simple_controller = false;
// Quest breaks spec and does not support grip_surface for ext/hand_interaction_ext
hand_interaction_grip_surface = false;
if (device == "monterey") // Quest 1
{
panel_width_override = 1440;
controller_profile = "oculus-touch-v2";
vk_debug_ext_allowed = false; // Quest 1 lies, the extension won't load
}
else if (device == "hollywood") // Quest 2
{
panel_width_override = 1832;
controller_profile = "oculus-touch-v3";
}
else if (device == "seacliff")
{
panel_width_override = 1800; // Quest pro
controller_profile = "meta-quest-touch-pro";
}
else if (device == "eureka")
{
panel_width_override = 2064; // Quest 3
controller_profile = "meta-quest-touch-plus";
usb_net = true;
}
else if (device == "panther") // Quest 3S
{
panel_width_override = 1832;
controller_profile = "meta-quest-touch-plus";
}
if (auto v = get_property("ro.hzos.build.display_name"))
{
auto digits = utils::split(*v, ".");
try
{
auto major = std::stoi(digits.at(0));
auto minor = std::stoi(digits.at(1));
usb_net = major > 2 or (major == 2 and minor >= 6);
}
catch (...)
{
spdlog::warn("Failed to parse Horizon OS version {}", *v);
}
}
}
else if (model == "Lynx-R1")
{
needs_srgb_conversion = false;
}
else if (manufacturer == "Play For Dream" and model == "PFDM MR")
{
controller_profile = "yvr-touch-v2";
}
else if (manufacturer == "Pico")
{
permissions[feature::eye_gaze] = "com.picovr.permission.EYE_TRACKING";
permissions[feature::face_tracking] = "com.picovr.permission.FACE_TRACKING";
view_locate = false;
discard_frame = false;
const auto pico_model = get_property("pxr.vendorhw.product.model");
spdlog::info(" pxr.vendorhw.product.model = \"{}\":", pico_model.value_or("<unset>"));
if (pico_model == "Pico Neo 3")
{
panel_width_override = 1832;
controller_profile = "pico-neo3";
}
else if (pico_model and pico_model->starts_with("PICO 4"))
{
panel_width_override = 2160;
if (pico_model == "PICO 4 Ultra")
controller_profile = "pico-4u";
else
controller_profile = "pico-4";
if (pico_model == "PICO 4 Pro" or pico_model == "PICO 4 Enterprise")
pico_face_tracker = true;
}
}
if (manufacturer == "HTC")
{
// Accepts OpenXR 1.1 but doesn't actually implement it
max_openxr_api_version = XR_API_VERSION_1_0;
// Doesn't handle additive blend, so needs specific ray model
// Fixed in XR elite firmware version 2.0
bool need_htc_ray = true;
const auto version = get_property("ro.product.version");
if (version)
{
auto digits = utils::split(*version, ".");
if (not digits.empty())
{
try
{
auto major = std::stoi(digits[0]);
if (major >= 2 and model == "VIVE XR Series")
need_htc_ray = false;
}
catch (...)
{}
}
}
if (need_htc_ray)
override_shader = {
{"ray.frag", "ray_htc.frag"},
{"ray_skinned.vert", "ray_skinned_htc.vert"},
{"ray.vert", "ray_htc.vert"},
};
controller_profile = "htc-vive-focus-3";
if (model == "VIVE Focus 3")
{
panel_width_override = 2448;
// Reports VK_EXT_debug_utils but does not expose vkSetDebugUtilsObjectNameEXT
vk_debug_ext_allowed = false;
}
if (model == "VIVE Focus Vision")
panel_width_override = 2448;
if (model == "VIVE XR Series")
panel_width_override = 1920;
}
if (manufacturer == "samsung")
{
if (model == "SM-I610") // Galaxy XR
{
panel_width_override = 3552;
controller_profile = "samsung-galaxyxr";
permissions[feature::hand_tracking] = "android.permission.HAND_TRACKING";
permissions[feature::eye_gaze] = "android.permission.EYE_TRACKING_FINE";
permissions[feature::face_tracking] = "android.permission.FACE_TRACKING";
}
}
#endif
spdlog::info("HMD traits initialized");
boost::pfr::for_each_field_with_name(
*this,
utils::overloaded{
[](std::string_view name, auto & field) {
if (auto val = env<std::remove_cvref_t<decltype(field)>>(name))
{
spdlog::info("\t{} override: {} -> {}", name, field, *val);
field = *val;
}
else
{
spdlog::info("\t{}: {}", name, field);
}
},
[](std::string_view name, XrVersion & field) {
if (auto val = env<std::string>(name))
{
XrVersion v;
if (val == "1.1")
v = XR_API_VERSION_1_1;
else if (val == "1.0")
v = XR_API_VERSION_1_0;
else
{
spdlog::warn("XrVersion {} not recognized", *val);
v = field;
}
spdlog::info("\t{} override: {} -> {}", name, xr::to_string(field), xr::to_string(v));
field = v;
}
else
{
spdlog::info("\t{}: {}", name, xr::to_string(field));
}
},
[](std::string_view name, std::unordered_map<std::string, std::string> & field) {
if (auto val = env<std::unordered_map<std::string, std::string>>(name))
{
for (const auto & [original, overridden]: *val)
field.insert_or_assign(original, overridden);
}
std::erase_if(field, [](const std::pair<std::string, std::string> & kv) { return kv.second == ""; });
for (const auto & [original, overridden]: field)
{
spdlog::info("\t{}: {} -> {}", name, original, overridden);
}
},
[](std::string_view name, std::unordered_set<std::string> & field) {
if (auto val = env<std::unordered_set<std::string>>(name))
{
for (const auto & i: *val)
{
if (i.starts_with("-"))
field.erase(i.substr(1));
else
field.insert(i);
}
}
for (const auto & i: field)
{
spdlog::info("\t{}: {}", name, i);
}
},
[](std::string_view, hmd_permissions) {},
});
}
static XrViewConfigurationView scale_view(XrViewConfigurationView view, uint32_t width)
{
double ratio = double(width) / view.recommendedImageRectWidth;
view.recommendedImageRectWidth = width;
view.recommendedImageRectHeight *= ratio;
spdlog::info("Using panel size: {}x{}", view.recommendedImageRectWidth, view.recommendedImageRectHeight);
return view;
}
std::string hmd_traits::model_name() const
{
#ifdef __ANDROID__
const auto manufacturer = get_property("ro.product.manufacturer").value_or("");
const auto model = get_property("ro.product.model").value_or("");
return manufacturer + " " + model;
#else
return "Unknown headset";
#endif
}
XrViewConfigurationView hmd_traits::override_view(XrViewConfigurationView view) const
{
// Standalone headsets tend to report a lower resolution
// as the GPU can't handle full res.
// Return the panel resolution instead.
spdlog::debug("Recommended image size: {}x{}", view.recommendedImageRectWidth, view.recommendedImageRectHeight);
if (panel_width_override > 0)
return scale_view(view, panel_width_override);
return view;
}
std::pair<glm::vec3, glm::quat> hmd_traits::controller_offset(xr::spaces space) const
{
#ifndef __ANDROID__
if (const char * offset = [space]() -> const char * {
switch (space)
{
case xr::spaces::grip_left:
return std::getenv("WIVRN_GRIP_LEFT_OFFSET");
case xr::spaces::grip_right:
return std::getenv("WIVRN_GRIP_RIGHT_OFFSET");
case xr::spaces::aim_left:
return std::getenv("WIVRN_AIM_LEFT_OFFSET");
case xr::spaces::aim_right:
return std::getenv("WIVRN_AIM_RIGHT_OFFSET");
default:
return nullptr;
}
}())
{
float x, y, z, yaw, pitch, roll;
if (sscanf(offset, "%f %f %f %f %f %f", &x, &y, &z, &yaw, &pitch, &roll) == 6)
{
return {{x, y, z},
glm::angleAxis(glm::radians(yaw), glm::vec3{0, 1, 0}) *
glm::angleAxis(glm::radians(pitch), glm::vec3{1, 0, 0}) *
glm::angleAxis(glm::radians(roll), glm::vec3{0, 0, 1})};
}
}
#endif
std::string_view profile = controller_profile;
if (profile == "oculus-touch-v2")
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.006, -0.025}, glm::angleAxis(glm::radians(-15.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
return {{-0.010, 0, 0.02}, {1, 0, 0, 0}};
case xr::spaces::aim_right:
return {{0.010, 0, 0.02}, {1, 0, 0, 0}};
default:
break;
}
else if (profile == "meta-quest-touch-plus")
{
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.006, -0.025}, glm::angleAxis(glm::radians(-14.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
return {{-0.010, 0, 0.02}, {1, 0, 0, 0}};
case xr::spaces::aim_right:
return {{0.010, 0, 0.02}, {1, 0, 0, 0}};
default:
break;
}
}
else if (profile == "meta-quest-touch-pro")
{
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, 0, 0}, glm::angleAxis(glm::radians(-20.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
return {{0, 0, 0}, {1, 0, 0, 0}};
case xr::spaces::aim_right:
return {{0, 0, 0}, {1, 0, 0, 0}};
default:
break;
}
}
else if (profile == "oculus-touch-v3")
{
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.003, -0.047}, glm::angleAxis(glm::radians(-20.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
return {{-0.006, 0, 0.015}, {1, 0, 0, 0}};
case xr::spaces::aim_right:
return {{0.006, 0, 0.015}, {1, 0, 0, 0}};
default:
break;
}
}
else if (profile == "pico-neo3")
{
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.016, -0.05}, glm::angleAxis(glm::radians(-15.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
case xr::spaces::aim_right:
return {{0, 0, 0}, {1, 0, 0, 0}};
default:
break;
}
}
else if (profile == "pico-4")
{
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.02, -0.05}, glm::angleAxis(glm::radians(-30.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
return {{-0.005, 0, 0.02}, {1, 0, 0, 0}};
case xr::spaces::aim_right:
return {{0.005, 0, 0.02}, {1, 0, 0, 0}};
default:
break;
}
}
else if (profile == "pico-4u")
{
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.042, -0.042}, glm::angleAxis(glm::radians(-8.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
return {{-0.005, 0, 0.02}, {1, 0, 0, 0}};
case xr::spaces::aim_right:
return {{0.005, 0, 0.02}, {1, 0, 0, 0}};
default:
break;
}
}
else if (profile == "htc-vive-focus-3")
{
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, 0, 0}, {1, 0, 0, 0}};
case xr::spaces::aim_left:
case xr::spaces::aim_right:
return {{0, -0.045, 0.035}, {1, 0, 0, 0}};
default:
break;
}
}
else if (profile == "samsung-galaxyxr")
{
switch (space)
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.01, -0.02}, glm::angleAxis(glm::radians(-20.f), glm::vec3{1, 0, 0})};
case xr::spaces::aim_left:
return {{-0.003, 0, 0.028}, {1, 0, 0, 0}};
case xr::spaces::aim_right:
return {{0.003, 0, 0.028}, {1, 0, 0, 0}};
default:
break;
}
}
return {{0, 0, 0}, {1, 0, 0, 0}};
}
-85
View File
@@ -1,85 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "configuration.h"
#include "xr/space.h"
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <magic_enum_containers.hpp>
#include <string>
#include <unordered_set>
#include <utility>
#include <openxr/openxr.h>
using hmd_permissions = magic_enum::containers::array<feature, const char *>;
class hmd_traits
{
public:
// Properties have the defaults below
// The cpp file has per-headset values
// it is possible to override values:
// on Android:
// adb setprop debug.wivrn.{property-name} {property-value}
// i.e. adb setprop debug.wivrn.view_locate false
// on Linux:
// export WIVRN_{PROPERTY-NAME}={property-value}
// i.e. export WIVRN_VIEW_LOCATE=false
std::string controller_profile = "generic-trigger-squeeze";
std::string controller_ray_model = "assets://ray.glb";
hmd_permissions permissions{};
XrVersion max_openxr_api_version = XR_API_VERSION_1_1;
uint32_t panel_width_override = 0;
bool needs_srgb_conversion = true;
bool view_locate = true; // can locate relative to view
bool vk_debug_ext_allowed = true;
bool bind_simple_controller = true;
bool hand_interaction_grip_surface = true;
bool pico_face_tracker = false;
bool discard_frame = true; // can do xrBeginFrame twice to discard the first one
bool usb_net = false;
std::unordered_map<std::string, std::string> override_shader;
std::unordered_set<std::string> blacklisted_extensions;
#ifndef NDEBUG
bool initialized_ = false;
#endif
public:
void init();
const char * permission_name(feature f) const
{
return permissions[f];
}
std::string model_name() const;
std::pair<glm::vec3, glm::quat> controller_offset(xr::spaces space) const;
XrViewConfigurationView override_view(XrViewConfigurationView) const;
bool is_initialized() const
{
#ifndef NDEBUG
return initialized_;
#else
return true;
#endif
}
};
-2
View File
@@ -17,7 +17,6 @@ public class MainActivity extends android.app.NativeActivity
public native void onActivityResult(int requestCode, int resultCode, android.content.Intent data);
private android.content.BroadcastReceiver BatteryInfoReceiver = null;
public android.net.ConnectivityManager.NetworkCallback netcb = null;
@Override
protected void onCreate(android.os.Bundle savedInstanceState)
@@ -25,7 +24,6 @@ public class MainActivity extends android.app.NativeActivity
super.onCreate(savedInstanceState);
this.BatteryInfoReceiver = new BroadcastReceiver();
this.netcb = new org.meumeu.wivrn.NetworkInfoCallback();
this.registerReceiver(this.BatteryInfoReceiver, new android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED));
}
-26
View File
@@ -1,26 +0,0 @@
package org.meumeu.wivrn;
public class NetworkInfoCallback extends android.net.ConnectivityManager.NetworkCallback
{
@Override
public native void onAvailable(android.net.Network network);
@Override
public native void onBlockedStatusChanged(android.net.Network network, boolean blocked);
@Override
public native void onCapabilitiesChanged(android.net.Network network, android.net.NetworkCapabilities caps);
@Override
public native void onLinkPropertiesChanged(android.net.Network network, android.net.LinkProperties props);
@Override
public native void onLosing(android.net.Network network, int maxMsToLive);
@Override
public native void onLost(android.net.Network network);
@Override
public native void onUnavailable();
}
+8 -15
View File
@@ -65,7 +65,7 @@ void libcurl::curl_thread_fn()
{
#ifdef __ANDROID__
// For Android, read all the certificates at start-up, the file names are not
// in the correct format for the current version of OpenSSL.
// in the correct format for the current verion of OpenSSL.
// See https://stackoverflow.com/questions/25253823/how-to-make-ssl-peer-verify-work-on-android
std::string ca_bundle;
for (const std::filesystem::directory_entry & entry: std::filesystem::directory_iterator{"/system/etc/security/cacerts"})
@@ -95,7 +95,7 @@ void libcurl::curl_thread_fn()
};
#endif
std::string user_agent = std::string("WiVRn/") + wivrn::display_version();
std::string user_agent = std::string("WiVRn/") + wivrn::git_version;
// We can't use auto here because of curl_easy_setopt
size_t (*write_callback)(void *, size_t, size_t, void *) = [](void * buffer, size_t size, size_t nmemb, void * userp) -> size_t {
@@ -158,10 +158,8 @@ void libcurl::curl_thread_fn()
if (msg->data.result == CURLE_OK)
{
if (xfer.finish())
xfer.current_state = state::done;
else
xfer.current_state = state::error;
xfer.current_state = state::done;
xfer.finish();
}
else
{
@@ -301,21 +299,17 @@ size_t libcurl::transfer_file::write(void * data, size_t size) noexcept
return size;
}
bool libcurl::transfer_file::finish() noexcept
void libcurl::transfer_file::finish() noexcept
{
stream.close();
std::error_code ec{};
std::filesystem::rename(temporary_path, final_path, ec);
if (ec)
return false;
std::filesystem::rename(temporary_path, final_path);
curl_off_t remote_timestamp;
if (curl_easy_getinfo(curl, CURLINFO_FILETIME_T, &remote_timestamp) == CURLE_OK)
{
auto time = std::chrono::file_clock::from_sys(std::chrono::system_clock::from_time_t(remote_timestamp));
std::filesystem::last_write_time(final_path, time, ec); // ignore errors
std::filesystem::last_write_time(final_path, time);
}
return true;
}
void libcurl::transfer_file::cancel() noexcept
@@ -349,9 +343,8 @@ size_t libcurl::transfer_buffer::write(void * data, size_t size) noexcept
return size;
}
bool libcurl::transfer_buffer::finish() noexcept
void libcurl::transfer_buffer::finish() noexcept
{
return true;
}
void libcurl::transfer_buffer::cancel() noexcept
+3 -4
View File
@@ -25,7 +25,6 @@
#include <filesystem>
#include <fstream>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <thread>
@@ -69,7 +68,7 @@ private:
virtual ~transfer();
virtual size_t write(void * data, size_t size) noexcept = 0;
virtual bool finish() noexcept = 0;
virtual void finish() noexcept = 0;
virtual void cancel() noexcept = 0;
};
@@ -82,7 +81,7 @@ private:
std::fstream stream;
size_t write(void * data, size_t size) noexcept override;
bool finish() noexcept override;
void finish() noexcept override;
void cancel() noexcept override;
};
@@ -93,7 +92,7 @@ private:
std::string buffer;
size_t write(void * data, size_t size) noexcept override;
bool finish() noexcept override;
void finish() noexcept override;
void cancel() noexcept override;
};
+1 -5
View File
@@ -20,7 +20,6 @@
#include "application.h"
#include "scenes/lobby.h"
#include "spdlog/spdlog.h"
#include "version.h"
#include <arpa/inet.h>
#include <netdb.h>
@@ -41,10 +40,6 @@ void real_main(android_app * native_app)
void real_main()
#endif
{
if (wivrn::is_tag)
spdlog::info("Starting WiVRn version {}", wivrn::display_version());
else
spdlog::info("Starting WiVRn version {} ({})", wivrn::display_version(), wivrn::git_commit);
try
{
application_info info;
@@ -89,6 +84,7 @@ void real_main()
}
#ifdef __ANDROID__
void android_main(android_app * native_app) __attribute__((visibility("default")));
void android_main(android_app * native_app)
{
static auto logger = spdlog::android_logger_mt("WiVRn", "WiVRn");
-7
View File
@@ -24,7 +24,6 @@
#include "vk/allocation.h"
#include <fastgltf/tools.hpp>
#include <fastgltf/types.hpp>
#include <span>
#include <vector>
#include <vulkan/vulkan.hpp>
@@ -91,12 +90,6 @@ public:
return add(alignment, data_to_add);
}
size_t add_indices(std::span<const uint16_t> indices)
{
usage |= vk::BufferUsageFlagBits::eIndexBuffer;
return add(4, indices.data(), indices.size_bytes());
}
std::pair<size_t, vk::IndexType> add_indices(const fastgltf::Accessor & accessor)
{
usage |= vk::BufferUsageFlagBits::eIndexBuffer;
+126 -69
View File
@@ -16,6 +16,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui_impl.h"
#include "implot.h"
@@ -23,7 +24,6 @@
#include "constants.h"
#include "image_loader.h"
#include "openxr/openxr.h"
#include "ui_theme.h"
#include "utils/mapped_file.h"
#include "utils/ranges.h"
#include "utils/strings.h"
@@ -182,7 +182,7 @@ static float distance_to_window(ImGuiWindow * window, ImVec2 position)
static const std::array layout_bindings = {
vk::DescriptorSetLayoutBinding{
.binding = 0,
.descriptorType = vk::DescriptorType::eSampledImage,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
}};
@@ -535,13 +535,11 @@ void imgui_context::initialize_fonts()
}
}
assert(font_awesome.empty());
font_awesome.emplace_back("assets://Font Awesome 7 Free-Regular-400.otf");
font_awesome.emplace_back("assets://Font Awesome 7 Free-Solid-900.otf");
font_awesome.emplace_back("assets://Font Awesome 7 Brands-Regular-400.otf");
utils::mapped_file font_awesome_regular("assets://Font Awesome 6 Free-Regular-400.otf");
utils::mapped_file font_awesome_solid("assets://Font Awesome 6 Free-Solid-900.otf");
ImFontConfig config;
config.FontDataOwnedByAtlas = true;
config.FontDataOwnedByAtlas = false;
for (auto & font: fonts)
{
@@ -550,11 +548,10 @@ void imgui_context::initialize_fonts()
config.MergeMode = true;
}
config.FontDataOwnedByAtlas = false;
config.MergeMode = true;
config.GlyphMinAdvanceX = 40; // Use if you want to make the icon monospaced
for (auto & fa: font_awesome)
io.Fonts->AddFontFromMemoryTTF(const_cast<std::byte *>(fa.data()), fa.size(), constants::gui::font_size_small, &config);
io.Fonts->AddFontFromMemoryTTF(const_cast<std::byte *>(font_awesome_regular.data()), font_awesome_regular.size(), constants::gui::font_size_small, &config);
io.Fonts->AddFontFromMemoryTTF(const_cast<std::byte *>(font_awesome_solid.data()), font_awesome_solid.size(), constants::gui::font_size_small, &config);
}
std::vector<imgui_context::controller_state> imgui_context::read_controllers_state(XrTime display_time)
@@ -936,28 +933,6 @@ std::vector<std::pair<int, XrCompositionLayerQuad>> imgui_context::end_frame()
}
}
if (auto modal_popup = ImGui::GetTopMostAndVisiblePopupModal(); modal_popup != nullptr)
{
ImDrawList * draw_list = ImGui::GetForegroundDrawList();
for (ImGuiWindow * window: context->Windows)
{
if (window == modal_popup or window->ParentWindow != nullptr or not window->Active or window->Hidden or window->IsFallbackWindow)
continue;
static const auto virtual_keyboard_id = ImHashStr("VirtualKeyboard");
if (window->ID == virtual_keyboard_id)
continue;
ImRect window_rect{
window->Pos.x,
window->Pos.y,
window->Pos.x + window->Size.x,
window->Pos.y + window->Size.y};
draw_list->AddRectFilled(window_rect.Min, window_rect.Max, ImGui::ColorConvertFloat4ToU32(wivrn::ui::current().dimming), window->WindowRounding);
}
}
ImGui::Render();
current_command_buffer = (current_command_buffer + 1) % command_buffers.size();
@@ -1172,12 +1147,12 @@ imgui_context::~imgui_context()
ImGui::DestroyContext(context);
}
ImTextureID imgui_textures::load_texture(const std::string & filename)
ImTextureID imgui_textures::load_texture(const std::string & filename, vk::raii::Sampler && sampler)
{
return load_texture(utils::mapped_file{filename}, filename);
return load_texture(utils::mapped_file{filename}, std::move(sampler), filename);
}
ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & bytes, const std::string & name)
ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & bytes, vk::raii::Sampler && sampler, const std::string & name)
{
bool srgb = true;
@@ -1190,6 +1165,7 @@ ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & byte
std::shared_ptr<vk::raii::DescriptorSet> ds = descriptor_pool.allocate();
vk::DescriptorImageInfo image_info{
.sampler = *sampler,
.imageView = *image->image_view,
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
};
@@ -1197,7 +1173,7 @@ ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & byte
vk::WriteDescriptorSet ds_write{
.dstSet = **ds,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eSampledImage,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info};
device.updateDescriptorSets(ds_write, nullptr);
@@ -1207,6 +1183,7 @@ ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & byte
textures.emplace(
id,
texture_data{
.sampler = std::move(sampler),
.image = image,
.descriptor_set = std::move(ds),
});
@@ -1214,6 +1191,43 @@ ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & byte
return id;
}
ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & bytes, const std::string & name)
{
return load_texture(
bytes,
vk::raii::Sampler{
device,
vk::SamplerCreateInfo{
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.mipmapMode = vk::SamplerMipmapMode::eLinear,
.addressModeU = vk::SamplerAddressMode::eClampToEdge,
.addressModeV = vk::SamplerAddressMode::eClampToEdge,
.addressModeW = vk::SamplerAddressMode::eClampToEdge,
.borderColor = vk::BorderColor::eFloatTransparentBlack,
},
},
name);
}
ImTextureID imgui_textures::load_texture(const std::string & filename)
{
return load_texture(
filename,
vk::raii::Sampler{
device,
vk::SamplerCreateInfo{
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.mipmapMode = vk::SamplerMipmapMode::eLinear,
.addressModeU = vk::SamplerAddressMode::eClampToEdge,
.addressModeV = vk::SamplerAddressMode::eClampToEdge,
.addressModeW = vk::SamplerAddressMode::eClampToEdge,
.borderColor = vk::BorderColor::eFloatTransparentBlack,
},
});
}
void imgui_textures::free_texture(ImTextureID texture)
{
textures.erase(texture);
@@ -1230,6 +1244,11 @@ void imgui_context::set_controllers_enabled(bool value)
controllers_enabled = value;
}
bool imgui_context::is_modal_popup_shown() const
{
return ImGui::GetTopMostAndVisiblePopupModal() != nullptr;
}
imgui_context::viewport & imgui_context::layer(ImVec2 position)
{
for (auto & layer: layers_)
@@ -1241,42 +1260,30 @@ imgui_context::viewport & imgui_context::layer(ImVec2 position)
return layers_.front();
}
void imgui_context::place_layer_relative(size_t layer, size_t base, glm::vec3 offset, glm::quat extra_rotation)
{
const viewport & b = layers_[base];
viewport & l = layers_[layer];
l.orientation = b.orientation * extra_rotation;
l.position = b.position + glm::mat3_cast(b.orientation) * offset;
}
void imgui_context::tooltip(std::string_view text, std::optional<ImVec2> anchor)
void imgui_context::tooltip(std::string_view text)
{
// FIXME: this is incorrect if we use the docking branch of imgui
ImGuiViewport * viewport = ImGui::GetMainViewport();
auto & current_layer = layer(anchor.value_or(ImGui::GetMousePos()));
auto & current_layer = layer(ImGui::GetMousePos());
assert(std::ranges::contains(layers_, true, &viewport::tooltip_viewport));
auto & tooltip_layer = *std::ranges::find(layers_, true, &viewport::tooltip_viewport);
// anchor above the given display point, or above the last item's rect (top center)
ImVec2 item_position = anchor.value_or(ImVec2{
// Get the item position before drawing the tooltip (top center)
ImVec2 item_position{
(ImGui::GetItemRectMin().x + ImGui::GetItemRectMax().x) / 2,
ImGui::GetItemRectMin().y,
});
};
auto pos_backup = viewport->Pos;
auto size_backup = viewport->Size;
viewport->Pos = ImVec2(tooltip_layer.vp_origin.x, tooltip_layer.vp_origin.y);
viewport->Size = ImVec2(tooltip_layer.vp_size.x, tooltip_layer.vp_size.y);
// Draw the tooltip in the tooltip layer, themed
// Draw the tooltip in the tooltip layer
// Clamp position to avoid overflowing on the left or the right
const wivrn::ui::theme & t = wivrn::ui::current();
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, wivrn::ui::metrics::tooltip_padding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, t.card_rounding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, t.border_size);
ImGui::PushStyleColor(ImGuiCol_PopupBg, t.card);
ImGui::PushStyleColor(ImGuiCol_Border, t.border);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::tooltip_padding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::tooltip_rounding);
auto & style = ImGui::GetStyle();
const ImVec2 text_size = ImGui::CalcTextSize(text.data(), text.data() + text.size(), true);
@@ -1286,13 +1293,12 @@ void imgui_context::tooltip(std::string_view text, std::optional<ImVec2> anchor)
ImGui::SetNextWindowSizeConstraints({0, 0}, viewport->Size);
if (ImGui::BeginTooltip())
{
ImGui::PushStyleColor(ImGuiCol_Text, t.col(t.text));
ImGui::PushStyleColor(ImGuiCol_Text, 0xffffffff);
ImGui::TextUnformatted(text.data(), text.data() + text.size());
ImGui::PopStyleColor();
ImGui::EndTooltip();
}
ImGui::PopStyleColor(2);
ImGui::PopStyleVar(3);
ImGui::PopStyleVar(2);
viewport->Pos = pos_backup;
viewport->Size = size_backup;
@@ -1302,7 +1308,7 @@ void imgui_context::tooltip(std::string_view text, std::optional<ImVec2> anchor)
auto M = glm::mat3_cast(tooltip_orientation);
float pixel_size = current_layer.size.y / current_layer.vp_size.y;
glm::vec3 tooltip_position_centre = rw_from_vp(item_position) + M * (glm::vec3(0, tooltip_size.y / 2, 0) * pixel_size + constants::gui::tooltip_distance);
glm::vec3 tooltip_position_centre = rw_from_vp(item_position) + M * (glm::vec3(0, tooltip_size.y / 2, 0) * pixel_size + constants::style::tooltip_distance);
// Position the tooltip layer
tooltip_layer.position = tooltip_position_centre;
@@ -1323,15 +1329,9 @@ void ScrollWhenDragging()
static int active_id;
static ImVec2 cumulated_delta;
// don't drag while a popup is open or just closed: the ray snaps back and synthesises a click
static bool popup_was_open;
const bool popup_open = ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel);
bool HoveredIdAllowOverlap_backup = std::exchange(g.HoveredIdAllowOverlap, true);
bool ActiveIdAllowOverlap_backup = std::exchange(g.ActiveIdAllowOverlap, true);
// start only over this window or a child card, and only with no active widget
const bool over = ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows);
if (active_id == 0 and g.ActiveId == 0 and not popup_open and not popup_was_open and over and ImGui::IsMouseClicked(mouse_button, ImGuiInputFlags_None, /*id*/ ImGuiKeyOwner_Any))
if (active_id == 0 and ImGui::ItemHoverable(window->Rect(), 0, g.CurrentItemFlags) and ImGui::IsMouseClicked(mouse_button, ImGuiInputFlags_None, /*id*/ ImGuiKeyOwner_Any))
{
active_id = id;
@@ -1357,8 +1357,6 @@ void ScrollWhenDragging()
g.HoveredIdAllowOverlap = HoveredIdAllowOverlap_backup;
g.ActiveIdAllowOverlap = ActiveIdAllowOverlap_backup;
popup_was_open = popup_open;
}
void CenterTextH(const std::string & text)
@@ -1399,3 +1397,62 @@ void CenterTextHV(const std::string & text)
}
ImGui::PopStyleVar();
}
void InputText(const char * label, std::string & text, const ImVec2 & size, ImGuiInputTextFlags flags)
{
auto callback = [](ImGuiInputTextCallbackData * data) -> int {
std::string & text = *reinterpret_cast<std::string *>(data->UserData);
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize)
{
assert(text.data() == data->Buf);
text.resize(data->BufTextLen);
data->Buf = text.data();
}
return 0;
};
ImGui::InputTextEx(label, nullptr, text.data(), text.size() + 1, size, flags | ImGuiInputTextFlags_CallbackResize, callback, &text);
}
bool RadioButtonWithoutCheckBox(const std::string & label, bool active, ImVec2 size_arg)
{
ImGuiWindow * window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext & g = *GImGui;
const ImGuiStyle & style = g.Style;
const ImGuiID id = window->GetID(label.c_str());
const ImVec2 label_size = ImGui::CalcTextSize(label.c_str(), NULL, true);
const ImVec2 pos = window->DC.CursorPos;
ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
const ImRect bb(pos, pos + size);
ImGui::ItemSize(bb, style.FramePadding.y);
if (!ImGui::ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held);
ImGuiCol_ col;
if ((held && hovered) || active)
col = ImGuiCol_ButtonActive;
else if (hovered)
col = ImGuiCol_ButtonHovered;
else
col = ImGuiCol_Button;
ImGui::RenderNavHighlight(bb, id);
ImGui::RenderFrame(bb.Min, bb.Max, ImGui::GetColorU32(col), true, style.FrameRounding);
ImVec2 TextAlign{0, 0.5f};
ImGui::RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label.c_str(), NULL, &label_size, TextAlign, &bb);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label.c_str(), g.LastItemData.StatusFlags);
return pressed;
}
+19 -8
View File
@@ -21,7 +21,6 @@
#include "image_loader.h"
#include "render/growable_descriptor_pool.h"
#include "utils/cache.h"
#include "utils/mapped_file.h"
#include "utils/thread_safe.h"
#include "wivrn_config.h"
#include "xr/hand_tracker.h"
@@ -31,7 +30,6 @@
#include <glm/gtc/quaternion.hpp>
#include <imgui.h>
#include <implot.h>
#include <inplace_vector.hpp>
#include <optional>
#include <span>
#include <unordered_map>
@@ -44,6 +42,7 @@ class imgui_textures
{
struct texture_data
{
vk::raii::Sampler sampler;
std::shared_ptr<loaded_image> image;
std::shared_ptr<vk::raii::DescriptorSet> descriptor_set;
};
@@ -70,7 +69,9 @@ public:
thread_safe<vk::raii::Queue> & queue,
std::shared_ptr<image_cache_type> image_cache = {});
~imgui_textures();
ImTextureID load_texture(const std::string & filename, vk::raii::Sampler && sampler);
ImTextureID load_texture(const std::string & filename);
ImTextureID load_texture(const std::span<const std::byte> & bytes, vk::raii::Sampler && sampler, const std::string & name = "");
ImTextureID load_texture(const std::span<const std::byte> & bytes, const std::string & name = "");
void free_texture(ImTextureID);
};
@@ -202,7 +203,6 @@ private:
bool show_demo_window = true;
#endif
beman::inplace_vector::inplace_vector<utils::mapped_file, 3> font_awesome;
void initialize_fonts();
std::vector<controller_state> read_controllers_state(XrTime display_time);
@@ -226,9 +226,6 @@ public:
return layers_;
}
// place a satellite layer at base orientation (optionally post-rotated), offset in the base's local frame
void place_layer_relative(size_t layer, size_t base, glm::vec3 offset, glm::quat extra_rotation = glm::quat(1, 0, 0, 0));
std::vector<window_viewport> windows();
viewport & layer(ImVec2 position);
@@ -249,11 +246,12 @@ public:
void set_current();
bool is_modal_popup_shown() const;
void vibrate_on_hover();
void set_hovered_item();
void set_controllers_enabled(bool value);
// anchor, if set, positions the tooltip above that display point instead of above the last item's rect
void tooltip(std::string_view text, std::optional<ImVec2> anchor = std::nullopt);
void tooltip(std::string_view text);
std::array<bool, 2> is_aim_interaction() const
{
return {aim_interaction[0] == 1, aim_interaction[1] == 1};
@@ -265,3 +263,16 @@ void ScrollWhenDragging();
void CenterTextH(const std::string & text);
void CenterTextHV(const std::string & text);
void InputText(const char * label, std::string & text, const ImVec2 & size, ImGuiInputTextFlags flags);
bool RadioButtonWithoutCheckBox(const std::string & label, bool active, ImVec2 size_arg);
template <typename T, typename U>
static bool RadioButtonWithoutCheckBox(const std::string & label, T & v, U v_button, ImVec2 size_arg)
{
const bool pressed = RadioButtonWithoutCheckBox(label, v == v_button, size_arg);
if (pressed)
v = v_button;
return pressed;
}
-7
View File
@@ -19,7 +19,6 @@
#include "scene_loader.h"
#include "gpu_buffer.h"
#include "hmd_traits.h"
#include "image_loader.h"
#include "render/scene_components.h"
#include "render/vertex_layout.h"
@@ -836,9 +835,6 @@ public:
if (auto it = extras.find({fastgltf::Category::Materials, material_id, "fragment_shader"}); it != extras.end())
material.fragment_shader = it->second;
if (auto it = application::get_hmd_traits().override_shader.find(material.fragment_shader); it != application::get_hmd_traits().override_shader.end())
material.fragment_shader = it->second;
renderer::material::gpu_data & material_data = material.staging;
material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor);
@@ -921,9 +917,6 @@ public:
else
primitive_ref.vertex_shader = "lit_skinned.vert";
if (auto it = application::get_hmd_traits().override_shader.find(primitive_ref.vertex_shader); it != application::get_hmd_traits().override_shader.end())
primitive_ref.vertex_shader = it->second;
// For attributes types, see https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview (§ 3.7.2.1)
auto shader = shader_loader{device}(primitive_ref.vertex_shader);
for (const auto & input: shader->inputs)
+1 -1
View File
@@ -1002,7 +1002,7 @@ void scene_renderer::render(
return false;
// If blending is disabled (std::get<0> == false), put the closest objects first
// If blending is enabled (std::get<0> == true), put the farthest objects first
// If blending is enabled (std::get<0> == true), put the farthest objeccts first
return std::get<0>(a) ^ (std::get<1>(a) > std::get<1>(b));
});
-234
View File
@@ -1,234 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "ui_theme.h"
#include "utils/i18n.h"
namespace wivrn::ui
{
static ImVec4 rgb(int r, int g, int b, float a = 1)
{
return {r / 255.f, g / 255.f, b / 255.f, a};
}
static theme dark_default()
{
theme t;
t.name = "Dark";
t.localized_name = _C("theme name", "Dark");
t.accent = rgb(30, 115, 255);
t.accent_hovered = rgb(64, 140, 255);
t.accent_active = rgb(18, 95, 228);
t.on_accent = rgb(255, 255, 255);
t.background = rgb(10, 11, 13);
t.card = rgb(22, 24, 29);
t.card_hovered = rgb(28, 30, 36);
t.control = rgb(35, 38, 46);
t.control_hovered = rgb(44, 48, 57);
t.control_active = rgb(52, 57, 68);
t.text = rgb(244, 245, 248);
t.text_muted = rgb(150, 156, 167);
t.border = rgb(40, 43, 51);
t.danger = rgb(239, 68, 68);
t.danger_hovered = rgb(248, 96, 96);
t.success = rgb(52, 199, 123);
t.warning = rgb(249, 115, 6);
t.dimming = rgb(128, 128, 128, 0.5f);
t.rounding = 8;
t.card_rounding = 14;
t.border_size = 1;
t.font_scale = 1.0; // user multiplier, 100% maps to metrics::font_base
return t;
}
static theme midnight()
{
theme t = dark_default();
t.name = "Midnight";
t.localized_name = _C("theme name", "Midnight");
t.background = rgb(6, 8, 16);
t.card = rgb(16, 20, 34);
t.card_hovered = rgb(22, 27, 44);
t.control = rgb(28, 34, 54);
t.control_hovered = rgb(36, 43, 66);
t.control_active = rgb(44, 52, 78);
t.border = rgb(30, 37, 58);
return t;
}
static theme slate_light()
{
theme t = dark_default();
t.name = "Slate";
t.localized_name = _C("theme name", "Slate");
t.background = rgb(28, 30, 36);
t.card = rgb(38, 41, 49);
t.card_hovered = rgb(46, 50, 60);
t.control = rgb(54, 59, 70);
t.control_hovered = rgb(64, 70, 83);
t.control_active = rgb(74, 81, 96);
t.text = rgb(236, 238, 242);
t.text_muted = rgb(168, 174, 186);
t.border = rgb(58, 63, 75);
return t;
}
// True black, ideal for OLED panels
static theme oled()
{
theme t = dark_default();
t.name = "OLED";
t.localized_name = _C("theme name", "OLED");
t.background = rgb(0, 0, 0);
t.card = rgb(6, 6, 8);
t.card_hovered = rgb(11, 12, 14);
t.control = rgb(22, 24, 28);
t.control_hovered = rgb(30, 32, 38);
t.control_active = rgb(40, 43, 50);
t.border = rgb(26, 28, 33);
return t;
}
// Neutral dark gray
static theme graphite()
{
theme t = dark_default();
t.name = "Graphite";
t.localized_name = _C("theme name", "Graphite");
t.background = rgb(20, 21, 23);
t.card = rgb(31, 33, 36);
t.card_hovered = rgb(39, 41, 45);
t.control = rgb(48, 51, 56);
t.control_hovered = rgb(58, 62, 68);
t.control_active = rgb(68, 72, 80);
t.text = rgb(238, 240, 243);
t.text_muted = rgb(160, 164, 172);
t.border = rgb(50, 53, 59);
return t;
}
// Light surfaces, dark text
static theme light()
{
theme t = dark_default();
t.name = "Light";
t.localized_name = _C("theme name", "Light");
t.background = rgb(188, 193, 202);
t.card = rgb(252, 252, 253);
t.card_hovered = rgb(242, 243, 246);
t.control = rgb(206, 210, 219);
t.control_hovered = rgb(193, 198, 208);
t.control_active = rgb(178, 184, 196);
t.text = rgb(14, 16, 20);
t.text_muted = rgb(66, 72, 84);
t.border = rgb(176, 182, 194);
t.success = rgb(36, 147, 90);
return t;
}
std::vector<theme> presets()
{
return {oled(), dark_default(), midnight(), graphite(), slate_light(), light()};
}
std::vector<accent_swatch> accent_swatches()
{
return {
{"Blue", rgb(30, 115, 255), rgb(64, 140, 255), rgb(18, 95, 228)},
{"Violet", rgb(132, 72, 255), rgb(152, 98, 255), rgb(112, 52, 232)},
{"Emerald", rgb(0, 200, 132), rgb(28, 214, 150), rgb(0, 172, 112)},
{"Amber", rgb(255, 160, 0), rgb(255, 176, 36), rgb(228, 140, 0)},
{"Rose", rgb(255, 40, 82), rgb(255, 74, 108), rgb(230, 28, 68)},
{"Cyan", rgb(0, 190, 225), rgb(34, 205, 236), rgb(0, 168, 200)},
};
}
void set_accent(const accent_swatch & swatch)
{
theme & t = current();
t.accent = swatch.base;
t.accent_hovered = swatch.hovered;
t.accent_active = swatch.active;
}
theme & current()
{
static theme t = dark_default();
return t;
}
void set_theme(const theme & t)
{
current() = t;
}
float & background_alpha()
{
static float alpha = 0.75f; // translucent panels by default
return alpha;
}
void theme::apply() const
{
ImGuiStyle & style = ImGui::GetStyle();
style.FontScaleMain = font_scale;
style.WindowRounding = card_rounding;
style.ChildRounding = card_rounding;
style.PopupRounding = card_rounding;
style.FrameRounding = rounding;
style.GrabRounding = rounding;
style.TabRounding = rounding;
style.FrameBorderSize = border_size;
style.WindowBorderSize = border_size;
ImVec4 * c = style.Colors;
c[ImGuiCol_Text] = text;
c[ImGuiCol_TextDisabled] = text_muted;
c[ImGuiCol_WindowBg] = background;
c[ImGuiCol_ChildBg] = card;
c[ImGuiCol_PopupBg] = card;
c[ImGuiCol_Border] = border;
c[ImGuiCol_FrameBg] = control;
c[ImGuiCol_FrameBgHovered] = control_hovered;
c[ImGuiCol_FrameBgActive] = control_active;
c[ImGuiCol_Button] = control;
c[ImGuiCol_ButtonHovered] = control_hovered;
c[ImGuiCol_ButtonActive] = accent;
c[ImGuiCol_Header] = control_hovered;
c[ImGuiCol_HeaderHovered] = control_hovered;
c[ImGuiCol_HeaderActive] = accent;
c[ImGuiCol_SliderGrab] = accent;
c[ImGuiCol_SliderGrabActive] = accent_active;
c[ImGuiCol_CheckMark] = accent;
c[ImGuiCol_ScrollbarBg] = {0, 0, 0, 0};
c[ImGuiCol_ScrollbarGrab] = control;
c[ImGuiCol_ScrollbarGrabHovered] = control_hovered;
c[ImGuiCol_ScrollbarGrabActive] = control_active;
c[ImGuiCol_Separator] = border;
}
} // namespace wivrn::ui
-173
View File
@@ -1,173 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <imgui.h>
#include <string>
#include <vector>
namespace wivrn::ui
{
struct theme
{
std::string name;
std::string localized_name;
// Accent
ImVec4 accent;
ImVec4 accent_hovered;
ImVec4 accent_active;
ImVec4 on_accent; // text/icon on an accent fill
// Surfaces, back to front
ImVec4 background;
ImVec4 card;
ImVec4 card_hovered;
ImVec4 control; // slider rail, secondary button, input
ImVec4 control_hovered;
ImVec4 control_active;
// Content
ImVec4 text;
ImVec4 text_muted;
ImVec4 border;
// Semantic
ImVec4 danger;
ImVec4 danger_hovered;
ImVec4 success;
ImVec4 warning;
// Dimming when a modal popup is visible
ImVec4 dimming;
// Shape, in pixels
float rounding; // buttons, inputs, sliders
float card_rounding; // cards
float border_size;
float font_scale; // global text size multiplier
// packed color with the current global alpha applied, so draw-list widgets dim with BeginDisabled()
ImU32 col(const ImVec4 & c) const
{
ImVec4 v = c;
v.w *= ImGui::GetStyle().Alpha;
return ImGui::ColorConvertFloat4ToU32(v);
}
// push colors and metrics into the global ImGui style
void apply() const;
};
// fixed design tokens shared by the widgets
namespace metrics
{
constexpr float font_base = 0.765; // user-facing 100% text scale
constexpr float font_title = 1.7; // page header, x base font size
constexpr float font_description = 0.82; // muted secondary text, x base font size
constexpr ImVec2 button_padding = {26, 14};
constexpr ImVec2 card_padding = {28, 22}; // regular cards
constexpr ImVec2 list_card_padding = {18, 18}; // cards holding a list of rows
// shared height of every full-width control so they line up in a setting row, x frame height
constexpr float control_height = 1.65;
constexpr float toggle_aspect = 1.9; // track width / height
constexpr float toggle_knob_inset = 3; // gap between track edge and knob
constexpr float slider_grab_width = 14;
constexpr float segmented_inset = 3; // gap around the active segment
constexpr float icon_button_glyph = 0.58; // glyph height as a fraction of the button side
constexpr float button_label_glyph = 1.35; // leading icon size in a labeled button, x base text size
constexpr float combo_row_height = 2.2; // x frame height, big touch rows in the modal
constexpr float combo_chevron = 12; // chevron size in the closed box
constexpr float combo_modal_min_width = 460; // popup never narrower than this
constexpr ImVec2 combo_padding = {16, 0}; // horizontal inner padding of box and rows
constexpr float list_row_box = 52; // leading icon/thumbnail size in a list row
constexpr float list_row_box_large = 80; // min thumbnail size for full-height list rows
constexpr float list_row_pad = 12; // inner padding of a list row, both axes
constexpr ImVec2 chip_padding = {12, 6}; // inner padding of a chip/badge
constexpr float chip_pill_padding_x = 18; // roomier horizontal padding for top-bar pill chips
constexpr float input_padding_x = 14; // horizontal text padding inside inputs
constexpr float font_modal_title = 1.2; // modal heading, x base font size
constexpr float label_line_gap = 5; // title to description
constexpr float label_bottom_pad = 6; // breathing room below the description
constexpr float nav_section_gap = 18; // space above a sidebar section header
constexpr ImVec2 card_item_spacing = {12, 10}; // ItemSpacing pushed around a card section
constexpr float setting_control_width = 480; // width of the control in a setting row
// application shell: top bar, sidebar, content panel, shared by lobby and in-stream window
constexpr float sidebar_width = 300;
constexpr float top_bar_height = 72;
constexpr float content_margin = 20; // gap around the main content panel
// application launcher grid
constexpr float app_icon_small = 120;
constexpr float app_icon_medium = 176;
constexpr float app_icon_large = 240;
constexpr float app_tile_margin = 24; // horizontal slack each side of the icon in a tile
constexpr float app_view_toggle_width = 150; // grid/list segmented control
constexpr float app_size_toggle_width = 300; // small/medium/large segmented control
constexpr float app_spinner_radius = 110; // app-starting spinner
constexpr float app_spinner_thickness = 22;
// modal/popup windows not yet on the card system (first-run, confirm dialogs, loading popup)
constexpr ImVec2 window_padding = {20, 20};
constexpr float window_rounding = 10;
constexpr float window_border_size = 2;
constexpr ImVec2 tooltip_padding = {16, 12}; // hover tooltip window padding
constexpr ImVec2 button_size = {220, 80}; // big touch buttons in confirm dialogs
// PIN entry keypad
constexpr ImVec2 pin_entry_key_size = {90, 70};
constexpr ImVec2 pin_entry_item_spacing = {10, 10};
constexpr float pin_entry_popup_width = 3 * pin_entry_key_size.x + 2 * pin_entry_item_spacing.x;
} // namespace metrics
// theme in effect, call current().apply() after mutating
theme & current();
void set_theme(const theme & t);
// panel and card background opacity, 0..1, kept out of the presets so switching palette keeps it
float & background_alpha();
std::vector<theme> presets();
struct accent_swatch
{
const char * name;
ImVec4 base;
ImVec4 hovered;
ImVec4 active;
};
std::vector<accent_swatch> accent_swatches();
void set_accent(const accent_swatch & swatch);
} // namespace wivrn::ui
File diff suppressed because it is too large Load Diff
-199
View File
@@ -1,199 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <functional>
#include <imgui.h>
#include <string>
#include <vector>
// Themed, reusable UI widgets, colors and metrics from wivrn::ui::current()
// Display text takes const std::string &, ids and icon glyphs stay const char *
namespace wivrn::ui
{
enum class button_style
{
primary, // accent fill
secondary, // control fill
danger, // destructive
ghost, // transparent until hovered
};
// Page title with an optional muted subtitle
void page_header(const std::string & title, const std::string & subtitle = {});
// Rounded panel, pair with end_card
bool begin_card(const char * id, const ImVec2 & size = {0, 0});
// Tighter padding, for cards holding a list of rows
bool begin_list_card(const char * id);
void end_card();
// Full-width divider between rows of a card
void row_separator();
// Title and wrapped muted description on the left, control_width reserved on the right
// Returns the window-local y of the label bottom, to keep the row tall enough for a multi-line label
float setting_label(const std::string & title, const std::string & description, float control_width);
// "<icon> <label>" with the standard two-space gap
std::string icon_label(const char * icon, const std::string & label);
// Auto-fit width of a button, as laid out when size.x is 0
float button_width(const std::string & label);
float button_width(const char * icon, const std::string & label);
// Footprint of a chip() with standard padding, no dot, no height override
ImVec2 chip_size(const std::string & label);
// Exact layout width of a chip(), accounting for the optional dot and the height override padding
float chip_width(const std::string & label, bool dot = false, float height = 0);
bool button(const std::string & label, button_style style = button_style::primary, const ImVec2 & size = {0, 0});
// Same, with a larger leading icon glyph
bool button(const char * icon, const std::string & label, button_style style = button_style::primary, const ImVec2 & size = {0, 0});
// tooltip, if not empty, is shown while hovered
bool icon_button(const char * icon, const ImVec2 & size = {0, 0}, bool active = false, const std::string & tooltip = {});
// Circular download-progress indicator with a centred cancel glyph
// fraction in [0,1] draws a determinate ring, < 0 an indeterminate spinner
// Returns true when cancel is clicked
bool cancel_progress_button(const char * id, float fraction, const ImVec2 & size = {0, 0}, const std::string & tooltip = {});
bool toggle(const char * id, bool * v, const bool * default_value = nullptr);
// Width a trailing reset slot consumes, gap + square
float reset_slot_width();
// The value controls below draw a reset button when the value differs from default_value
bool slider_int(const char * id, int * v, int v_min, int v_max, const char * format, const ImVec2 & size = {0, 0}, const int * default_value = nullptr);
// Pill group, *selected is the index of the active option
bool segmented(const char * id, const std::vector<std::string> & options, int * selected, const ImVec2 & size = {0, 0}, const int * default_value = nullptr);
struct combo_item
{
const char * name;
const char * description = nullptr;
};
// Combo box whose options open in a modal list, *selected is the chosen index, title labels the modal
bool combo(const char * id, const std::string & title, const std::vector<combo_item> & items, int * selected, float width = 0, const int * default_value = nullptr);
// Combo box with multiple selection
bool combo_multi(const char * id, const std::string & title, const std::string & preview, const std::vector<combo_item> & items, std::vector<char> * selected, float width, const std::vector<char> * default_value);
// Centre (display coords) where combo and begin_modal popups open, plus the popup-layer height
// available_height of 0 leaves the list unbounded, set once per frame
void set_popup_center(const ImVec2 & center, float available_height = 0);
// hover-haptic hook, fired after an interactive item
void set_hover_haptic(std::function<void()> hook);
// tooltip hook for the last item
void set_tooltip_hook(std::function<void(const char *)> hook);
enum class chip_style
{
neutral, // control fill, normal text
muted, // control fill, muted text
accent,
success,
warning,
danger,
};
// Status badge, label may include a leading icon glyph, dot draws a status dot
// height overrides the pill height, default sizes to text + padding
void chip(const std::string & label, chip_style style = chip_style::neutral, bool dot = false, float height = 0);
// Muted sidebar group header
void nav_section(const std::string & label);
// sidebar entry: icon + label, highlighted when selected, returns true when clicked
bool nav_item(const char * icon, const std::string & label, bool selected);
// Single-line text field at control height, hint is optional placeholder text
bool input_text(const char * id, std::string & text, const char * hint = nullptr, float width = 0);
// number field with -/+ steppers, returns true on change
bool input_int(const char * id, int * v, int step = 1, int v_min = 0, int v_max = 0, float width = 0);
// Centred modal on the popup layer, open with ImGui::OpenPopup(id), dismiss with ImGui::CloseCurrentPopup()
// Pair with end_modal only when this returns true
bool begin_modal(const char * id, const std::string & title, float width = 0);
void end_modal();
struct action_item
{
const char * icon;
const char * label;
bool danger = false;
bool checked = false;
};
// overflow icon button opening a popup of actions, returns the picked index or -1
int action_menu(const char * id, const char * icon, const std::vector<action_item> & items);
struct list_row_result
{
ImVec2 min, max; // row rect (screen) for right-aligning trailing controls
bool clicked; // the row body was clicked
// Screen position for a size trailing control, right-aligned to right_x and vertically centred
ImVec2 trailing(float right_x, const ImVec2 & size) const
{
return {right_x - size.x, min.y + (max.y - min.y - size.y) * 0.5f};
}
};
// List row: leading thumbnail (image, if non-zero) or icon box, title and muted subtitle
// trailing_width reserves right-side space for trailing controls, excluded from the click area
// large_thumb spans the leading thumbnail/icon box across the full row height
// interactive=false reserves layout only, no row-body click area or hover highlight
list_row_result begin_list_row(const char * id, const char * icon, ImTextureID image, const std::string & title, const std::string & subtitle, bool selected = false, float trailing_width = 0, float height = 0, bool large_thumb = false, bool interactive = true);
void end_list_row();
// confirmation dialog, open with ImGui::OpenPopup(id), returns 1 confirmed / -1 cancelled / 0 otherwise
// danger styles the confirm button as destructive
int confirm_modal(const char * id, const std::string & title, const std::string & message, const std::string & confirm_label, const std::string & cancel_label, bool danger = false);
// shared window shell: top bar, sidebar and dividers, called inside the main window
// One slot in the top bar's right-aligned cluster, width is the slot's layout width
// draw() renders it at the cursor, vertically centred, at the standard control height
struct top_bar_item
{
float width;
std::function<void()> draw;
};
// Top bar: WiVRn logo + wordmark on the left, right_items right-aligned, height in pixels
void top_bar(float height, ImTextureID logo, const std::vector<top_bar_item> & right_items);
// sidebar nav frame: scrolling top section, footer_items rows pinned at the bottom
// always pair: begin_sidebar -> sidebar_footer -> end_sidebar
void begin_sidebar(float top_bar_h, float tab_width, int footer_items = 0);
void sidebar_footer();
void end_sidebar();
// Hairline dividers separating the top bar, sidebar and content, dimmed with the panel
void shell_dividers(float top_bar_h, float tab_width);
} // namespace wivrn::ui
-21
View File
@@ -25,7 +25,6 @@
#include "utils/i18n.h"
#include "utils/overloaded.h"
#include "utils/ranges.h"
#include <cstring>
#include <entt/core/fwd.hpp>
#include <magic_enum.hpp>
#include <spdlog/spdlog.h>
@@ -530,26 +529,6 @@ std::pair<entt::entity, components::node &> scene::add_gltf(const std::filesyste
return add_gltf(load_gltf(path), layer_mask);
}
std::shared_ptr<renderer::material> scene::create_material(std::function<void(renderer::material &)> init) const
{
auto material = std::make_shared<renderer::material>(*renderer->get_default_material());
if (init)
init(*material);
material->buffer = std::make_shared<buffer_allocation>(
device,
vk::BufferCreateInfo{
.size = sizeof(material->staging),
.usage = vk::BufferUsageFlagBits::eUniformBuffer},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO});
material->offset = 0;
std::memcpy(material->buffer->map(), &material->staging, sizeof(material->staging));
material->buffer->unmap();
return material;
}
void scene::remove(entt::entity entity)
{
std::vector to_be_removed{entity};
-3
View File
@@ -33,7 +33,6 @@
#include <cstdint>
#include <entt/entity/registry.hpp>
#include <filesystem>
#include <functional>
#include <span>
#include <string>
#include <unordered_map>
@@ -219,8 +218,6 @@ public:
entt::registry world;
std::shared_ptr<renderer::material> create_material(std::function<void(renderer::material &)> init = {}) const;
std::shared_ptr<entt::registry> load_gltf(const std::filesystem::path & path, std::function<void(float)> progress_cb = {});
void unload_gltf(const std::filesystem::path & path);
std::pair<entt::entity, components::node &> add_gltf(std::shared_ptr<entt::registry> gltf, uint32_t layer_mask = -1);
+143 -180
View File
@@ -17,84 +17,77 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#define IMGUI_DEFINE_MATH_OPERATORS
#include "app_launcher.h"
#include "application.h"
#include "configuration.h"
#include "constants.h"
#include "imgui.h"
#include "imgui_internal.h"
#include "render/ui_theme.h"
#include "render/ui_widgets.h"
#include "scenes/stream.h"
#include "utils/i18n.h"
#include "utils/ranges.h"
#include <IconsFontAwesome7.h>
#include <algorithm>
#include <imspinner.h>
#include <spdlog/fmt/fmt.h>
#include <uni_algo/case.h>
using namespace std::chrono_literals;
namespace ui = wivrn::ui;
namespace
// Display a button with an image and a text centred horizontally
static bool icon(
const std::string & text,
ImTextureRef tex_ref,
const ImVec2 & image_size,
ImGuiButtonFlags flags = 0,
const ImVec2 & size_arg = ImVec2(0, 0),
const ImVec2 & uv0 = ImVec2(0, 0),
const ImVec2 & uv1 = ImVec2(1, 1),
const ImVec4 & tint_col = ImVec4(1, 1, 1, 1))
{
// target grid icon size per small/medium/large setting, tiles stretch from this to fill the row
float grid_image_size(uint32_t size)
{
switch (size)
{
case 0:
return ui::metrics::app_icon_small;
case 2:
return ui::metrics::app_icon_large;
default:
return ui::metrics::app_icon_medium;
}
}
// Themed grid tile: image with a centred label below, control surface, accent on hover
bool app_tile(const std::string & id, const std::string & name, ImTextureID texture, float tile_w, float image_size)
{
const ui::theme & t = ui::current();
const ImGuiStyle & style = ImGui::GetStyle();
// Based on ImGui::ButtonEx and ImGui::ImageButtonEx
ImGuiWindow * window = ImGui::GetCurrentWindow();
const ImGuiStyle & style = ImGui::GetStyle();
if (window->SkipItems)
return false;
const float pad = ui::metrics::list_row_pad;
const ImVec2 size{tile_w, image_size + pad * 2 + style.ItemInnerSpacing.y + ImGui::GetTextLineHeight()};
const ImVec2 label_size = ImGui::CalcTextSize(text.c_str(), nullptr, true);
ImVec2 size = ImGui::CalcItemSize(
size_arg,
std::max(image_size.x, label_size.x) + style.FramePadding.x * 2.0f,
image_size.y + style.ItemInnerSpacing.y + label_size.y + style.FramePadding.y * 2.0f);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ImRect image_pos(
{(bb.Min.x + bb.Max.x - image_size.x) / 2, bb.Min.y + style.FramePadding.y},
{(bb.Min.x + bb.Max.x + image_size.x) / 2, bb.Min.y + style.FramePadding.y + image_size.y});
ImRect label_pos(
{bb.Min.x + style.FramePadding.x, image_pos.Max.y + style.ItemInnerSpacing.y},
{bb.Max.x - style.FramePadding.x, bb.Max.y - style.FramePadding.y});
ImGui::ItemSize(bb);
const ImGuiID iid = window->GetID(id.c_str());
if (not ImGui::ItemAdd(bb, iid))
ImGuiID id = window->GetID(text.c_str());
if (!ImGui::ItemAdd(bb, id))
return false;
bool hovered, held;
const bool pressed = ImGui::ButtonBehavior(bb, iid, &hovered, &held, ImGuiButtonFlags_PressedOnClickRelease);
bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held, flags);
ImDrawList * dl = window->DrawList;
dl->AddRectFilled(bb.Min, bb.Max, t.col(held and hovered ? t.control_active : hovered ? t.card_hovered
: t.control),
t.card_rounding);
if (hovered)
dl->AddRect(bb.Min, bb.Max, t.col(t.accent), t.card_rounding, t.border_size * 2);
// Render
const ImU32 col = ImGui::GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered
: ImGuiCol_Button);
ImGui::RenderNavCursor(bb, id);
ImGui::RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
const ImVec2 image_min{(bb.Min.x + bb.Max.x - image_size) / 2, bb.Min.y + pad};
dl->AddImage(texture, image_min, image_min + ImVec2{image_size, image_size});
const ImVec2 label_min{bb.Min.x + pad, image_min.y + image_size + style.ItemInnerSpacing.y};
const ImVec2 label_max{bb.Max.x - pad, bb.Max.y - pad};
const ImVec2 label_size = ImGui::CalcTextSize(name.c_str(), nullptr, true);
ImGui::RenderTextClipped(label_min, label_max, name.c_str(), nullptr, &label_size, {0.5f, 0.5f}, &bb);
window->DrawList->AddImage(tex_ref, image_pos.Min, image_pos.Max, uv0, uv1, ImGui::GetColorU32(tint_col));
ImGui::RenderTextClipped(label_pos.Min, label_pos.Max, text.c_str(), NULL, &label_size, style.ButtonTextAlign, &bb);
return pressed;
}
} // namespace
app_launcher::app_launcher(
scenes::stream & stream,
@@ -112,169 +105,139 @@ app_launcher::app_launcher(
app_launcher::clicked app_launcher::draw_gui(imgui_context & imgui_ctx, const std::string & cancel)
{
auto & config = application::get_config();
auto res = clicked::None;
auto t0 = std::chrono::steady_clock::now();
bool app_starting = start_time != std::chrono::steady_clock::time_point{} and
t0 - start_time < 10s;
auto cancel_size = ImGui::CalcTextSize(cancel.c_str());
auto apps = applications.lock();
// resolve an app's icon, uploading lazily and capped per frame to stay responsive
auto texture_for = [&](app & a) -> ImTextureID {
if (a.image.empty())
return default_icon;
auto it = app_icons.find(a.id);
if (it == app_icons.end())
{
if (std::chrono::steady_clock::now() - t0 > 10ms)
return default_icon;
try
{
it = app_icons.emplace(a.id, textures.load_texture(a.image)).first;
}
catch (std::exception & e)
{
spdlog::warn("Unable to load icon for \"{}\": {}", a.id, e.what());
a.image.clear();
return default_icon;
}
}
return it->second;
};
auto launch = [&](const std::string & id) {
res = clicked::Start;
start_time = t0;
stream.start_application(id);
};
const ImVec2 content_pad = {34, 34}; // symmetric inner padding, both axes equal
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, content_pad);
ImGui::BeginChild("launcher", {0, 0}, ImGuiChildFlags_AlwaysUseWindowPadding);
const float header_top = ImGui::GetCursorPosY();
const std::string subtitle = _S("Pick an application to start streaming, or start one on the PC.");
ImGui::PushFont(nullptr, constants::gui::font_size_large);
if (server_name.empty())
ui::page_header(_cS("status in the title bar", "Connected"), subtitle);
CenterTextH(_("Connected to WiVRn server"));
else
ui::page_header(fmt::format(_F("Connected to {}"), server_name), subtitle);
const float content_y = ImGui::GetCursorPosY();
CenterTextH(fmt::format(_F("Connected to {}"), server_name));
ImGui::PopFont();
const bool has_apps = not apps->empty();
int view = config.app_list_view ? 1 : 0;
int size_idx = std::clamp<int>(config.app_icon_size, 0, 2);
const std::vector<std::string> size_opts = {_cS("icon size", "Small"), _cS("icon size", "Medium"), _cS("icon size", "Large")};
const std::vector<std::string> view_opts = {ICON_FA_TABLE_CELLS_LARGE, ICON_FA_LIST};
const float gap = ImGui::GetStyle().ItemSpacing.x;
const float view_w = ui::metrics::app_view_toggle_width;
const float size_w = ui::metrics::app_size_toggle_width;
const float disconnect_w = ui::button_width(cancel);
// title row stays fixed: view/size toggles then disconnect, right-aligned, disconnect stays enabled while an app starts
const float right = ImGui::GetContentRegionAvail().x + ImGui::GetCursorScreenPos().x - ImGui::GetWindowPos().x;
ImGui::SetCursorPos({right - disconnect_w, header_top});
if (ui::button(cancel, ui::button_style::danger))
res = clicked::Cancel;
ImGui::BeginDisabled(app_starting);
if (has_apps)
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {20, 20});
if (apps->empty())
{
float toggles_x = right - disconnect_w - gap - view_w;
if (view == 0)
toggles_x -= size_w + gap;
ImGui::SetCursorPos({toggles_x, header_top});
if (view == 0)
{
if (ui::segmented("##icon_size", size_opts, &size_idx, {size_w, 0}))
{
config.app_icon_size = size_idx;
config.save();
}
ImGui::SameLine(0, gap);
}
if (ui::segmented("##view_mode", view_opts, &view, {view_w, 0}))
{
config.app_list_view = view == 1;
config.save();
}
}
ImGui::SetCursorPos({ImGui::GetCursorStartPos().x, content_y});
if (not has_apps)
{
ImGui::Spacing();
ImGui::TextUnformatted(_S("Waiting for an application on the server"));
CenterTextHV(_("Start an application on the server to start streaming."));
}
else
{
// only the grid/list scrolls, flush to the header edge with no extra inset
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {0, 0});
ImGui::BeginChild("applist", {0, 0});
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {20, 0});
ImGui::BeginDisabled(app_starting);
ImGui::BeginChild("Main", ImGui::GetWindowSize() - ImGui::GetCursorPos() - ImVec2(0, cancel_size.y + 80), 0, app_starting ? ImGuiWindowFlags_NoScrollWithMouse : 0);
if (config.app_list_view)
{
ui::begin_list_card("##apps");
for (auto & app: *apps)
{
if (ui::begin_list_row(app.id.c_str(), nullptr, texture_for(app), app.name, "").clicked)
launch(app.id);
ui::end_list_row();
}
ui::end_card();
}
ImGui::Indent(20);
if (server_name.empty())
ImGui::Text("%s", _S("Start an application on your computer or select one to start streaming."));
else
ImGui::Text("%s", fmt::format(_F("Start an application on {} or select one to start streaming."), server_name).c_str());
ImGui::Unindent();
float icon_width = 400;
float icon_spacing = ImGui::GetStyle().ItemSpacing.x;
float usable_window_width = ImGui::GetWindowSize().x - ImGui::GetCurrentWindow()->ScrollbarSizes.x;
int icons_per_line = (usable_window_width + icon_spacing) / (icon_width + icon_spacing);
float icon_line_width = icons_per_line * icon_width + (icons_per_line - 1) * icon_spacing;
ImGui::Indent((usable_window_width - icon_line_width) / 2);
for (const auto [index, app]: utils::enumerate(*apps))
{
// justified grid: as many columns as fit, tiles stretched to divide the row exactly so there is no trailing gap
const float tile_margin = ui::metrics::app_tile_margin;
const float target = grid_image_size(config.app_icon_size) + tile_margin * 2;
const float avail = ImGui::GetContentRegionAvail().x;
const int per_line = std::max(1, int((avail + gap) / (target + gap)));
const float tile_w = int((avail - gap * (per_line - 1)) / per_line);
const float image_size = grid_image_size(config.app_icon_size);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {gap, gap});
for (const auto [index, app]: utils::enumerate(*apps))
ImTextureID texture = [&]() -> ImTextureID {
if (app.image.empty())
return default_icon;
else
{
auto it = app_icons.find(app.id);
if (it == app_icons.end())
{
// Don't load too many textures at the same time to keep the GUI responsive
if (std::chrono::steady_clock::now() - t0 > 10ms)
return default_icon;
try
{
it = app_icons.emplace(app.id, textures.load_texture(app.image)).first;
}
catch (std::exception & e)
{
spdlog::warn("Unable to load icon for \"{}\": {}", app.id, e.what());
app.image.clear();
return default_icon;
}
}
return it->second;
}
}();
ImGui::PushStyleColor(ImGuiCol_Button, 0);
if (icon(app.name + "##" + app.id, texture, {256, 256}, ImGuiButtonFlags_PressedOnClickRelease, {icon_width, 0}))
{
if (app_tile(app.id, app.name, texture_for(app), tile_w, image_size))
launch(app.id);
imgui_ctx.vibrate_on_hover();
if ((index + 1) % per_line)
ImGui::SameLine();
res = clicked::Start;
start_time = t0;
stream.start_application(app.id);
}
ImGui::PopStyleVar();
imgui_ctx.vibrate_on_hover();
ImGui::PopStyleColor(); // ImGuiCol_Button
if ((index + 1) % icons_per_line)
ImGui::SameLine();
}
ImGui::Unindent();
std::vector<std::pair<std::string, ImTextureID>> to_be_removed;
for (const auto & [app_id, app_icon]: app_icons)
{
if (not std::ranges::contains(*apps, app_id, &app::id))
to_be_removed.emplace_back(app_id, app_icon);
}
for (const auto & [app_id, app_icon]: to_be_removed)
{
imgui_ctx.free_texture(app_icon);
app_icons.erase(app_id);
}
ScrollWhenDragging();
ImGui::EndChild();
ImGui::PopStyleVar();
ImGui::EndDisabled();
// drop textures for apps no longer listed
std::vector<std::string> stale;
for (const auto & [app_id, app_icon]: app_icons)
if (not std::ranges::contains(*apps, app_id, &app::id))
stale.push_back(app_id);
for (const auto & app_id: stale)
if (app_starting)
{
imgui_ctx.free_texture(app_icons.at(app_id));
app_icons.erase(app_id);
ImGui::SetCursorPos(ImGui::GetWindowSize() / 2 - ImVec2{200, 200} - ImGui::GetStyle().FramePadding);
ImSpinner::SpinnerAng("App starting spinner",
200, // Radius
40, // Thickness
ImColor{1.f, 1.f, 1.f, 1.f}, // Colour
ImColor{1.f, 1.f, 1.f, 0.f}, // Background
6, // Velocity
0.75f * 2 * M_PI // Angle
);
}
}
ImGui::EndDisabled();
ImGui::EndChild();
ImGui::PopStyleVar(); // ImGuiStyleVar_WindowPadding
}
ImGui::PopStyleVar();
if (app_starting)
{
const float r = ui::metrics::app_spinner_radius;
ImGui::SetCursorPos(ImGui::GetWindowSize() / 2 - ImVec2{r, r});
ImSpinner::SpinnerAng("starting", r, ui::metrics::app_spinner_thickness, ImColor{ui::current().accent}, ImColor{ui::current().card}, 6, 0.75f * 2 * M_PI);
}
ImGui::SetCursorPos(ImGui::GetWindowSize() - cancel_size - ImVec2{50, 50});
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {10, 10});
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f));
if (ImGui::Button(cancel.c_str()))
res = clicked::Cancel;
imgui_ctx.vibrate_on_hover();
ImGui::PopStyleColor(3); // ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive
ImGui::PopStyleVar(2);
return res;
}
-90
View File
@@ -1,90 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022-2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022-2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "gui_common.h"
#include "android/battery.h"
#include "render/ui_theme.h"
#include "render/ui_widgets.h"
#include "imgui.h"
#include <IconsFontAwesome7.h>
#include <cmath>
#include <spdlog/fmt/fmt.h>
namespace wivrn::gui
{
float toggle_width()
{
return ImGui::GetFrameHeight() * ui::metrics::control_height * ui::metrics::toggle_aspect;
}
std::optional<battery_indicator> battery_status_indicator(XrTime now)
{
#ifdef __ANDROID__
const auto battery = get_battery_status();
if (not battery.charge)
return std::nullopt;
const char * icon = ICON_FA_BATTERY_FULL;
int icon_nr;
if (battery.charging)
icon_nr = *battery.charge > 0.995 ? 5 : now / 500'000'000 % 5;
else
icon_nr = std::round((*battery.charge) * 4);
switch (icon_nr)
{
case 0:
icon = ICON_FA_BATTERY_EMPTY;
break;
case 1:
icon = ICON_FA_BATTERY_QUARTER;
break;
case 2:
icon = ICON_FA_BATTERY_HALF;
break;
case 3:
icon = ICON_FA_BATTERY_THREE_QUARTERS;
break;
case 4:
icon = ICON_FA_BATTERY_FULL;
break;
case 5:
icon = ICON_FA_PLUG;
break;
}
ui::chip_style style;
if (*battery.charge < 0.2)
style = ui::chip_style::danger;
else if (*battery.charge < 0.5)
style = ui::chip_style::warning;
else
style = ui::chip_style::success;
return battery_indicator{
.label = fmt::format("{} {}%", icon, (int)std::round(*battery.charge * 100)),
.style = style,
};
#else
(void)now;
return std::nullopt;
#endif
}
} // namespace wivrn::gui
-66
View File
@@ -1,66 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022-2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022-2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "render/ui_widgets.h"
#include <optional>
#include <string>
#include <openxr/openxr.h>
class configuration;
class imgui_context;
namespace xr
{
class instance;
class session;
class system;
} // namespace xr
namespace wivrn
{
namespace gui
{
bool refresh_rate(
xr::instance & instance,
xr::session & session,
imgui_context & imgui_ctx,
configuration & config);
bool post_processing(
imgui_context & imgui_ctx,
configuration & config);
float toggle_width();
// top-bar battery pill: icon+percent label and threshold colour
struct battery_indicator
{
std::string label;
wivrn::ui::chip_style style;
};
// headset battery as a top-bar pill, nullopt when unavailable, now drives the charging animation
std::optional<battery_indicator> battery_status_indicator(XrTime now);
} // namespace gui
} // namespace wivrn
-908
View File
@@ -1,908 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// each page builds a list of `setting` descriptors, render_settings() draws the matching
// ui:: widget for each, rebuilt every frame so dynamic options/descriptions just work
// same pages serve the lobby and the in-stream window, gated by ctx.in_game
#include "scenes/gui_common.h"
#include "gui_settings.h"
#include "application.h"
#include "configuration.h"
#include "decoder/decoder.h"
#include "render/imgui_impl.h"
#include "render/ui_theme.h"
#include "render/ui_widgets.h"
#include "utils/i18n.h"
#include "xr/instance.h"
#include "xr/session.h"
#include "xr/system.h"
#include "imgui.h"
#include <algorithm>
#include <array>
#include <boost/locale.hpp>
#include <cmath>
#include <functional>
#include <locale>
#include <optional>
#include <spdlog/fmt/fmt.h>
#include <string>
#include <tuple>
#include <vector>
namespace ui = wivrn::ui;
namespace
{
constexpr float control_w = ui::metrics::setting_control_width;
float toggle_width()
{
return ImGui::GetFrameHeight() * ui::metrics::control_height * ui::metrics::toggle_aspect;
}
enum class ui_kind
{
toggle,
slider,
segmented,
combo,
combo_multi,
button,
};
// one declarative setting, `enabled` greys the row out without hiding it
struct setting
{
const char * id; // stable imgui id
std::string label;
std::string description;
ui_kind ui = ui_kind::toggle;
std::function<bool()> get_bool;
std::function<void(bool)> set_bool;
std::function<int()> get_int;
std::function<void(int)> set_int;
int v_min = 0;
int v_max = 0;
std::function<bool(int)> get_multi;
std::function<void(int, bool)> set_multi;
std::string fmt;
std::function<std::vector<std::string>()> options;
std::string title; // combo modal title
std::string button_label; // ui_kind::button
std::function<void()> on_click; // ui_kind::button
std::optional<bool> default_bool; // reset target for toggles
std::optional<int> default_int; // reset target for slider/segmented/combo
std::optional<std::vector<char>> default_multi; // reset target for multicombo
std::function<bool()> enabled;
std::string disabled_tooltip; // shown on a disabled row
};
void render_settings(const wivrn::gui::settings_context & ctx, const char * card_id, const std::vector<setting> & list)
{
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ui::metrics::card_item_spacing);
ui::begin_card(card_id);
for (const auto & s: list)
{
const bool enabled = s.enabled ? s.enabled() : true;
ImGui::BeginDisabled(not enabled);
// stable storage for the reset defaults during this call
bool def_b = s.default_bool.value_or(false);
int def_i = s.default_int.value_or(0);
const bool * dpb = s.default_bool ? &def_b : nullptr;
const int * dpi = s.default_int ? &def_i : nullptr;
const std::vector<char> * dpm = s.default_multi ? &s.default_multi.value() : nullptr;
const ImVec2 row_min = ImGui::GetCursorScreenPos();
const float w = s.ui == ui_kind::toggle ? toggle_width() + (s.default_bool ? ui::reset_slot_width() : 0) : control_w;
const float label_bottom = ui::setting_label(s.label, s.description, w);
switch (s.ui)
{
case ui_kind::toggle: {
bool v = s.get_bool();
if (ui::toggle(s.id, &v, dpb))
s.set_bool(v);
break;
}
case ui_kind::slider: {
int v = s.get_int();
if (ui::slider_int(s.id, &v, s.v_min, s.v_max, s.fmt.c_str(), {control_w, 0}, dpi))
s.set_int(v);
break;
}
case ui_kind::segmented: {
const auto opts = s.options();
int v = s.get_int();
if (ui::segmented(s.id, opts, &v, {control_w, 0}, dpi))
s.set_int(v);
break;
}
case ui_kind::combo: {
const auto opts = s.options();
std::vector<ui::combo_item> items;
for (const auto & o: opts)
items.push_back({o.c_str()});
int v = s.get_int();
if (ui::combo(s.id, s.title, items, &v, control_w, dpi))
s.set_int(v);
break;
}
case ui_kind::combo_multi: {
const auto opts = s.options();
std::vector<ui::combo_item> items;
std::vector<char> selected;
for (const auto & o: opts)
items.push_back({o.c_str()});
for (size_t i = 0; i < items.size(); ++i)
selected.push_back(s.get_multi(i));
if (ui::combo_multi(s.id, s.title, s.title, items, &selected, control_w, dpm))
{
// TODO only set the changed value
for (size_t i = 0; i < items.size(); ++i)
s.set_multi(i, selected[i]);
}
break;
}
case ui_kind::button: {
if (ui::button(s.button_label, ui::button_style::secondary, {control_w, 0}) and s.on_click)
s.on_click();
break;
}
}
ImGui::EndDisabled();
// reserve row height for a multi-line description plus padding, Dummy grows content size
const float pad = std::max(label_bottom - ImGui::GetCursorPosY(), 0.f) + ui::metrics::label_bottom_pad;
ImGui::Dummy({0, pad});
// disabled rows can't fire the widget tooltip hook, do it on the row
if (not enabled and not s.disabled_tooltip.empty())
{
const ImVec2 row_max{row_min.x + ImGui::GetContentRegionAvail().x, ImGui::GetCursorScreenPos().y};
if (ImGui::IsMouseHoveringRect(row_min, row_max))
ctx.imgui_ctx.tooltip(s.disabled_tooltip, (row_min + row_max) / 2);
}
}
ui::end_card();
ImGui::PopStyleVar();
}
template <typename Range, typename T>
std::optional<int> index(const Range & range, const T & value)
{
auto it = std::ranges::find(range, value);
if (it == range.end())
return std::nullopt;
else
return (it - range.begin());
}
} // namespace
namespace wivrn::gui
{
void settings_video(const settings_context & ctx)
{
auto & config = ctx.config;
auto & default_config = ctx.default_config;
const std::string disconnect_tip = ctx.in_game ? _C("tooltip for disabled settings", "Disconnect to change this setting.") : std::string{};
std::vector<setting> list;
if (const auto rates = ctx.session.get_refresh_rates(); not rates.empty())
{
int default_rate_index = index(rates, default_config.preferred_refresh_rate).value_or(-1) + 1;
list.push_back({
.id = "##refresh",
.label = _("Refresh rate"),
.description = _("Use 'auto' to select the refresh rate based on measured application performance. May cause flicker when a change happens."),
.ui = rates.size() < 7 ? ui_kind::segmented : ui_kind::combo,
.get_int = [&config, rates] {
for (size_t i = 0; i < rates.size(); ++i)
if (rates[i] == config.preferred_refresh_rate)
return int(i) + 1;
return 0; },
.set_int = [&ctx, &config, rates](int v) {
if (v == 0)
{
config.preferred_refresh_rate = 0;
config.fps_divider = 1;
}
else
{
ctx.session.set_refresh_rate(rates[v - 1]);
config.preferred_refresh_rate = rates[v - 1];
}
config.save();
if (ctx.on_streaming_changed)
ctx.on_streaming_changed(); },
.options = [rates] {
std::vector<std::string> opts;
opts.push_back(_C("automatic refresh rate, use a short string", "Auto"));
for (float r: rates)
opts.push_back(fmt::format("{}", int(r)));
return opts; },
.default_int = default_rate_index,
});
}
{
const auto width = ctx.recommended_width;
const auto height = ctx.recommended_height;
list.push_back({
.id = "##resolution",
.label = _("Render resolution"),
.description = fmt::format(_cF("render resolution", "Pixels rendered per eye ({}x{}). Lower to gain performance."), int(width * config.resolution_scale), int(height * config.resolution_scale)),
.ui = ui_kind::slider,
.get_int = [&config] { return int(std::lround(config.resolution_scale * 100)); },
.set_int = [&config](int v) { config.resolution_scale = v / 100.0; config.save(); },
.v_min = 50,
.v_max = config.extended_config ? 350 : 150,
.fmt = "%d%%",
.default_int = int(std::lround(default_config.resolution_scale * 100)),
.enabled = [&ctx] { return not ctx.in_game; },
.disabled_tooltip = disconnect_tip,
});
}
if (ctx.instance.has_extension(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME))
{
list.push_back({
.id = "##spacewarp",
.label = _("Application SpaceWarp"),
.description = _("Renders at half the refresh rate. The headset may synthesise frames."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.fps_divider == 2; },
.set_bool = [&ctx, &config](bool v) { config.fps_divider = v ? 2 : 1; config.save(); if (ctx.on_streaming_changed) ctx.on_streaming_changed(); },
.default_bool = default_config.fps_divider == 2,
.enabled = [&config] { return config.preferred_refresh_rate != 0; },
.disabled_tooltip = _("Set a refresh rate other than auto to enable this setting."),
});
}
ui::page_header(_cS("page header title", "Video"), _cS("page header subtitle", "Frame rate and resolution."));
render_settings(ctx, "##video", list);
}
void settings_streaming(const settings_context & ctx)
{
auto & config = ctx.config;
auto & default_config = ctx.default_config;
const std::string disconnect_tip = ctx.in_game ? _C("tooltip for disabled settings", "Disconnect to change this setting.") : std::string{};
std::vector<setting> list;
list.push_back({
.id = "##foveation",
.label = _("Foveated encoding"),
.description = config.check_feature(feature::eye_gaze)
? _("Higher values focus image quality where you look at, improving latency, power efficiency and quality.")
: _("Higher values focus image quality at the center, improving latency, power efficiency and quality."),
.ui = ui_kind::slider,
.get_int = [&config] { return int(std::lround((1 - config.get_stream_scale()) * 100)); },
.set_int = [&config](int v) {
if (not config.extended_config)
v = std::clamp(v, 30, 80);
config.set_stream_scale(1 - v * 0.01);
config.save(); },
.v_min = 0,
.v_max = 80,
.fmt = "%d%%",
.default_int = int(std::lround((1 - default_config.get_stream_scale()) * 100)),
.enabled = [&ctx] { return not ctx.in_game; },
.disabled_tooltip = disconnect_tip,
});
auto codec_name = [](std::optional<wivrn::video_codec> codec) -> std::string {
if (not codec)
return _C("Codec", "Automatic");
switch (*codec)
{
case wivrn::h264:
return _C("Codec", "H.264");
case wivrn::h265:
return _C("Codec", "HEVC (H.265)");
case wivrn::av1:
return _C("Codec", "AV1");
case wivrn::raw:
break;
}
return _C("Codec", "Automatic");
};
std::vector<wivrn::video_codec> codecs;
for (auto c: wivrn::decoder::supported_codecs())
if (c != wivrn::raw)
codecs.push_back(c);
list.push_back({
.id = "##codec",
.label = _C("setting name", "Video codec"),
.description = _("How video is compressed before it is sent to the headset."),
.ui = ui_kind::combo,
.get_int = [&config, codecs] { return config.codec ? index(codecs, *config.codec).value_or(-1) + 1 : 0; },
.set_int = [&config, codecs](int v) {
config.codec = v == 0 ? std::nullopt : std::optional(codecs[v - 1]);
config.save(); },
.options = [codecs, codec_name] {
std::vector<std::string> opts;
opts.push_back(codec_name(std::nullopt));
for (auto c: codecs)
opts.push_back(codec_name(c));
return opts; },
.title = _C("setting name", "Video codec"),
.default_int = default_config.codec ? index(codecs, *default_config.codec).value_or(-1) + 1 : 0,
.enabled = [&ctx] { return not ctx.in_game; },
.disabled_tooltip = disconnect_tip,
});
if (config.codec == wivrn::h265 or config.codec == wivrn::av1)
{
list.push_back({
.id = "##ten_bit",
.label = _C("setting name", "10-bit color"),
.description = _("Higher color precision, supported by HEVC and AV1."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.bit_depth == 10; },
.set_bool = [&config](bool v) { config.bit_depth = v ? 10 : 8; config.save(); },
.default_bool = default_config.bit_depth == 10,
.enabled = [&ctx] { return not ctx.in_game; },
.disabled_tooltip = disconnect_tip,
});
}
const int mb = 1'000'000;
list.push_back({
.id = "##bitrate",
.label = _("Bitrate"),
.description = _("Video data rate sent to the headset."),
.ui = ui_kind::slider,
.get_int = [&config] { return int(config.bitrate_bps / mb); },
.set_int = [&ctx, &config](int v) { config.bitrate_bps = uint32_t(v) * mb; config.save(); if (ctx.on_streaming_changed) ctx.on_streaming_changed(); },
.v_min = 5,
.v_max = int(config.max_bitrate() / mb),
.fmt = "%d Mbit/s",
.default_int = int(default_config.bitrate_bps / mb),
});
// in-stream: steer where foveation focuses quality
if (ctx.in_game)
{
list.push_back({
.id = "##fov_override",
.label = _C("setting name", "Foveation center override"),
.description = _("Manually set where image quality is focused, instead of the center or your gaze."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.override_foveation_enable; },
.set_bool = [&ctx, &config](bool v) {
config.override_foveation_enable = v;
config.save();
if (ctx.on_foveation_override_changed)
ctx.on_foveation_override_changed(); },
.default_bool = default_config.override_foveation_enable,
});
list.push_back({
.id = "##fov_adjust",
.label = _C("setting name", "Foveation center"),
.description = fmt::format(_F("Height {:.1f} °, distance {:.2f} m"), -config.override_foveation_pitch * 180 / M_PI, config.override_foveation_distance),
.ui = ui_kind::button,
.button_label = _C("button label to change the foveation center", "Change"),
.on_click = [&ctx] { if (ctx.enter_foveation_adjust) ctx.enter_foveation_adjust(); },
.enabled = [&config] { return config.override_foveation_enable; },
.disabled_tooltip = _("Enable foveation center override to change this setting."),
});
}
ui::page_header(_cS("page header title", "Streaming"), _cS("page header subtitle", "How video is encoded and sent to the headset."));
render_settings(ctx, "##streaming", list);
if (wivrn::ui::confirm_modal(
"confirm disable in stream gui",
_C("confirmation messagebox title", "Disable in-stream window"),
_C("confirmation message", "Do you really want to disable the in-stream window?\nYou will not be able to re-open it with the thumbsticks."),
_("Yes"),
_("No"),
true) == 1)
{
config.enable_stream_gui = false;
config.save();
}
}
void settings_post_processing(const settings_context & ctx)
{
auto & config = ctx.config;
auto & default_config = ctx.default_config;
std::vector<setting> list;
if (application::get_openxr_post_processing_supported())
{
auto flag_name = [](XrCompositionLayerSettingsFlagsFB f) -> std::string {
switch (f)
{
case XR_COMPOSITION_LAYER_SETTINGS_NORMAL_SUPER_SAMPLING_BIT_FB:
case XR_COMPOSITION_LAYER_SETTINGS_NORMAL_SHARPENING_BIT_FB:
return _C("openxr_post_processing", "Normal");
case XR_COMPOSITION_LAYER_SETTINGS_QUALITY_SUPER_SAMPLING_BIT_FB:
case XR_COMPOSITION_LAYER_SETTINGS_QUALITY_SHARPENING_BIT_FB:
return _C("openxr_post_processing", "Quality");
default:
return _C("openxr_post_processing", "Disabled");
}
};
auto flag_combo = [&](const char * id, std::string label, std::string desc, std::array<XrCompositionLayerSettingsFlagsFB, 3> flags, XrCompositionLayerSettingsFlagsFB configuration::openxr_post_processing_settings::* member) {
std::string title = label;
list.push_back({
.id = id,
.label = std::move(label),
.description = std::move(desc),
.ui = ui_kind::combo,
.get_int = [&config, flags, member] { return index(flags, config.openxr_post_processing.*member).value_or(0); },
.set_int = [&config, flags, member](int v) {
config.openxr_post_processing.*member = flags[v];
config.save(); },
.options = [flags, flag_name] {
std::vector<std::string> o;
for (auto f: flags)
o.push_back(flag_name(f));
return o; },
.title = std::move(title),
.default_int = index(flags, config.openxr_post_processing.*member).value_or(0),
});
};
flag_combo("##supersampling", _("Supersampling"), _("Reduce flicker for high contrast edges. Useful when the input resolution is high compared to the headset display."), {0, XR_COMPOSITION_LAYER_SETTINGS_NORMAL_SUPER_SAMPLING_BIT_FB, XR_COMPOSITION_LAYER_SETTINGS_QUALITY_SUPER_SAMPLING_BIT_FB}, &configuration::openxr_post_processing_settings::super_sampling);
flag_combo("##sharpening", _("Sharpening"), _("Improve clarity of high contrast edges and counteract blur. Useful when the input resolution is low compared to the headset display."), {0, XR_COMPOSITION_LAYER_SETTINGS_NORMAL_SHARPENING_BIT_FB, XR_COMPOSITION_LAYER_SETTINGS_QUALITY_SHARPENING_BIT_FB}, &configuration::openxr_post_processing_settings::sharpening);
}
ui::page_header(_S("Post-processing"), _cS("page header subtitle", "OpenXR layer supersampling and sharpening."));
render_settings(ctx, "##post_processing", list);
}
void settings_audio(const settings_context & ctx)
{
auto & config = ctx.config;
auto & default_config = ctx.default_config;
const std::string disconnect_tip = ctx.in_game ? _C("tooltip for disabled settings", "Disconnect to change this setting.") : std::string{};
std::vector<setting> list;
list.push_back({
.id = "##microphone",
.label = _C("setting name", "Microphone"),
.description = _("Stream the headset microphone to the PC."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.check_feature(feature::microphone); },
.set_bool = [&config](bool v) { config.set_feature(feature::microphone, v); },
.default_bool = default_config.check_feature(feature::microphone),
.enabled = [&ctx] { return not ctx.in_game; },
.disabled_tooltip = disconnect_tip,
});
list.push_back({
.id = "##unprocessed",
.label = _C("setting name", "Unprocessed audio"),
.description = _("Disable audio filters, such as noise cancellation."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.mic_unprocessed_audio; },
.set_bool = [&config](bool v) { config.mic_unprocessed_audio = v; config.save(); },
.default_bool = default_config.mic_unprocessed_audio,
.enabled = [&ctx, &config] { return not ctx.in_game and config.check_feature(feature::microphone); },
.disabled_tooltip = disconnect_tip,
});
ui::page_header(_cS("page header title", "Audio"), _cS("page header subtitle", "Microphone streamed to the PC."));
render_settings(ctx, "##audio", list);
}
void settings_devices(const settings_context & ctx)
{
auto & config = application::get_config();
auto & default_config = ctx.default_config;
std::vector<setting> list;
#ifdef __ANDROID__
list.push_back({
.id = "##keyboard",
.label = _C("setting name", "Keyboard"),
.description = _("Forward the keyboard from the headset to the PC."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.forward_keyboard; },
.set_bool = [&config](bool v) { config.forward_keyboard = v; config.save(); },
.default_bool = default_config.forward_keyboard,
});
list.push_back({
.id = "##mouse",
.label = _C("setting name", "Mouse"),
.description = _("Forward the mouse from the headset to the PC."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.forward_mouse; },
.set_bool = [&config](bool v) { config.forward_mouse = v; config.save(); },
.default_bool = default_config.forward_mouse,
});
#endif
list.push_back({
.id = "##gamepad",
.label = _C("setting name", "Gamepad"),
.description = _("Forward the gamepad from the headset to the PC."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.forward_gamepad; },
.set_bool = [&config](bool v) { config.forward_gamepad = v; config.save(); },
.default_bool = default_config.forward_gamepad,
});
ui::page_header(_cS("page header title", "Devices"), _cS("page header subtitle", "Forward input devices to the PC."));
render_settings(ctx, "##devices", list);
if (ctx.server_hid_forwarding == false and (config.forward_keyboard or config.forward_mouse or config.forward_gamepad))
ui::chip(_("The server does not allow forwarded input devices"), ui::chip_style::warning);
}
bool settings_tracking(const settings_context & ctx)
{
auto & config = ctx.config;
auto & default_config = ctx.default_config;
const std::string disconnect_tip = ctx.in_game ? _C("tooltip for disabled settings", "Disconnect to change this setting.") : std::string{};
std::vector<setting> list;
auto feature_toggle = [&](const char * id, std::string label, std::string desc, feature f) {
list.push_back({
.id = id,
.label = std::move(label),
.description = std::move(desc),
.ui = ui_kind::toggle,
.get_bool = [&config, f] { return config.check_feature(f); },
.set_bool = [&config, f](bool v) { config.set_feature(f, v); },
.default_bool = default_config.check_feature(f),
.enabled = [&ctx] { return not ctx.in_game; },
.disabled_tooltip = disconnect_tip,
});
};
if (ctx.system.hand_tracking_supported())
feature_toggle("##hand", _C("setting name", "Hand tracking"), _("Track your hands for input when controllers are down."), feature::hand_tracking);
if (application::get_eye_gaze_supported())
feature_toggle("##eye", _C("setting name", "Eye tracking"), _("Used by foveated encoding to focus quality where you look."), feature::eye_gaze);
if (ctx.system.face_tracker_supported() != xr::face_tracker_type::none)
feature_toggle("##face", _C("setting name", "Face tracking"), _("Stream facial expressions to the PC."), feature::face_tracking);
const auto body_tracker = ctx.system.body_tracker_supported();
std::vector<char> body_parts_default;
std::vector<std::string> body_parts_names;
std::vector<from_headset::body_part_mask> body_parts_bit;
for (const auto & [bit, name]: {
std::make_pair(from_headset::body_part_mask::chest, _C("virtual body tracker selection", "Chest")),
std::make_pair(from_headset::body_part_mask::left_elbow, _C("virtual body tracker selection", "Left elbow")),
std::make_pair(from_headset::body_part_mask::right_elbow, _C("virtual body tracker selection", "Right elbow")),
std::make_pair(from_headset::body_part_mask::hip, _C("virtual body tracker selection", "Hip")),
std::make_pair(from_headset::body_part_mask::left_knee, _C("virtual body tracker selection", "Left knee")),
std::make_pair(from_headset::body_part_mask::right_knee, _C("virtual body tracker selection", "Right knee")),
std::make_pair(from_headset::body_part_mask::left_foot, _C("virtual body tracker selection", "Left foot")),
std::make_pair(from_headset::body_part_mask::right_foot, _C("virtual body tracker selection", "Right foot")),
})
{
if (body_tracker == xr::body_tracker_type::fb and bit > from_headset::body_part_mask::hip)
break;
body_parts_default.push_back((default_config.body_part_mask & std::to_underlying(bit)) != 0);
body_parts_names.push_back(name);
body_parts_bit.push_back(bit);
}
bool changed = false;
if (body_tracker != xr::body_tracker_type::none)
{
list.push_back({
.id = "##body",
.label = _C("setting name", "Body tracking"),
.description = body_tracker == xr::body_tracker_type::fb or body_tracker == xr::body_tracker_type::meta
? _("Requires 'Hand and body tracking' to be enabled in the Quest movement tracking settings, otherwise body data will be guessed from controller and headset positions.")
: _("Stream body joint positions to the PC."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.check_feature(feature::body_tracking); },
.set_bool = [&config](bool v) { config.set_feature(feature::body_tracking, v); },
.default_bool = default_config.check_feature(feature::body_tracking),
.enabled = [&ctx] { return not ctx.in_game; },
.disabled_tooltip = disconnect_tip,
});
list.push_back({
.id = "##body_tracking_parts",
.label = _C("setting name", "Virtual body trackers"),
.description = _("Create virtual tracker devices."),
.ui = ui_kind::combo_multi,
.get_multi = [&config, &body_parts_bit](int index) {
const auto underlying = std::to_underlying(body_parts_bit[index]);
return config.body_part_mask & underlying; },
.set_multi = [&config, &body_parts_bit, &changed](int index, bool value) {
const auto underlying = std::to_underlying(body_parts_bit[index]);
if (value)
config.body_part_mask |= underlying;
else
config.body_part_mask &= ~underlying;
config.save();
changed = true; },
.options = [&body_parts_names]() { return body_parts_names; },
.title = _C("setting name", "Virtual body trackers"),
.default_multi = body_parts_default,
.disabled_tooltip = disconnect_tip,
});
}
ui::page_header(_cS("page header title", "Tracking"), _cS("page header subtitle", "Body and input tracking sent to the PC."));
render_settings(ctx, "##tracking", list);
return changed;
}
void settings_system(const settings_context & ctx)
{
auto & config = ctx.config;
auto & default_config = ctx.default_config;
std::vector<setting> list;
auto language_name = [](const std::locale & loc = std::locale()) {
return boost::locale::pgettext("language selection, replace with the name of the language", "English", loc);
};
std::vector<std::tuple<std::string, std::locale, std::string>> languages;
for (const auto & msg_info: get_locales())
{
std::string code = msg_info.language;
if (not msg_info.country.empty())
code += "_" + msg_info.country;
std::locale loc(std::locale(), boost::locale::gnu_gettext::create_messages_facet<char>(msg_info));
languages.emplace_back(language_name(loc), loc, std::move(code));
}
std::ranges::sort(languages, [](auto & l, auto & r) { return std::get<0>(l) < std::get<0>(r); });
auto language_index = [languages](const configuration & cfg) {
if (cfg.locale != "")
for (size_t i = 0; i < languages.size(); ++i)
if (std::get<2>(languages[i]) == cfg.locale)
return int(i) + 1;
return 0;
};
list.push_back({
.id = "##language",
.label = _("Language"),
.description = _C("setting name", "Interface language."),
.ui = ui_kind::combo,
.get_int = [&config, language_index] { return language_index(config); },
.set_int = [&config, languages](int v) {
config.locale = v == 0 ? "" : std::get<2>(languages[v - 1]);
config.save();
application::instance().load_locale(); },
.options = [languages] {
std::vector<std::string> opts;
opts.push_back(_C("item in the interface language combobox", "System language"));
for (const auto & [lang, loc, code]: languages)
opts.push_back(lang);
return opts; },
.title = _("Language"),
.default_int = language_index(default_config),
});
#ifdef __ANDROID__
if (application::get_hmd_traits().usb_net)
list.push_back({
.id = "##usbnet",
.label = _C("setting name", "USB networking"),
.description = _("Enables connection by USB without ADB or developer mode.\nMake sure the server allows IPv6 link-local only connections."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.usb_network; },
.set_bool = [&config](bool v) { config.usb_network = v;config.save(); application::instance().set_usb_networking(v); },
.default_bool = default_config.usb_network,
});
#endif
list.push_back({
.id = "##extended",
.label = _C("setting name", "Extended configuration"),
.description = _("Allows unsafe configuration values, use at your own risk."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.extended_config; },
.set_bool = [&config](bool v) { config.extended_config = v; config.save(); },
.default_bool = default_config.extended_config,
});
if (ctx.instance.has_extension(XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME))
{
list.push_back({
.id = "##high_power",
.label = _("High power mode"),
.description = _("Increase power usage to allow higher resolution and refresh rate. Drains battery and runs hot."),
.ui = ui_kind::toggle,
.get_bool = [&config] { return config.high_power_mode; },
.set_bool = [&config](bool v) { config.high_power_mode = v; config.save(); },
.default_bool = default_config.high_power_mode,
});
}
bool disable_instream_gui = false;
bool disable_instream_gui_popup_open = ImGui::IsPopupOpen("confirm disable in stream gui");
list.push_back({
.id = "##stream_gui",
.label = _C("setting name", "In-stream window"),
.description = _("Enables the configuration window to be shown while the game is streaming. If enabled, the window is activated by pressing both thumbsticks."),
.ui = ui_kind::toggle,
.get_bool = [&config, &disable_instream_gui_popup_open] { return config.enable_stream_gui and not disable_instream_gui_popup_open; },
.set_bool = [&ctx, &config, &disable_instream_gui](bool v) {
if (ctx.in_game and not v)
{
disable_instream_gui = true;
}
else
{
config.enable_stream_gui = v;
config.save();
} },
.default_bool = default_config.enable_stream_gui,
});
ui::page_header(_cS("page header title", "System"), _cS("page header suibtitle", "Language and advanced options."));
render_settings(ctx, "##system", list);
if (disable_instream_gui)
ImGui::OpenPopup("confirm disable in stream gui");
}
void settings_theme(const settings_context & ctx)
{
ui::theme & theme = ui::current();
auto & config = ctx.config;
auto & default_config = ctx.default_config;
ui::page_header(_cS("page header title", "Theme"), _cS("page header subtitle", "Accent color, palette and sizing of the interface."));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ui::metrics::card_item_spacing);
const float control_w = ui::metrics::setting_control_width;
ui::begin_card("##theme");
{
// Accent
ImGui::TextUnformatted(_cS("setting name", "Accent color"));
ImGui::Dummy({0, 2});
for (const auto & swatch: ui::accent_swatches())
{
const bool selected = theme.accent.x == swatch.base.x and theme.accent.y == swatch.base.y and theme.accent.z == swatch.base.z;
const auto flags = ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoBorder | (selected ? 0 : ImGuiColorEditFlags_NoDragDrop);
if (ImGui::ColorButton(swatch.name, swatch.base, flags, {ImGui::GetFrameHeight() * 1.4f, ImGui::GetFrameHeight() * 1.4f}))
{
ui::set_accent(swatch);
config.theme_accent = swatch.name;
config.save();
}
ImGui::SameLine();
}
ImGui::NewLine();
ui::row_separator();
// Preset
const auto preset_list = ui::presets();
std::vector<ui::combo_item> preset_items;
for (const auto & p: preset_list)
preset_items.push_back({p.localized_name.c_str()});
// seed the selection from the saved preset so the box matches what is applied
auto f = [&](const configuration & cfg) {
for (int i = 0; i < int(preset_list.size()); ++i)
if (preset_list[i].name == cfg.theme_preset)
return i;
return 1; // dark_default
};
static int preset = f(config);
static const int preset_default = f(default_config);
ui::setting_label(_cS("setting name", "Preset"), _cS("setting description", "Surface and background palette"), control_w);
if (ui::combo("##preset", _("Theme preset"), preset_items, &preset, control_w, &preset_default))
{
// keep the accent across a preset change, only the surfaces swap
const ImVec4 keep_accent = theme.accent;
const ImVec4 keep_hover = theme.accent_hovered;
const ImVec4 keep_active = theme.accent_active;
ui::set_theme(preset_list[preset]);
theme.accent = keep_accent;
theme.accent_hovered = keep_hover;
theme.accent_active = keep_active;
config.theme_preset = preset_list[preset].name;
config.save();
}
ui::row_separator();
// Rounding
static const int rounding_default = default_config.theme_rounding;
int rounding = int(theme.rounding);
ui::setting_label(_cS("setting label", "Rounding"), _cS("setting description", "Corner radius of controls"), control_w);
if (ui::slider_int("##rounding", &rounding, 0, 20, "%d px", {control_w, 0}, &rounding_default))
{
theme.rounding = float(rounding);
config.theme_rounding = theme.rounding;
config.save();
}
ui::row_separator();
static const int card_rounding_default = 14;
int card_rounding = int(theme.card_rounding);
ui::setting_label(_cS("setting label", "Card rounding"), _cS("setting description", "Corner radius of panels"), control_w);
if (ui::slider_int("##card_rounding", &card_rounding, 0, 28, "%d px", {control_w, 0}, &card_rounding_default))
{
theme.card_rounding = float(card_rounding);
config.theme_card_rounding = theme.card_rounding;
config.save();
}
ui::row_separator();
// global font scale, 100% is the design default
static const int font_scale_default = 100;
int font_scale = int(theme.font_scale * 100);
ui::setting_label(_cS("setting name", "Text size"), _cS("setting description", "Global font scale"), control_w);
if (ui::slider_int("##font_scale", &font_scale, 60, 140, "%d%%", {control_w, 0}, &font_scale_default))
{
theme.font_scale = float(font_scale) / 100.f;
config.theme_font_scale = theme.font_scale;
config.save();
}
ui::row_separator();
// Panel transparency, independent of the selected preset
static const int opacity_default = int(default_config.theme_background_alpha * 100 + 0.5);
int opacity = int(ui::background_alpha() * 100 + 0.5);
ui::setting_label(_cS("setting name", "Panel opacity"), _cS("setting description", "Opacity of the panel and card backgrounds"), control_w);
if (ui::slider_int("##opacity", &opacity, 20, 100, "%d%%", {control_w, 0}, &opacity_default))
{
ui::background_alpha() = float(opacity) / 100.f;
config.theme_background_alpha = ui::background_alpha();
config.save();
}
ui::end_card();
}
ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing
}
} // namespace wivrn::gui
-72
View File
@@ -1,72 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <cstdint>
#include <functional>
class configuration;
class imgui_context;
namespace xr
{
class instance;
class session;
class system;
} // namespace xr
namespace wivrn::gui
{
// what the shared settings pages need, in the lobby or the in-stream window
struct settings_context
{
configuration & config;
configuration & default_config;
xr::instance & instance;
xr::session & session;
xr::system & system;
imgui_context & imgui_ctx;
// recommended per-eye render resolution, for the resolution description
uint32_t recommended_width = 0;
uint32_t recommended_height = 0;
// streaming: connection-time settings are disabled, in-stream controls appear
bool in_game = false;
std::optional<bool> server_hid_forwarding;
// in-stream hooks, empty in the lobby
std::function<void()> on_streaming_changed; // refresh rate / spacewarp / bitrate
std::function<void()> enter_foveation_adjust; // thumbstick foveation sub-mode
std::function<void()> on_foveation_override_changed; // foveation override toggled
};
void settings_video(const settings_context &);
void settings_streaming(const settings_context &);
void settings_post_processing(const settings_context &);
void settings_audio(const settings_context &);
void settings_devices(const settings_context &);
bool settings_tracking(const settings_context &);
void settings_system(const settings_context &);
void settings_theme(const settings_context &);
} // namespace wivrn::gui
-243
View File
@@ -18,21 +18,10 @@
#include "hand_model.h"
#include "openxr/openxr.h"
#include "render/gpu_buffer.h"
#include "render/scene_components.h"
#include "vk/shader.h"
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <cstring>
#include <entt/entt.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <magic_enum.hpp>
#include <spdlog/spdlog.h>
#include <stdexcept>
#include <string>
#include <string_view>
namespace components
{
@@ -41,175 +30,8 @@ struct hand_joint
XrHandEXT hand;
XrHandJointEXT joint;
};
struct hand_mesh_fb_root
{
XrHandEXT hand;
};
} // namespace components
static glm::vec3 to_vec3(const XrVector3f & value)
{
return {value.x, value.y, value.z};
}
static glm::quat to_quat(const XrQuaternionf & value)
{
return glm::quat(value.w, value.x, value.y, value.z);
}
static glm::mat4 to_matrix(const XrPosef & pose)
{
return glm::translate(glm::mat4(1), to_vec3(pose.position)) * glm::mat4_cast(to_quat(pose.orientation));
}
template <typename T>
static void write_vertex_attribute(std::vector<std::byte> & buffer, size_t stride, size_t offset, size_t index, const T & value)
{
std::memcpy(buffer.data() + index * stride + offset, &value, sizeof(value));
}
static std::string normalize_hand_mesh_fb_semantic(std::string semantic)
{
std::transform(semantic.begin(), semantic.end(), semantic.begin(), [](unsigned char c) {
return static_cast<char>(std::toupper(c));
});
if (semantic.starts_with("IN_"))
semantic = semantic.substr(3);
return semantic;
}
static renderer::vertex_layout create_hand_mesh_fb_layout(scene & scene)
{
renderer::vertex_layout layout;
auto shader = load_shader(scene.device, "lit_skinned.vert");
for (const auto & input: shader->inputs)
{
std::string semantic = normalize_hand_mesh_fb_semantic(input.name);
const uint32_t binding = semantic == "POSITION" || semantic == "JOINTS" || semantic == "WEIGHTS" ? 0 : 1;
layout.add_vertex_attribute(semantic, input.format, binding, input.location, input.array_size);
}
return layout;
}
static const vk::VertexInputBindingDescription & find_hand_mesh_fb_binding(const renderer::vertex_layout & layout, uint32_t binding)
{
for (const auto & description: layout.bindings)
if (description.binding == binding)
return description;
throw std::runtime_error("Missing hand mesh FB vertex binding");
}
static const vk::VertexInputAttributeDescription & find_hand_mesh_fb_attribute(const renderer::vertex_layout & layout, std::string_view semantic)
{
for (size_t i = 0; i < layout.attribute_names.size(); ++i)
if (layout.attribute_names[i] == semantic)
return layout.attributes.at(i);
throw std::runtime_error("Missing hand mesh FB vertex attribute");
}
static std::shared_ptr<renderer::material> create_hand_mesh_fb_material(scene & scene, XrHandEXT hand)
{
return scene.create_material([hand](renderer::material & material) {
material.staging.base_color_factor = {0.5f, 0.5f, 0.5f, 1.0f};
material.staging.metallic_factor = 0.0f;
material.staging.roughness_factor = 0.5527864f;
material.name = hand == XR_HAND_LEFT_EXT ? "left-hand-mesh-material" : "right-hand-mesh-material";
material.double_sided = false;
material.blend_enable = false;
});
}
static std::shared_ptr<renderer::mesh> create_hand_mesh_fb_mesh(scene & scene, const xr::hand_tracker::mesh_data & mesh)
{
std::vector<uint16_t> indices;
indices.reserve(mesh.indices.size());
for (int16_t index: mesh.indices)
indices.push_back(static_cast<uint16_t>(index));
auto layout = create_hand_mesh_fb_layout(scene);
const auto & binding_0_layout = find_hand_mesh_fb_binding(layout, 0);
const auto & binding_1_layout = find_hand_mesh_fb_binding(layout, 1);
const size_t position_offset = find_hand_mesh_fb_attribute(layout, "POSITION").offset;
const size_t joints_offset = find_hand_mesh_fb_attribute(layout, "JOINTS").offset;
const size_t weights_offset = find_hand_mesh_fb_attribute(layout, "WEIGHTS").offset;
const size_t normal_offset = find_hand_mesh_fb_attribute(layout, "NORMAL").offset;
const size_t tangent_offset = find_hand_mesh_fb_attribute(layout, "TANGENT").offset;
const size_t texcoord_0_offset = find_hand_mesh_fb_attribute(layout, "TEXCOORD_0").offset;
const size_t texcoord_1_offset = find_hand_mesh_fb_attribute(layout, "TEXCOORD_1").offset;
const size_t color_offset = find_hand_mesh_fb_attribute(layout, "COLOR").offset;
std::vector<std::byte> binding_0(mesh.vertex_positions.size() * binding_0_layout.stride);
std::vector<std::byte> binding_1(mesh.vertex_positions.size() * binding_1_layout.stride);
glm::vec3 obb_min;
glm::vec3 obb_max;
for (size_t i = 0; i < mesh.vertex_positions.size(); ++i)
{
glm::vec3 position = to_vec3(mesh.vertex_positions.at(i));
glm::vec3 normal = to_vec3(mesh.vertex_normals.at(i));
glm::vec4 tangent{};
glm::vec2 texcoord_0{mesh.vertex_uvs.at(i).x, mesh.vertex_uvs.at(i).y};
glm::vec2 texcoord_1{};
glm::vec4 color{1, 1, 1, 1};
glm::vec4 joints{
static_cast<float>(mesh.vertex_blend_indices.at(i).x),
static_cast<float>(mesh.vertex_blend_indices.at(i).y),
static_cast<float>(mesh.vertex_blend_indices.at(i).z),
static_cast<float>(mesh.vertex_blend_indices.at(i).w)};
glm::vec4 weights{
mesh.vertex_blend_weights.at(i).x,
mesh.vertex_blend_weights.at(i).y,
mesh.vertex_blend_weights.at(i).z,
mesh.vertex_blend_weights.at(i).w};
if (i == 0)
obb_min = obb_max = position;
else
{
obb_min.x = std::min(obb_min.x, position.x);
obb_min.y = std::min(obb_min.y, position.y);
obb_min.z = std::min(obb_min.z, position.z);
obb_max.x = std::max(obb_max.x, position.x);
obb_max.y = std::max(obb_max.y, position.y);
obb_max.z = std::max(obb_max.z, position.z);
}
write_vertex_attribute(binding_0, binding_0_layout.stride, position_offset, i, position);
write_vertex_attribute(binding_0, binding_0_layout.stride, joints_offset, i, joints);
write_vertex_attribute(binding_0, binding_0_layout.stride, weights_offset, i, weights);
write_vertex_attribute(binding_1, binding_1_layout.stride, normal_offset, i, normal);
write_vertex_attribute(binding_1, binding_1_layout.stride, tangent_offset, i, tangent);
write_vertex_attribute(binding_1, binding_1_layout.stride, texcoord_0_offset, i, texcoord_0);
write_vertex_attribute(binding_1, binding_1_layout.stride, texcoord_1_offset, i, texcoord_1);
write_vertex_attribute(binding_1, binding_1_layout.stride, color_offset, i, color);
}
fastgltf::Asset asset;
gpu_buffer staging_buffer(scene.physical_device, asset);
auto hand_mesh_fb_mesh = std::make_shared<renderer::mesh>();
auto & primitive = hand_mesh_fb_mesh->primitives.emplace_back();
primitive.indexed = true;
primitive.index_count = indices.size();
primitive.vertex_count = mesh.vertex_positions.size();
primitive.index_type = vk::IndexType::eUint16;
primitive.index_offset = staging_buffer.add_indices(indices);
primitive.vertex_offset.push_back(staging_buffer.add_vertices(binding_0));
primitive.vertex_offset.push_back(staging_buffer.add_vertices(binding_1));
primitive.layout = std::move(layout);
primitive.obb_min = obb_min;
primitive.obb_max = obb_max;
primitive.vertex_shader = "lit_skinned.vert";
primitive.cull_mode = vk::CullModeFlagBits::eBack;
primitive.front_face = vk::FrontFace::eCounterClockwise;
primitive.topology = vk::PrimitiveTopology::eTriangleList;
hand_mesh_fb_mesh->buffer = std::make_shared<buffer_allocation>(staging_buffer.copy_to_gpu(scene.device));
return hand_mesh_fb_mesh;
}
static const std::array<std::pair<XrHandJointEXT, std::string_view>, XR_HAND_JOINT_COUNT_EXT - 1 /* No palm in gltf */> joints{{
// clang-format off
{XR_HAND_JOINT_WRIST_EXT, "wrist"},
@@ -260,34 +82,6 @@ void hand_model::add_hand(scene & scene,
scene.world.emplace<components::hand_joint>(entity, hand, (XrHandJointEXT)-1);
}
void hand_model::add_hand(scene & scene,
XrHandEXT hand,
const xr::hand_tracker::mesh_data & mesh,
uint32_t layer_mask)
{
auto material = create_hand_mesh_fb_material(scene, hand);
entt::entity entity = scene.world.create();
auto & node = scene.world.emplace<components::node>(entity);
node.name = hand == XR_HAND_LEFT_EXT ? "left-hand-mesh" : "right-hand-mesh";
node.mesh = create_hand_mesh_fb_mesh(scene, mesh);
for (auto & primitive: node.mesh->primitives)
primitive.material_ = material;
node.visible = false;
node.layer_mask = layer_mask;
node.joints.reserve(mesh.joint_bind_poses.size());
scene.world.emplace<components::hand_mesh_fb_root>(entity, hand);
for (size_t i = 0; i < mesh.joint_bind_poses.size(); ++i)
{
entt::entity joint_entity = scene.world.create();
auto & joint_node = scene.world.emplace<components::node>(joint_entity);
joint_node.parent = entity;
joint_node.name = std::string(magic_enum::enum_name(static_cast<XrHandJointEXT>(i)));
node.joints.emplace_back(joint_entity, glm::inverse(to_matrix(mesh.joint_bind_poses[i])));
}
}
void hand_model::apply(entt::registry & scene,
const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & left_hand,
const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & right_hand)
@@ -333,41 +127,4 @@ void hand_model::apply(entt::registry & scene,
break;
}
}
for (auto && [entity, hand_root, node]: scene.view<components::hand_mesh_fb_root, components::node>().each())
{
const auto & joints = hand_root.hand == XR_HAND_LEFT_EXT ? left_hand : right_hand;
if (!joints)
{
node.visible = false;
continue;
}
node.visible = true;
const auto & wrist_pose = (*joints)[XR_HAND_JOINT_WRIST_EXT].first.pose;
glm::vec3 wrist_position = to_vec3(wrist_pose.position);
glm::quat wrist_orientation = to_quat(wrist_pose.orientation);
glm::quat wrist_orientation_inv = glm::conjugate(wrist_orientation);
node.position = wrist_position;
node.orientation = wrist_orientation;
for (size_t i = 0; i < node.joints.size(); ++i)
{
auto & joint_node = scene.get<components::node>(node.joints[i].first);
if (i == XR_HAND_JOINT_WRIST_EXT)
{
joint_node.position = {};
joint_node.orientation = {1, 0, 0, 0};
continue;
}
const auto & pose = (*joints)[i].first.pose;
glm::vec3 position = to_vec3(pose.position);
glm::quat orientation = to_quat(pose.orientation);
joint_node.position = wrist_orientation_inv * (position - wrist_position);
joint_node.orientation = glm::normalize(wrist_orientation_inv * orientation);
}
}
}
-5
View File
@@ -31,11 +31,6 @@ void add_hand(scene & scene,
const std::filesystem::path & gltf_path,
uint32_t layer_mask);
void add_hand(scene & scene,
XrHandEXT hand,
const xr::hand_tracker::mesh_data & mesh,
uint32_t layer_mask);
void apply(entt::registry & scene,
const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & left_hand,
const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & right_hand);
+2 -1
View File
@@ -19,6 +19,7 @@
#include "input_profile.h"
#include "application.h"
#include "hardware.h"
#include "render/scene_components.h"
#include "utils/mapped_file.h"
#include "xr/space.h"
@@ -305,7 +306,7 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p
else
continue;
auto && [ray_entity, ray_node] = scene.add_gltf(application::get_hmd_traits().controller_ray_model, layer_mask_ray);
auto && [ray_entity, ray_node] = scene.add_gltf(controller_ray_model_name(), layer_mask_ray);
ray_node.name = (std::string)layout.key + "_ray";
spdlog::debug("Created entity {}", ray_node.name);
+53 -72
View File
@@ -23,6 +23,7 @@
#include "constants.h"
#include "glm/geometric.hpp"
#include "hand_model.h"
#include "hardware.h"
#include "imgui.h"
#include "openxr/openxr.h"
#include "protocol_version.h"
@@ -64,10 +65,6 @@
#include "vk/renderdoc.h"
#endif
#ifdef __ANDROID__
#include "android/usb.h"
#endif
using namespace std::chrono_literals;
static bool force_autoconnect = false;
@@ -125,19 +122,24 @@ static glm::quat compute_gui_orientation(glm::vec3 head_position, glm::vec3 new_
void scenes::lobby::move_gui(glm::vec3 head_position, glm::vec3 new_gui_position)
{
using constants::gui::popup_position;
using constants::lobby::keyboard_pitch;
using constants::lobby::keyboard_position;
using constants::lobby::popup_position;
auto q = compute_gui_orientation(head_position, new_gui_position);
auto M = glm::mat3_cast(q); // plane-to-world transform
// Main window
imgui_ctx->layers()[0].position = new_gui_position;
imgui_ctx->layers()[0].orientation = q;
// Popup and keyboard track the main window
imgui_ctx->place_layer_relative(1, 0, popup_position);
imgui_ctx->place_layer_relative(2, 0, keyboard_position, glm::quat(cos(keyboard_pitch / 2), sin(keyboard_pitch / 2), 0, 0));
// Popup
imgui_ctx->layers()[1].position = new_gui_position + M * popup_position;
imgui_ctx->layers()[1].orientation = q;
// Keyboard
imgui_ctx->layers()[2].position = new_gui_position + M * keyboard_position;
imgui_ctx->layers()[2].orientation = q * glm::quat(cos(keyboard_pitch / 2), sin(keyboard_pitch / 2), 0, 0);
}
scenes::lobby::lobby() :
@@ -169,8 +171,6 @@ scenes::lobby::lobby() :
keyboard.set_layout(config.virtual_keyboard_layout);
apply_theme_settings();
if (config.first_run)
current_tab = tab::first_run;
@@ -202,16 +202,6 @@ static std::string ip_address_to_string(const in6_addr & addr)
return buf;
}
static std::string ip_address_to_string(const sockaddr_in & addr)
{
return ip_address_to_string(addr.sin_addr);
}
static std::string ip_address_to_string(const sockaddr_in6 & addr)
{
return ip_address_to_string(addr.sin6_addr);
}
std::unique_ptr<wivrn_session> scenes::lobby::connect_to_session(wivrn_discover::service service, bool manual_connection)
{
if (!manual_connection)
@@ -253,18 +243,12 @@ std::unique_ptr<wivrn_session> scenes::lobby::connect_to_session(wivrn_discover:
{
switch (i->ai_family)
{
case AF_INET: {
auto addr = (sockaddr_in *)i->ai_addr;
addr->sin_port = htons(service.port);
service.addresses.push_back({.address = *addr});
}
break;
case AF_INET6: {
auto addr = (sockaddr_in6 *)i->ai_addr;
addr->sin6_port = htons(service.port);
service.addresses.push_back({.address = *addr});
}
break;
case AF_INET:
service.addresses.push_back(((sockaddr_in *)i->ai_addr)->sin_addr);
break;
case AF_INET6:
service.addresses.push_back(((sockaddr_in6 *)i->ai_addr)->sin6_addr);
break;
}
}
@@ -272,22 +256,22 @@ std::unique_ptr<wivrn_session> scenes::lobby::connect_to_session(wivrn_discover:
}
std::string error;
for (const auto & entry: service.addresses)
for (const std::variant<in_addr, in6_addr> & address: service.addresses)
{
std::string address_string = std::visit([](const auto & address) {
std::string address_string = std::visit([](auto & address) {
return ip_address_to_string(address);
},
entry.address);
address);
struct connection_cancelled
{};
try
{
spdlog::info("Connection to {}", address_string);
spdlog::debug("Connection to {}", address_string);
return std::visit([this, &service](auto & address) {
return std::make_unique<wivrn_session>(address, service.tcp_only, keypair, [&](int fd) {
return std::make_unique<wivrn_session>(address, service.port, service.tcp_only, keypair, [&](int fd) {
auto request = pin_request.lock();
request->pin_requested = true;
request->pin_cancelled = false;
@@ -329,7 +313,7 @@ std::unique_ptr<wivrn_session> scenes::lobby::connect_to_session(wivrn_discover:
return request->pin;
});
},
entry.address);
address);
}
catch (connection_cancelled)
{
@@ -360,11 +344,6 @@ void scenes::lobby::update_server_list()
if (not discover)
return;
#ifdef __ANDROID__
if (usb_link_properties_changed())
discover.emplace();
#endif
std::vector<wivrn_discover::service> discovered_services = discover->get_services();
// TODO: only if discovered_services changed
@@ -655,7 +634,7 @@ static void stick_finger_to_gui(std::array<xr::hand_tracker::joint, XR_HAND_JOIN
std::vector<std::pair<glm::vec3, float>> intersections; // Target position of the finger tip, distance to the GUI plane
for (const imgui_context::window_viewport & layer: layers)
{
// Ignore layers that are not absolutely positioned
// Ignore layers that are not absolutely positionned
if (layer.space != xr::spaces::world)
continue;
@@ -889,8 +868,6 @@ void scenes::lobby::render(const XrFrameState & frame_state)
if (next_scene)
{
server_hid_forwarding = next_scene->hid_forwarding_enabled();
switch (next_scene->current_state())
{
case scenes::stream::state::streaming:
@@ -1088,14 +1065,20 @@ void scenes::lobby::render(const XrFrameState & frame_state)
if (composition_layer_depth_test_supported)
set_depth_test(true, XR_COMPARE_OP_ALWAYS_FB);
bool dim_gui = imgui_ctx->is_modal_popup_shown() and composition_layer_color_scale_bias_supported;
for (auto & [z_index, layer]: imgui_layers)
{
if (z_index < constants::lobby::zindex_recenter_tip)
{
add_quad_layer(layer.layerFlags, layer.space, layer.eyeVisibility, layer.subImage, layer.pose, layer.size);
if (dim_gui)
set_color_scale_bias(constants::lobby::dimming_scale, constants::lobby::dimming_bias);
if (composition_layer_depth_test_supported)
set_depth_test(true, XR_COMPARE_OP_LESS_OR_EQUAL_FB);
dim_gui = false; // Only dim the main window
}
}
@@ -1131,7 +1114,7 @@ void scenes::lobby::on_focused()
auto views = system.view_configuration_views(viewconfig);
assert(views.size() == 2); // FIXME
stream_view = application::get_hmd_traits().override_view(views[0]);
stream_view = override_view(views[0], guess_model());
width = views[0].recommendedImageRectWidth;
height = views[0].recommendedImageRectHeight;
@@ -1147,12 +1130,12 @@ void scenes::lobby::on_focused()
catch (std::exception & e)
{
spdlog::warn("Cannot load environment from {}: {}, reverting to default", config.environment_model, e.what());
config.environment_model = application::get_default_config().environment_model;
config.environment_model = configuration{}.environment_model;
lobby_entity = add_gltf(config.environment_model, layer_lobby).first;
config.save();
}
const auto & profile = application::get_hmd_traits().controller_profile;
std::string profile = controller_name();
input.emplace(
*this,
"assets://controllers/" + profile + "/profile.json",
@@ -1165,7 +1148,7 @@ void scenes::lobby::on_focused()
for (auto i: {xr::spaces::aim_left, xr::spaces::aim_right, xr::spaces::grip_left, xr::spaces::grip_right})
{
auto [p, q] = input->offset[i] = application::get_hmd_traits().controller_offset(i);
auto [p, q] = input->offset[i] = controller_offset(controller_name(), i);
auto rot = glm::degrees(glm::eulerAngles(q));
spdlog::info("Initializing offset of space {} to ({}, {}, {}) mm, ({}, {}, {})°",
@@ -1194,25 +1177,8 @@ void scenes::lobby::on_focused()
{
left_hand = session.create_hand_tracker(XR_HAND_LEFT_EXT);
right_hand = session.create_hand_tracker(XR_HAND_RIGHT_EXT);
bool using_hand_mesh_fb = false;
if (system.hand_mesh_fb_supported())
{
const auto * left_hand_mesh_fb = left_hand->mesh();
const auto * right_hand_mesh_fb = right_hand->mesh();
if (left_hand_mesh_fb and right_hand_mesh_fb)
{
hand_model::add_hand(*this, XR_HAND_LEFT_EXT, *left_hand_mesh_fb, layer_controllers);
hand_model::add_hand(*this, XR_HAND_RIGHT_EXT, *right_hand_mesh_fb, layer_controllers);
using_hand_mesh_fb = true;
}
}
if (!using_hand_mesh_fb)
{
hand_model::add_hand(*this, XR_HAND_LEFT_EXT, "assets://left-hand.glb", layer_controllers);
hand_model::add_hand(*this, XR_HAND_RIGHT_EXT, "assets://right-hand.glb", layer_controllers);
}
hand_model::add_hand(*this, XR_HAND_LEFT_EXT, "assets://left-hand.glb", layer_controllers);
hand_model::add_hand(*this, XR_HAND_RIGHT_EXT, "assets://right-hand.glb", layer_controllers);
}
std::vector imgui_inputs{
@@ -1296,7 +1262,20 @@ void scenes::lobby::on_focused()
vps,
image_cache);
about_picture = imgui_ctx->load_texture("assets://wivrn.ktx2");
auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
auto tm = std::localtime(&t);
switch (tm->tm_mon)
{
case 5:
about_picture = imgui_ctx->load_texture("assets://wivrn-pride.ktx2");
break;
case 11:
about_picture = imgui_ctx->load_texture("assets://wivrn-christmas.ktx2");
break;
default:
about_picture = imgui_ctx->load_texture("assets://wivrn.ktx2");
break;
}
default_environment_screenshot = imgui_ctx->load_texture("assets://default-environment.ktx2");
@@ -1335,12 +1314,13 @@ void scenes::lobby::on_focused()
.gltf_url = "default",
.builtin = true,
.override_order = -1,
.local_gltf_path = application::get_default_config().environment_model,
.local_gltf_path = configuration{}.environment_model,
.screenshot = imgui_ctx->load_texture("assets://default-environment.ktx2")});
std::ranges::sort(local_environments, std::less{});
setup_passthrough();
multicast = application::get_wifi_lock().get_multicast_lock();
discover.emplace();
session.set_performance_level(XR_PERF_SETTINGS_DOMAIN_CPU_EXT, XR_PERF_SETTINGS_LEVEL_SUSTAINED_HIGH_EXT);
@@ -1372,6 +1352,8 @@ void scenes::lobby::on_unfocused()
left_hand.reset();
right_hand.reset();
face_tracker.emplace<std::monostate>();
multicast.reset();
}
void scenes::lobby::on_xr_event(const xr::event & event)
@@ -1423,7 +1405,6 @@ scene::meta & scenes::lobby::get_meta_scene()
"/interaction_profiles/bytedance/pico_neo3_controller",
"/interaction_profiles/bytedance/pico4_controller",
"/interaction_profiles/bytedance/pico4s_controller",
"/interaction_profiles/yvr/touch_controller_yvr",
"/interaction_profiles/htc/vive_focus3_controller",
},
{
+5 -20
View File
@@ -27,6 +27,7 @@
#include "scenes/lobby_keyboard.h"
#include "utils/mapped_file.h"
#include "utils/thread_safe.h"
#include "wifi_lock.h"
#include "wivrn_config.h"
#include "wivrn_discover.h"
#include "xr/face_tracker.h"
@@ -50,13 +51,13 @@ class stream;
class lobby : public scene_impl<lobby>
{
std::optional<wivrn_discover> discover;
wifi_lock::multicast multicast;
std::string add_server_window_prettyname;
std::string add_server_window_hostname;
int add_server_window_port = wivrn::default_port;
bool add_server_tcp_only = false;
std::string add_server_cookie;
std::string delete_server_cookie; // server pending a delete confirmation
utils::future<std::unique_ptr<wivrn_session>, std::string> async_session;
std::optional<std::string> async_error;
@@ -64,10 +65,6 @@ class lobby : public scene_impl<lobby>
std::string server_name;
bool autoconnect_enabled = true;
// Last known uinput forwarding state of the connected server, kept after disconnection so the
// settings can warn that forwarded keyboard and mouse will not reach the server.
std::optional<bool> server_hid_forwarding;
std::optional<input_profile> input;
entt::entity lobby_entity;
@@ -119,15 +116,9 @@ class lobby : public scene_impl<lobby>
{
first_run,
server_list,
video,
audio,
streaming,
settings,
post_processing,
devices,
tracking,
system,
customize,
theme,
#if WIVRN_CLIENT_DEBUG_MENU
debug,
#endif
@@ -224,22 +215,16 @@ class lobby : public scene_impl<lobby>
std::pair<entt::entity, int> debug_primitive_to_highlight = {entt::null, 0};
#endif
void draw_features_status(XrTime predicted_display_time);
void gui_connecting(locked_notifiable<pin_request_data> & request);
void gui_enter_pin(locked_notifiable<pin_request_data> & request);
void gui_connected(XrTime predicted_display_time);
void gui_disconnected();
void gui_server_list();
void gui_new_server();
void gui_video();
void gui_streaming();
void gui_audio();
void gui_devices();
void gui_tracking();
void gui_system();
void gui_settings();
void gui_post_processing();
void gui_customize(XrTime predicted_display_time);
void gui_theme();
void apply_theme_settings(); // push the saved theme config into the global theme
void gui_debug_node_hierarchy(entt::entity root = entt::null);
void gui_debug();
void gui_about();
+1181 -493
View File
File diff suppressed because it is too large Load Diff
+389 -190
View File
@@ -17,6 +17,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#define IMGUI_DEFINE_MATH_OPERATORS
#include "lobby.h"
#include "application.h"
@@ -26,8 +28,6 @@
#include "imspinner.h"
#include "render/image_writer.h"
#include "render/scene_renderer.h"
#include "render/ui_theme.h"
#include "render/ui_widgets.h"
#include "utils/files.h"
#include "utils/i18n.h"
#include "utils/json_string.h"
@@ -39,7 +39,7 @@
#include <spdlog/fmt/chrono.h>
#include <spdlog/spdlog.h>
#include "IconsFontAwesome7.h"
#include "IconsFontAwesome6.h"
using namespace std::chrono_literals;
@@ -337,140 +337,278 @@ void scenes::lobby::download_environment_list()
scenes::lobby::environment_item_action scenes::lobby::environment_item(environment_model & model, bool download_screenshot)
{
namespace ui = wivrn::ui;
environment_item_action action = environment_item_action::none;
const bool local = std::ranges::contains(local_environments, model.name, &environment_model::name);
ImGuiWindow * window = ImGui::GetCurrentWindow();
const ImGuiStyle & style = ImGui::GetStyle();
bool local = std::ranges::contains(local_environments, model.name, &environment_model::name);
// lazily load the screenshot texture
if (model.screenshot == 0)
{
if (download_screenshot)
{
if (model.screenshot_url != "" and not try_get_download_handle(model.screenshot_url))
{
spdlog::info("Downloading {}", model.screenshot_url);
download(model.screenshot_url, [this, url = model.screenshot_url](libcurl::curl_handle & handle) {
try
{
auto png = handle.get_response_bytes();
auto tex = imgui_ctx->load_texture(png);
for (auto & m: downloadable_environments)
if (m.screenshot_url == url)
{
m.screenshot = tex;
m.screenshot_png = std::vector<std::byte>{png.begin(), png.end()};
}
}
catch (std::exception & e)
{
spdlog::warn("Cannot load image from {}: {}", handle.get_url(), e.what());
for (auto & m: downloadable_environments)
if (m.screenshot_url == url)
{
m.screenshot_url = "";
m.screenshot = default_environment_screenshot;
}
}
});
}
}
else if (model.local_screenshot_path != "" and std::filesystem::exists(model.local_screenshot_path))
{
try
{
model.screenshot = imgui_ctx->load_texture(utils::mapped_file{model.local_screenshot_path});
}
catch (std::exception & e)
{
spdlog::warn("Cannot load screenshot {}: {}", model.local_screenshot_path.native(), e.what());
std::error_code ec;
std::filesystem::remove(model.local_screenshot_path, ec);
model.local_screenshot_path = "";
model.screenshot = default_environment_screenshot;
}
}
}
static std::unordered_map<std::string, float> expanded_height;
const auto & config = application::get_config();
const bool selected = (config.passthrough_enabled and model.local_gltf_path == "") or
(not config.passthrough_enabled and config.environment_model == model.local_gltf_path);
// subtitle: author / description / size, one per line
std::string subtitle;
auto add_line = [&](const std::string & s) {
if (s.empty())
return;
if (not subtitle.empty())
subtitle += "\n";
subtitle += s;
float width = ImGui::GetWindowSize().x - ImGui::GetCurrentWindow()->ScrollbarSizes.x - 2 * ImGui::GetCurrentWindow()->WindowPadding.x;
ImVec2 screenshot_size{256, 256};
ImVec2 default_selectable_size{
width,
screenshot_size.y + 2 * style.FramePadding.y // Screenshot size including padding
// + style.ItemSpacing.y // Spacing
// + ImGui::GetFontSize() + 2 * style.FramePadding.y // Progress bar height
};
if (model.author != "")
add_line(fmt::format(_F("Author: {}"), model.author));
if (model.description != "")
add_line(model.builtin ? std::string(_(model.description.c_str())) : model.description);
if (not model.builtin)
add_line(fmt::format(_F("Size: {:.1f} MB"), model.size * 1.0e-6));
ImVec2 selectable_size = default_selectable_size;
const char * icon = model.local_gltf_path == "" ? ICON_FA_VIDEO : (model.builtin ? ICON_FA_TABLE_CELLS : ICON_FA_IMAGE);
const std::string title = model.builtin ? std::string(_(model.name.c_str())) : model.name;
ImGui::PushID(model.gltf_url.c_str());
const float bh = ImGui::GetFrameHeight() * ui::metrics::control_height;
auto handle = try_get_download_handle(model.gltf_url);
const bool transferring = handle and handle->get_state() == libcurl::state::transferring;
// measure the trailing control so the row body click area can exclude it
const std::string active_l = ui::icon_label(ICON_FA_CHECK, _C("chip displayed next to the selected environment in the settings", "Active"));
const ImVec2 active_sz = ui::chip_size(active_l);
float trailing = 0;
if (selected)
trailing = active_sz.x + ui::metrics::list_row_pad;
else if (transferring or (local and not model.builtin))
trailing = bh + ui::metrics::list_row_pad;
const auto row = ui::begin_list_row("##env", icon, model.screenshot, title, subtitle, selected, trailing, 0, true);
if (row.clicked and not selected)
action = local ? environment_item_action::use_model : environment_item_action::download_model;
const float x = row.max.x;
if (selected)
bool expanded = false;
if (auto iter = expanded_height.find(model.gltf_url); iter != expanded_height.end())
{
ImGui::SetCursorScreenPos(row.trailing(x, active_sz));
ui::chip(active_l, ui::chip_style::success);
}
else if (transferring)
{
const int64_t total = handle->get_content_length() > 0 ? handle->get_content_length() : model.size;
const float fraction = total > 0 ? float(handle->get_progress()) / float(total) : -1.f;
ImGui::SetCursorScreenPos(row.trailing(x, {bh, bh}));
if (ui::cancel_progress_button("##cancel", fraction, {bh, bh}, _S("Cancel")))
handle->cancel();
}
else if (local and not model.builtin)
{
ImGui::SetCursorScreenPos(row.trailing(x, {bh, bh}));
if (ui::icon_button(ICON_FA_TRASH, {bh, bh}, false, _S("Delete this model")))
action = environment_item_action::delete_model;
selectable_size.y = std::max(selectable_size.y, iter->second);
expanded = true;
}
// surface download errors
if (handle)
ImTextureID screenshot = model.screenshot;
if (ImRect{window->DC.CursorPos, window->DC.CursorPos + selectable_size}.Overlaps(window->ClipRect))
{
if (handle->get_state() == libcurl::state::error)
if (screenshot == 0)
{
if (handle->get_curl_code() == CURLE_HTTP_RETURNED_ERROR)
load_environment_status = fmt::format(_F("HTTP error {} when downloading {}"), handle->get_response_code(), handle->get_url());
else
load_environment_status = fmt::format(_F("Curl error when downloading {}\n{}: {}"), handle->get_url(), magic_enum::enum_name(handle->get_curl_code()), curl_easy_strerror(handle->get_curl_code()));
handle->reset();
if (download_screenshot)
{
if (model.screenshot_url != "" and not try_get_download_handle(model.screenshot_url))
{
spdlog::info("Downloading {}", model.screenshot_url);
download(model.screenshot_url,
[this, url = model.screenshot_url](libcurl::curl_handle & handle) {
try
{
auto png = handle.get_response_bytes();
auto screenshot = imgui_ctx->load_texture(png);
for (auto & model: downloadable_environments)
{
if (model.screenshot_url == url)
{
model.screenshot = screenshot;
model.screenshot_png = std::vector<std::byte>{png.begin(), png.end()};
}
}
}
catch (std::exception & e)
{
spdlog::warn("Cannot load image from {}: {}", handle.get_url(), e.what());
for (auto & model: downloadable_environments)
{
if (model.screenshot_url == url)
{
model.screenshot_url = "";
model.screenshot = default_environment_screenshot;
}
}
}
});
}
}
else if (model.local_screenshot_path != "" and std::filesystem::exists(model.local_screenshot_path))
{
try
{
spdlog::info("Loading {}", model.local_screenshot_path.native());
screenshot = model.screenshot = imgui_ctx->load_texture(utils::mapped_file{model.local_screenshot_path});
}
catch (std::exception & e)
{
spdlog::warn("Cannot load screenshot {}: {}", model.local_screenshot_path.native(), e.what());
std::error_code ec;
std::filesystem::remove(model.local_screenshot_path, ec); // Ignore errors
model.local_screenshot_path = ""; // Avoid subsequent loading errors
model.screenshot = default_environment_screenshot;
}
}
}
else if (handle->get_state() == libcurl::state::cancelled)
handle->reset();
}
ui::end_list_row();
ImGui::PopID();
auto backup_cursor = ImGui::GetCursorScreenPos();
const auto & config = application::get_config();
bool selected = (config.passthrough_enabled and model.local_gltf_path == "") or
(not config.passthrough_enabled and config.environment_model == model.local_gltf_path);
ImGui::SetNextItemAllowOverlap();
// Use ImGuiSelectableFlags_AllowDoubleClick to have ImGuiButtonFlags_PressedOnClickRelease in ImGui::Selectable
if (ImGui::Selectable(("##" + model.gltf_url).c_str(), &selected, ImGuiSelectableFlags_AllowDoubleClick, selectable_size))
{
if (local)
action = environment_item_action::use_model;
else
action = environment_item_action::download_model;
}
imgui_ctx->vibrate_on_hover();
auto end_cursor = ImGui::GetCursorScreenPos();
// Remove the height of the progress bar if a transfer is in progress
float text_clip_height = selectable_size.y + style.FramePadding.y;
if (auto handle = try_get_download_handle(model.gltf_url); handle and handle->get_state() == libcurl::state::transferring)
text_clip_height -= ImGui::GetFontSize() + 2 * style.FramePadding.y + style.ItemSpacing.y;
// Display the screenshot
ImGui::SetCursorScreenPos(backup_cursor + ImVec2(style.FramePadding.x, 0));
ImGui::Image(screenshot ? screenshot : default_environment_screenshot, screenshot_size);
ImGui::PushClipRect(backup_cursor, backup_cursor + ImVec2(selectable_size.x, text_clip_height), true);
float indent = screenshot_size.x + style.FramePadding.x + 2 * style.ImageBorderSize + style.ItemSpacing.x;
// Display the text
std::pair<std::string, ImVec2> text_name;
std::pair<std::string, ImVec2> text_author;
std::pair<std::string, ImVec2> text_description;
std::pair<std::string, ImVec2> text_filesize;
text_name.first = model.builtin ? _(model.name.c_str()) : model.name;
if (model.author != "")
text_author.first = fmt::format(_F("Author: {}"), model.author);
if (model.description != "")
text_description.first = model.description;
if (not model.builtin)
text_filesize.first = fmt::format(_F("Size: {:.1f} MB"), model.size * 1.0e-6);
const float wrap_width = selectable_size.x - indent - style.FramePadding.x;
// clang-format off
text_name.second = ImGui::CalcTextSize(text_name.first.data(), text_name.first.data() + text_name.first.size(), false, wrap_width);
text_author.second = ImGui::CalcTextSize(text_author.first.data(), text_author.first.data() + text_author.first.size(), false, wrap_width);
text_description.second = ImGui::CalcTextSize(text_description.first.data(), text_description.first.data() + text_description.first.size(), false, wrap_width);
text_filesize.second = ImGui::CalcTextSize(text_filesize.first.data(), text_filesize.first.data() + text_filesize.first.size(), false, wrap_width);
// clang-format on
ImGui::SetCursorScreenPos(backup_cursor);
ImVec2 text_pos = backup_cursor + ImVec2(indent, 0);
float text_height = 0;
ImGui::RenderTextWrapped(text_pos, text_name.first.data(), text_name.first.data() + text_name.first.size(), wrap_width);
text_height += text_name.second.y + style.ItemSpacing.y;
if (text_author.first != "")
{
ImGui::RenderTextWrapped(text_pos + ImVec2(0, text_height), text_author.first.data(), text_author.first.data() + text_author.first.size(), wrap_width);
text_height += text_author.second.y + style.ItemSpacing.y;
}
if (text_description.first != "")
{
ImGui::RenderTextWrapped(text_pos + ImVec2(0, text_height), text_description.first.data(), text_description.first.data() + text_description.first.size(), wrap_width);
text_height += text_description.second.y + style.ItemSpacing.y;
}
if (text_filesize.first != "")
{
ImGui::RenderTextWrapped(text_pos + ImVec2(0, text_height), text_filesize.first.data(), text_filesize.first.data() + text_filesize.first.size(), wrap_width);
text_height += text_filesize.second.y + style.ItemSpacing.y;
}
ImGui::PopClipRect();
// Display the expand/collapse button
if (text_height > default_selectable_size.y - 2 * style.FramePadding.y)
{
const char * button_text = expanded ? ICON_FA_CHEVRON_UP : ICON_FA_CHEVRON_DOWN;
auto expand_size = ImGui::CalcTextSize(button_text) + style.FramePadding * 2.0f;
float radius = std::max(expand_size.x, expand_size.y) / 2;
ImGui::SetCursorScreenPos(ImVec2(
backup_cursor.x + selectable_size.x / 2 - radius,
backup_cursor.y + selectable_size.y + style.FramePadding.y - radius));
// Triple hash so that the button text is not used to compute the button ID and
// avoid vibrating the controller when the text changes
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, radius);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
if (ImGui::Button((button_text + ("###expand-" + model.gltf_url)).c_str(), ImVec2(radius * 2, radius * 2)))
{
if (expanded)
expanded_height.erase(model.gltf_url);
else
expanded_height[model.gltf_url] = text_height + 2 * style.FramePadding.y;
}
imgui_ctx->vibrate_on_hover();
ImGui::PopStyleColor();
ImGui::PopStyleVar(); // ImGuiStyleVar_FrameRounding
}
// Display the delete button
if (local and not model.builtin)
{
auto delete_size = ImGui::CalcTextSize(ICON_FA_TRASH) + style.FramePadding * 2;
ImGui::SetCursorScreenPos(ImVec2(
backup_cursor.x + width - style.FramePadding.x - delete_size.x,
backup_cursor.y));
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f));
if (ImGui::Button((ICON_FA_TRASH "##delete-" + model.name).c_str()))
action = environment_item_action::delete_model;
if (ImGui::IsItemHovered())
imgui_ctx->tooltip(_("Delete this model"));
imgui_ctx->vibrate_on_hover();
ImGui::PopStyleColor(3);
}
// Display the download progress
else if (auto handle = try_get_download_handle(model.gltf_url))
{
switch (handle->get_state())
{
case libcurl::state::transferring: {
ImVec2 cancel_size = ImGui::CalcTextSize(ICON_FA_STOP) + style.FramePadding * 2;
ImGui::SetCursorScreenPos(ImVec2(
backup_cursor.x + screenshot_size.x + style.FramePadding.x + style.ItemSpacing.x,
backup_cursor.y + selectable_size.y - (ImGui::GetFontSize() + 2 * style.FramePadding.y)));
float progress_width = width - cancel_size.x - screenshot_size.x - 2 * style.FramePadding.x - 2 * style.ItemSpacing.x;
if (handle->get_content_length() > 0)
ImGui::ProgressBar(handle->get_progress() / (float)handle->get_content_length(), {progress_width, 0});
else
ImGui::ProgressBar(-ImGui::GetTime(), {progress_width, 0}); // Indeterminate progress bar
ImGui::SameLine();
if (ImGui::Button((ICON_FA_STOP "##" + model.name).c_str()))
handle->cancel();
imgui_ctx->vibrate_on_hover();
break;
}
case libcurl::state::error:
if (handle->get_curl_code() == CURLE_HTTP_RETURNED_ERROR)
{
spdlog::error("HTTP error {} when downloading {}", handle->get_response_code(), handle->get_url());
load_environment_status = fmt::format(
_F("HTTP error {} when downloading {}"),
handle->get_response_code(),
handle->get_url());
}
else
{
spdlog::error("Curl error when downloading {}: {}", handle->get_url(), curl_easy_strerror(handle->get_curl_code()));
load_environment_status = fmt::format(
_F("Curl error when downloading {}\n{}: {}"),
handle->get_url(),
magic_enum::enum_name(handle->get_curl_code()),
curl_easy_strerror(handle->get_curl_code()));
}
handle->reset();
break;
case libcurl::state::cancelled:
handle->reset();
break;
case libcurl::state::cancelling:
case libcurl::state::reset:
case libcurl::state::done:
break;
}
}
ImGui::SetCursorScreenPos(end_cursor);
ImGui::Dummy({});
return action;
}
@@ -502,20 +640,46 @@ void scenes::lobby::environment_list(std::vector<environment_model> & models, bo
ImGui::EndDisabled();
}
if (environment_to_be_deleted)
const auto & popup_layer = imgui_ctx->layers()[1];
const glm::vec2 popup_layer_center = popup_layer.vp_origin + popup_layer.vp_size / 2;
ImGui::SetNextWindowPos({popup_layer_center.x, popup_layer_center.y}, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::window_padding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::window_rounding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, constants::style::window_border_size);
if (ImGui::BeginPopupModal("confirm delete model", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize))
{
const std::string msg = fmt::format(_cF("confirmation message", "Permanently delete {}?"), environment_to_be_deleted->name);
switch (wivrn::ui::confirm_modal("confirm delete model", _C("confirmation messagebox title", "Delete environment"), msg, _("Delete"), _("Cancel"), true))
ImGui::Text("%s", fmt::format(_F("Really delete {}?"), environment_to_be_deleted->name).c_str());
const auto & style = ImGui::GetStyle();
auto cancel_text = _("Cancel");
auto delete_text = _("Delete");
auto cancel_size = ImGui::CalcTextSize(cancel_text.c_str()) + style.FramePadding * 2.0f;
auto delete_size = ImGui::CalcTextSize(delete_text.c_str()) + style.FramePadding * 2.0f;
ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - cancel_size.x - style.ItemSpacing.x - delete_size.x);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f));
if (ImGui::Button(delete_text.c_str()))
{
case 1:
delete_environment(*environment_to_be_deleted);
environment_to_be_deleted = nullptr;
break;
case -1:
environment_to_be_deleted = nullptr;
break;
delete_environment(*environment_to_be_deleted);
environment_to_be_deleted = nullptr;
ImGui::CloseCurrentPopup();
}
imgui_ctx->vibrate_on_hover();
ImGui::PopStyleColor(3);
ImGui::SameLine();
if (ImGui::Button(cancel_text.c_str()))
{
environment_to_be_deleted = nullptr;
ImGui::CloseCurrentPopup();
}
imgui_ctx->vibrate_on_hover();
ImGui::EndPopup();
}
ImGui::PopStyleVar(3); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_WindowRounding, ImGuiStyleVar_WindowBorderSize
}
void scenes::lobby::popup_load_environment(XrTime predicted_display_time)
@@ -530,10 +694,12 @@ void scenes::lobby::popup_load_environment(XrTime predicted_display_time)
ImGui::OpenPopup("loading environment model");
}
ImGui::SetNextWindowPos(imgui_ctx->layers()[1].vp_center(), ImGuiCond_Always, {0.5f, 0.5f});
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, wivrn::ui::metrics::window_padding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, wivrn::ui::metrics::window_rounding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, wivrn::ui::metrics::window_border_size);
const auto & popup_layer = imgui_ctx->layers()[1];
const glm::vec2 popup_layer_center = popup_layer.vp_origin + popup_layer.vp_size / 2;
ImGui::SetNextWindowPos({popup_layer_center.x, popup_layer_center.y}, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::window_padding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::window_rounding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, constants::style::window_border_size);
if (ImGui::BeginPopupModal("loading environment model", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize))
{
if (future_environment.valid())
@@ -644,56 +810,40 @@ void scenes::lobby::gui_customize(XrTime predicted_display_time)
{
auto & config = application::get_config();
namespace ui = wivrn::ui;
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {20, 20});
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {10, 10});
ui::page_header(_cS("page header title", "Environment"), _cS("page header subtitle", "Choose the environment your panels float in."));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ui::metrics::card_item_spacing);
ui::begin_list_card("##environments");
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {0, 0});
ImGui::BeginChild("environment list", ImGui::GetWindowSize() - ImGui::GetCursorPos() - ImVec2(0, ImGui::GetFontSize() + 80));
environment_list(local_environments, false);
ui::end_card();
ScrollWhenDragging();
ImGui::EndChild();
ImGui::PopStyleVar();
// Get more environments
bool open_download_popup = false;
ui::begin_list_card("##get_more");
if (ImGui::Button(_S("Download more environments")))
{
const float bh = ImGui::GetFrameHeight() * ui::metrics::control_height;
const std::string browse = ui::icon_label(ICON_FA_UP_RIGHT_FROM_SQUARE, _C("button label to browse environments to download", "Browse"));
const float bw1 = ui::button_width(browse);
const std::string open = ui::icon_label(ICON_FA_FOLDER_OPEN, _C("button label to open an environment from a local gltf file", "Open"));
const float bw2 = ui::button_width(open);
const float bw = ImMax(bw1, bw2);
const auto row1 = ui::begin_list_row("##getmore", ICON_FA_IMAGES, 0, _S("Get more environments"), _S("Download community-made spaces."), false, bw1 + ui::metrics::list_row_pad, 0, false, false);
ImGui::SetCursorScreenPos(row1.trailing(row1.max.x, {bw, bh}));
if (ui::button(browse + "##browse", ui::button_style::secondary, {bw, 0}))
{
download_environment_list();
open_download_popup = true;
}
ui::end_list_row();
const auto row2 = ui::begin_list_row("##localgltf", ICON_FA_CUBE, 0, _S("Open local glTF model"), _S("Open a local glTF file saved on your headset."), false, bw2 + ui::metrics::list_row_pad, 0, false, false);
ImGui::SetCursorScreenPos(row2.trailing(row2.max.x, {bw, bh}));
if (ui::button(open + "##open", ui::button_style::secondary, {bw, 0}))
lobby_file_picker_future = lobby_file_picker.open();
ui::end_list_row();
}
ui::end_card();
// deferred past end_card so OpenPopup hashes at the same id-stack level as BeginPopupModal
if (open_download_popup)
download_environment_list();
ImGui::OpenPopup("download environment model");
}
imgui_ctx->vibrate_on_hover();
if (ui::begin_modal("download environment model", _cS("popup window title", "Browse environments"), 1200))
ImGui::SameLine();
if (ImGui::Button(_S("Open local glTF model")))
lobby_file_picker_future = lobby_file_picker.open();
imgui_ctx->vibrate_on_hover();
const auto & popup_layer = imgui_ctx->layers()[1];
const glm::vec2 popup_layer_center = popup_layer.vp_origin + popup_layer.vp_size / 2;
ImGui::SetNextWindowPos({popup_layer_center.x, popup_layer_center.y}, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::SetNextWindowSize({1200, 900});
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::window_rounding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, constants::style::window_border_size);
if (ImGui::BeginPopupModal("download environment model", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize))
{
const float side = ImGui::GetFrameHeight() * ui::metrics::control_height;
const float list_h = 760;
auto close = _("Close");
auto close_size = ImGui::CalcTextSize(close.c_str());
ImGui::BeginChild("Main", {0, list_h});
ImGui::BeginChild("Main", ImGui::GetWindowSize() - ImGui::GetCursorPos() - ImVec2(0, close_size.y + 80) /*, ImGuiChildFlags_AlwaysUseWindowPadding*/);
auto index_transfer = parse_environment_list();
switch (index_transfer ? index_transfer->get_state() : libcurl::state::reset)
@@ -705,7 +855,7 @@ void scenes::lobby::gui_customize(XrTime predicted_display_time)
ImSpinner::SpinnerAng("index download spinner",
200, // Radius
40, // Thickness
ImColor{ui::current().text}, // Colour
ImColor{1.f, 1.f, 1.f, 1.f}, // Colour
ImColor{1.f, 1.f, 1.f, 0.f}, // Background
6, // Velocity
0.75f * 2 * M_PI // Angle
@@ -728,30 +878,79 @@ void scenes::lobby::gui_customize(XrTime predicted_display_time)
CenterTextHV(downloadable_environment_list_status);
ImGui::Dummy({0, constants::gui::font_size_large});
ImGui::SetCursorPosX((ImGui::GetWindowSize().x - side) / 2);
if (ui::icon_button(ICON_FA_ROTATE, {side, side}, false, _C("button label to re-deownload the environment list", "Refresh")))
ImGui::PushFont(nullptr, constants::gui::font_size_large);
ImGui::PushStyleColor(ImGuiCol_Button, 0);
ImGui::SetCursorPosX((ImGui::GetWindowSize().x - ImGui::CalcTextSize(ICON_FA_ROTATE).x) / 2 - ImGui::GetStyle().FramePadding.x);
if (ImGui::Button(ICON_FA_ROTATE))
download_environment_list();
imgui_ctx->vibrate_on_hover();
ImGui::PopStyleColor(); // ImGuiCol_Button
ImGui::PopFont();
}
}
ScrollWhenDragging();
ImGui::EndChild();
ImGui::Dummy({0, ImGui::GetStyle().ItemSpacing.y});
const std::string close = _S("Close");
const float cw = ui::button_width(close);
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - cw);
if (ui::button(close, ui::button_style::secondary, {cw, 0}))
ImGui::SetCursorPos(ImGui::GetWindowSize() - close_size - ImVec2{50, 50});
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f));
if (ImGui::Button(_S("Close")))
ImGui::CloseCurrentPopup();
imgui_ctx->vibrate_on_hover();
ImGui::PopStyleColor(3); // ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive
popup_load_environment(predicted_display_time);
ui::end_modal();
ImGui::EndPopup();
}
else
{
popup_load_environment(predicted_display_time);
}
ImGui::PopStyleVar(2); // ImGuiStyleVar_WindowRounding, ImGuiStyleVar_WindowBorderSize
ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing
// if (ImGui::RadioButton(_S("Custom environment"), not config.passthrough_enabled and config.environment_model_uri != ""))
// lobby_file_picker_future = lobby_file_picker.open();
// imgui_ctx->vibrate_on_hover();
//
// try
// {
// lobby_file_picker.display();
//
// if (lobby_file_picker_future.valid() and lobby_file_picker_future.wait_for(0s) == std::future_status::ready)
// {
// auto environment = lobby_file_picker_future.get();
//
// // TODO load asynchronously
// // TODO allow caching
// spdlog::info("Loading new environment from {}", environment.path.native());
// auto t0 = std::chrono::steady_clock::now();
// auto new_lobby = load_gltf(environment.file);
// auto dt = std::chrono::steady_clock::now() - t0;
// spdlog::info("Loaded successfully in {}", dt);
//
// remove(lobby_entity);
// lobby_entity = add_gltf(new_lobby, layer_lobby).first;
//
// config.passthrough_enabled = false;
// setup_passthrough();
// }
// }
// catch (std::exception & e)
// {
// spdlog::warn("Cannot load environment: {}", e.what());
// }
// auto & lobby_node = world.get<components::node>(lobby_entity);
// float scale = lobby_node.scale.x;
// if (ImGui::SliderFloat("Environment scale", &scale, 0.1, 10, "%.3f", ImGuiSliderFlags_Logarithmic))
// lobby_node.scale = glm::vec3{scale, scale, scale};
// imgui_ctx->vibrate_on_hover();
//
// ImGui::SliderFloat("Environment elevation", &lobby_node.position.y, -3, 3, "%.3f");
// imgui_ctx->vibrate_on_hover();
ImGui::PopStyleVar(2); // ImGuiStyleVar_ItemSpacing, ImGuiStyleVar_FramePadding
}
-84
View File
@@ -1,84 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// lobby-side settings pages, shared with the in-stream window (see gui_settings.cpp)
#include "lobby.h"
#include "application.h"
#include "gui_settings.h"
namespace
{
wivrn::gui::settings_context lobby_settings_context(xr::instance & instance, xr::session & session, xr::system & system, imgui_context & imgui_ctx, const XrViewConfigurationView & stream_view, std::optional<bool> server_hid_forwarding)
{
return {
.config = application::get_config(),
.default_config = application::get_default_config(),
.instance = instance,
.session = session,
.system = system,
.imgui_ctx = imgui_ctx,
.recommended_width = stream_view.recommendedImageRectWidth,
.recommended_height = stream_view.recommendedImageRectHeight,
.in_game = false,
.server_hid_forwarding = server_hid_forwarding,
};
}
} // namespace
void scenes::lobby::gui_video()
{
wivrn::gui::settings_video(lobby_settings_context(instance, session, system, *imgui_ctx, stream_view, server_hid_forwarding));
}
void scenes::lobby::gui_streaming()
{
wivrn::gui::settings_streaming(lobby_settings_context(instance, session, system, *imgui_ctx, stream_view, server_hid_forwarding));
}
void scenes::lobby::gui_post_processing()
{
wivrn::gui::settings_post_processing(lobby_settings_context(instance, session, system, *imgui_ctx, stream_view, server_hid_forwarding));
}
void scenes::lobby::gui_audio()
{
wivrn::gui::settings_audio(lobby_settings_context(instance, session, system, *imgui_ctx, stream_view, server_hid_forwarding));
}
void scenes::lobby::gui_devices()
{
wivrn::gui::settings_devices(lobby_settings_context(instance, session, system, *imgui_ctx, stream_view, server_hid_forwarding));
}
void scenes::lobby::gui_tracking()
{
wivrn::gui::settings_tracking(lobby_settings_context(instance, session, system, *imgui_ctx, stream_view, server_hid_forwarding));
}
void scenes::lobby::gui_system()
{
wivrn::gui::settings_system(lobby_settings_context(instance, session, system, *imgui_ctx, stream_view, server_hid_forwarding));
}
void scenes::lobby::gui_theme()
{
wivrn::gui::settings_theme(lobby_settings_context(instance, session, system, *imgui_ctx, stream_view, server_hid_forwarding));
}
-57
View File
@@ -1,57 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2026 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "lobby.h"
#include "application.h"
#include "configuration.h"
#include "render/ui_theme.h"
#include <string>
namespace ui = wivrn::ui;
void scenes::lobby::apply_theme_settings()
{
auto & config = application::get_config();
// preset by name, surfaces only, accent applied separately below
for (const auto & p: ui::presets())
{
if (p.name == config.theme_preset)
{
ui::set_theme(p);
break;
}
}
for (const auto & swatch: ui::accent_swatches())
{
if (swatch.name == config.theme_accent)
{
ui::set_accent(swatch);
break;
}
}
ui::theme & theme = ui::current();
theme.rounding = config.theme_rounding;
theme.card_rounding = config.theme_card_rounding;
theme.font_scale = config.theme_font_scale;
ui::background_alpha() = config.theme_background_alpha;
}
+9 -15
View File
@@ -17,7 +17,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "lobby_keyboard.h"
#define IMGUI_DEFINE_MATH_OPERATORS
#include <array>
#include <cassert>
@@ -29,10 +29,10 @@
#include <uni_algo/ranges_grapheme.h>
#include <utility>
#include "IconsFontAwesome7.h"
#include "IconsFontAwesome6.h"
#include "imgui.h"
#include "imgui_internal.h"
#include "render/ui_theme.h"
#include "lobby_keyboard.h"
static const ImGuiKey key_layout = (ImGuiKey)(ImGuiKey_NamedKey_END + 1);
static const ImGuiKey key_symbols_letter = (ImGuiKey)(ImGuiKey_NamedKey_END + 2);
@@ -391,7 +391,7 @@ virtual_keyboard::key_status virtual_keyboard::draw_single_key(const key & k, in
const ImU32 col = ImGui::GetColorU32(active ? ImGuiCol_ButtonActive : status.hovered ? ImGuiCol_ButtonHovered
: ImGuiCol_Button);
ImGui::RenderNavCursor(bb, id);
ImGui::RenderNavHighlight(bb, id);
ImGui::RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
ImGui::RenderTextClippedEx(
@@ -465,7 +465,6 @@ void virtual_keyboard::press_single_key(const key & k)
void virtual_keyboard::display(imgui_context & ctx)
{
ImGuiStyle & style = ImGui::GetStyle();
const wivrn::ui::theme & th = wivrn::ui::current();
ImGuiInputTextState * input_state = ImGui::GetInputTextState(ImGui::GetCurrentContext()->ActiveId);
bool want_digits = input_state and (input_state->Flags & ImGuiInputTextFlags_CharsDecimal) != 0;
@@ -474,20 +473,15 @@ void virtual_keyboard::display(imgui_context & ctx)
: *layouts[current_layout].second;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8});
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, th.card_rounding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 16);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {8, 8});
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, th.rounding);
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 8);
ImGui::PushStyleColor(ImGuiCol_WindowBg, IM_COL32(8, 8, 8, 224));
if (want_digits)
ImGui::SetNextWindowSize({350, 400});
else
ImGui::SetNextWindowSize({1400, 400});
// window background follows the theme, with a user-controlled opacity
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4{th.background.x, th.background.y, th.background.z, wivrn::ui::background_alpha()});
ImGui::PushStyleColor(ImGuiCol_Button, th.control);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, th.control_hovered);
ImGui::PushStyleColor(ImGuiCol_ButtonActive, th.control_active);
ImGui::PushStyleColor(ImGuiCol_Text, th.text);
ImGui::Begin("VirtualKeyboard", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoFocusOnClick);
ImVec2 size = ImGui::GetWindowSize();
@@ -560,8 +554,8 @@ void virtual_keyboard::display(imgui_context & ctx)
}
ImGui::End();
ImGui::PopStyleColor(5); // ImGuiCol_WindowBg, ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive, ImGuiCol_Text
ImGui::PopStyleVar(4); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_WindowRounding, ImGuiStyleVar_ItemSpacing, ImGuiStyleVar_FrameRounding
ImGui::PopStyleColor(); // ImGuiCol_WindowBg
ImGui::PopStyleVar(4); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_WindowRounding, ImGuiStyleVar_ItemSpacing, ImGuiStyleVar_FrameRounding
}
const std::string_view virtual_keyboard::get_layout() const
+195 -246
View File
@@ -21,7 +21,6 @@
#include "xr/face_tracker.h"
#include "xr/fb_face_tracker2.h"
#include "xr/space.h"
#include "xr/system.h"
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/quaternion.hpp>
#include <magic_enum.hpp>
@@ -34,6 +33,7 @@
#include "audio/audio.h"
#include "boost/pfr/core.hpp"
#include "decoder/shard_accumulator.h"
#include "hardware.h"
#include "inplace_vector.hpp"
#include "spdlog/spdlog.h"
#include "utils/named_thread.h"
@@ -139,27 +139,6 @@ static const std::unordered_map<std::string, device_id> device_ids = {
{"/user/hand/right/input/aim_activate_ext/ready_ext",device_id::RIGHT_AIM_ACTIVATE_READY},
{"/user/hand/right/input/grasp_ext/value", device_id::RIGHT_GRASP_VALUE},
{"/user/hand/right/input/grasp_ext/ready_ext", device_id::RIGHT_GRASP_READY},
{"/user/gamepad/input/menu/click", device_id::GAMEPAD_MENU_CLICK},
{"/user/gamepad/input/view/click", device_id::GAMEPAD_VIEW_CLICK},
{"/user/gamepad/input/a/click", device_id::GAMEPAD_A_CLICK},
{"/user/gamepad/input/b/click", device_id::GAMEPAD_B_CLICK},
{"/user/gamepad/input/x/click", device_id::GAMEPAD_X_CLICK},
{"/user/gamepad/input/y/click", device_id::GAMEPAD_Y_CLICK},
{"/user/gamepad/input/dpad_down/click", device_id::GAMEPAD_DPAD_DOWN_CLICK},
{"/user/gamepad/input/dpad_right/click", device_id::GAMEPAD_DPAD_RIGHT_CLICK},
{"/user/gamepad/input/dpad_up/click", device_id::GAMEPAD_DPAD_UP_CLICK},
{"/user/gamepad/input/dpad_left/click", device_id::GAMEPAD_DPAD_LEFT_CLICK},
{"/user/gamepad/input/shoulder_left/click", device_id::GAMEPAD_SHOULDER_LEFT_CLICK},
{"/user/gamepad/input/shoulder_right/click", device_id::GAMEPAD_SHOULDER_RIGHT_CLICK},
{"/user/gamepad/input/thumbstick_left/click", device_id::GAMEPAD_THUMBSTICK_LEFT_CLICK},
{"/user/gamepad/input/thumbstick_right/click", device_id::GAMEPAD_THUMBSTICK_RIGHT_CLICK},
{"/user/gamepad/input/trigger_left/value", device_id::GAMEPAD_TRIGGER_LEFT_VALUE},
{"/user/gamepad/input/trigger_right/value", device_id::GAMEPAD_TRIGGER_RIGHT_VALUE},
{"/user/gamepad/input/thumbstick_left/x", device_id::GAMEPAD_THUMBSTICK_LEFT_X},
{"/user/gamepad/input/thumbstick_left/y", device_id::GAMEPAD_THUMBSTICK_LEFT_Y},
{"/user/gamepad/input/thumbstick_right/x", device_id::GAMEPAD_THUMBSTICK_RIGHT_X},
{"/user/gamepad/input/thumbstick_right/y", device_id::GAMEPAD_THUMBSTICK_RIGHT_Y},
};
// clang-format on
@@ -238,7 +217,7 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
{
auto view = self->system.view_configuration_views(self->viewconfig)[0];
view = application::get_hmd_traits().override_view(view);
view = override_view(view, guess_model());
info.render_eye_width = view.recommendedImageRectWidth * config.resolution_scale;
info.render_eye_height = view.recommendedImageRectHeight * config.resolution_scale;
@@ -256,7 +235,6 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
info.settings.preferred_refresh_rate = config.preferred_refresh_rate;
info.settings.minimum_refresh_rate = config.minimum_refresh_rate.value_or(0);
}
info.settings.fps_divider = config.fps_divider;
if (info.available_refresh_rates.empty())
{
@@ -266,8 +244,6 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
}
info.settings.bitrate_bps = config.bitrate_bps;
info.settings.mirror_gamepad = config.forward_gamepad;
info.settings.enabled_body_parts = config.body_part_mask;
info.hand_tracking = config.check_feature(feature::hand_tracking);
info.eye_gaze = config.check_feature(feature::eye_gaze);
@@ -297,26 +273,22 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
}
}
info.num_generic_trackers = 0;
if (config.check_feature(feature::body_tracking))
{
switch (self->system.body_tracker_supported())
{
case xr::body_tracker_type::none:
info.body_tracking = from_headset::body_type::none;
break;
case xr::body_tracker_type::fb:
info.body_tracking = from_headset::body_type::fb;
break;
case xr::body_tracker_type::meta:
info.body_tracking = from_headset::body_type::meta;
break;
case xr::body_tracker_type::pico:
info.body_tracking = from_headset::body_type::bd;
info.num_generic_trackers = xr::fb_body_tracker::get_whitelisted_joints(config.fb_lower_body, config.fb_hip).size();
break;
case xr::body_tracker_type::htc:
info.body_tracking = from_headset::body_type::htc;
info.num_generic_trackers = application::get_generic_trackers().size();
break;
case xr::body_tracker_type::pico:
info.num_generic_trackers = xr::pico_body_tracker::joint_whitelist.size();
break;
}
}
@@ -408,12 +380,7 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
std::tuple(device_id::LEFT_THUMB_HAPTIC, "/user/hand/left", "/output/haptic_thumb"),
std::tuple(device_id::RIGHT_THUMB_HAPTIC, "/user/hand/right", "/output/haptic_thumb"),
std::tuple(device_id::LEFT_THUMB_HAPTIC, "/user/hand/left", "/output/haptic_thumb_fb"),
std::tuple(device_id::RIGHT_THUMB_HAPTIC, "/user/hand/right", "/output/haptic_thumb_fb"),
std::tuple(device_id::GAMEPAD_HAPTIC_LEFT, "/user/gamepad", "/output/haptic_left"),
std::tuple(device_id::GAMEPAD_HAPTIC_RIGHT, "/user/gamepad", "/output/haptic_right"),
std::tuple(device_id::GAMEPAD_HAPTIC_LEFT_TRIGGER, "/user/gamepad", "/output/haptic_left_trigger"),
std::tuple(device_id::GAMEPAD_HAPTIC_RIGHT_TRIGGER, "/user/gamepad", "/output/haptic_right_trigger")})
std::tuple(device_id::RIGHT_THUMB_HAPTIC, "/user/hand/right", "/output/haptic_thumb_fb")})
{
if (auto action = application::get_action(std::string(path) + output); action.first)
{
@@ -453,7 +420,7 @@ void scenes::stream::on_focused()
{
gui_status_last_change = instance.now();
const auto & profile = application::get_hmd_traits().controller_profile;
std::string profile = controller_name();
input.emplace(
*this,
"assets://controllers/" + profile + "/profile.json",
@@ -466,7 +433,7 @@ void scenes::stream::on_focused()
for (auto i: {xr::spaces::aim_left, xr::spaces::aim_right, xr::spaces::grip_left, xr::spaces::grip_right})
{
auto [p, q] = input->offset[i] = application::get_hmd_traits().controller_offset(i);
auto [p, q] = input->offset[i] = controller_offset(controller_name(), i);
auto rot = glm::degrees(glm::eulerAngles(q));
spdlog::info("Initializing offset of space {} to ({}, {}, {}) mm, ({}, {}, {})°",
@@ -503,12 +470,11 @@ void scenes::stream::on_focused()
session,
device,
swapchain_format,
3600,
1800,
1200);
std::vector<imgui_context::viewport> vps{
{
// Main window
.space = xr::spaces::world,
// Position and orientation are set at each frame
.size = {1.2, 0.6666},
@@ -522,13 +488,6 @@ void scenes::stream::on_focused()
.vp_size = {1800, 200},
.tooltip_viewport = true,
},
{
// popup window for combos and modals, tracks the main panel each frame at the same pixel density
.space = xr::spaces::world,
.size = {1.2, 0.6666},
.vp_origin = {1800, 0},
.vp_size = {1800, 1000},
},
};
imgui_ctx.emplace(physical_device,
@@ -540,30 +499,13 @@ void scenes::stream::on_focused()
std::move(vps),
image_cache);
// match the lobby's seasonal wordmark logo
if (application::get_config().enable_stream_gui)
{
auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
auto tm = std::localtime(&t);
switch (tm->tm_mon)
{
case 5:
wivrn_logo = imgui_ctx->load_texture("assets://wivrn-pride.ktx2");
break;
case 11:
wivrn_logo = imgui_ctx->load_texture("assets://wivrn-christmas.ktx2");
break;
default:
wivrn_logo = imgui_ctx->load_texture("assets://wivrn.ktx2");
break;
}
plots_toggle_1 = get_action("plots_toggle_1").first;
plots_toggle_2 = get_action("plots_toggle_2").first;
}
plots_toggle_1 = get_action("plots_toggle_1").first;
plots_toggle_2 = get_action("plots_toggle_2").first;
recenter_left = get_action("recenter_left").first;
recenter_right = get_action("recenter_right").first;
gui_distance_left = get_action("gui_distance_left").first;
gui_distance_right = get_action("gui_distance_right").first;
settings_adjust = get_action("settings_adjust").first;
foveation_distance = get_action("foveation_distance").first;
foveation_ok = get_action("foveation_ok").first;
@@ -622,7 +564,7 @@ void scenes::stream::push_blit_handle(shard_accumulator * decoder, std::shared_p
std::swap(handle, decoders[stream].latest_frames[handle->feedback.frame_index % decoders[stream].latest_frames.size()]);
}
if (state_ != state::streaming and not(decoders[0].empty() or decoders[1].empty()))
if (state_ != state::streaming and not(decoders[0].empty() and decoders[1].empty()))
{
set_state(state::streaming);
spdlog::info("Stream scene ready at t={}", instance.now());
@@ -737,29 +679,59 @@ std::shared_ptr<shard_accumulator::blit_handle> scenes::stream::accumulator_imag
return frame;
}
void scenes::stream::update_gui_position(xr::spaces controller, float predicted_display_period)
void scenes::stream::update_gui_position(xr::spaces controller)
{
std::optional<std::pair<glm::vec3, glm::quat>> aim = application::locate_controller(
application::space(controller),
application::space(xr::spaces::world),
predicted_display_time);
std::optional<std::pair<glm::vec3, glm::quat>> aim;
if (not aim)
return;
switch (guess_model())
{
case model::pico_4:
case model::pico_4s:
case model::pico_4_pro:
case model::pico_4_enterprise: {
// Pico fails to find its controllers within view space, so use the head position in
// world space as a reference
aim = application::locate_controller(
application::space(controller),
application::space(xr::spaces::world),
predicted_display_time);
auto head_position = application::locate_controller(application::space(xr::spaces::view),
application::space(xr::spaces::world),
predicted_display_time);
if (not aim || not head_position)
return;
aim->first = glm::conjugate(head_position->second) * (aim->first - head_position->first);
aim->second = glm::conjugate(head_position->second) * aim->second;
break;
}
default:
aim = application::locate_controller(
application::space(controller),
application::space(xr::spaces::view),
predicted_display_time);
if (not aim)
return;
break;
}
auto [offset_position, offset_orientation] = input->offset[controller];
auto world_controller_position = aim->first + glm::mat3_cast(aim->second * offset_orientation) * offset_position;
auto world_controller_orientation = aim->second * offset_orientation;
auto world_controller_direction = -glm::column(glm::mat3_cast(world_controller_orientation), 2);
auto head_controller_position = aim->first + glm::mat3_cast(aim->second * offset_orientation) * offset_position;
auto head_controller_orientation = aim->second * offset_orientation;
auto head_controller_direction = -glm::column(glm::mat3_cast(head_controller_orientation), 2);
if (not recentering_context)
{
// First frame of recentering: get the GUI position relative to the controller
// Compute the intersection of the ray with the GUI
auto gui_controller_direction = glm::conjugate(world_gui_orientation) * world_controller_direction;
auto gui_controller_position = glm::conjugate(world_gui_orientation) * (world_controller_position - world_gui_position);
auto gui_controller_direction = glm::conjugate(head_gui_orientation) * head_controller_direction;
auto gui_controller_position = glm::conjugate(head_gui_orientation) * (head_controller_position - head_gui_position);
float lambda = -gui_controller_position.z / gui_controller_direction.z;
auto gui_intersection = gui_controller_position + lambda * gui_controller_direction;
@@ -774,8 +746,8 @@ void scenes::stream::update_gui_position(xr::spaces controller, float predicted_
}
else
{
glm::vec3 controller_gui_position = glm::conjugate(world_controller_orientation) * (world_gui_position - world_controller_position);
glm::quat controller_gui_orientation = glm::conjugate(world_controller_orientation) * world_gui_orientation;
glm::vec3 controller_gui_position = glm::conjugate(head_controller_orientation) * (head_gui_position - head_controller_position);
glm::quat controller_gui_orientation = glm::conjugate(head_controller_orientation) * head_gui_orientation;
recentering_context.emplace(controller, controller_gui_position, controller_gui_orientation);
}
@@ -783,16 +755,10 @@ void scenes::stream::update_gui_position(xr::spaces controller, float predicted_
else
{
// Subsequent frames of recentering: keep the GUI locked to the controller
auto & [_, controller_gui_position, controller_gui_orientation] = *recentering_context;
auto [_, controller_gui_position, controller_gui_orientation] = *recentering_context;
if (auto gui_distance = application::read_action_float(controller == xr::spaces::aim_left ? gui_distance_left : gui_distance_right))
{
controller_gui_position.z *= std::pow(constants::stream::gui_max_layer_speed, gui_distance->second * predicted_display_period);
controller_gui_position.z = -std::clamp<float>(-controller_gui_position.z, constants::stream::gui_min_layer_distance, constants::stream::gui_max_layer_distance);
}
world_gui_position = world_controller_position + world_controller_orientation * controller_gui_position;
world_gui_orientation = world_controller_orientation * controller_gui_orientation;
head_gui_position = head_controller_position + head_controller_orientation * controller_gui_position;
head_gui_orientation = head_controller_orientation * controller_gui_orientation;
}
}
@@ -802,6 +768,7 @@ bool scenes::stream::is_interactable(stream_tab tab)
{
case stream_tab::stats:
case stream_tab::settings:
case stream_tab::bitrate_settings:
case stream_tab::foveation_settings:
case stream_tab::applications:
case stream_tab::application_launcher:
@@ -832,7 +799,7 @@ void scenes::stream::render(const XrFrameState & frame_state)
last_display_time = frame_state.predictedDisplayTime;
std::shared_lock lock(decoder_mutex);
if (not frame_state.shouldRender or decoders[0].empty() or decoders[1].empty() or state_ == state::shutdown)
if (not frame_state.shouldRender or (decoders[0].empty() and decoders[1].empty()) or state_ == state::shutdown)
{
// TODO: stop/restart video stream
session.begin_frame();
@@ -855,6 +822,8 @@ void scenes::stream::render(const XrFrameState & frame_state)
if (device.waitForFences(*fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout)
throw std::runtime_error("Vulkan fence timeout");
device.resetFences(*fence);
// We don't need those after vkWaitForFences
current_blit_handles.fill(nullptr);
@@ -906,11 +875,7 @@ void scenes::stream::render(const XrFrameState & frame_state)
{
auto & blit_handle = current_blit_handles[i];
if (not blit_handle)
{
if (i == view_count)
use_alpha = false;
continue;
}
blit_handle->feedback.blitted = instance.now();
if (blit_handle->feedback.blitted - blit_handle->feedback.received_from_decoder > 1'000'000'000)
@@ -976,54 +941,118 @@ void scenes::stream::render(const XrFrameState & frame_state)
}
}
// Allow the headset to time warp if we are redisplaying a frame
if ((not application::get_hmd_traits().discard_frame) or
std::ranges::any_of(current_blit_handles, [](const auto & h) { return h and h->feedback.times_displayed < 2; }) or
is_gui_interactable())
XrExtent2Di extents[view_count];
{
XrExtent2Di extents[view_count];
int32_t max_width = 0;
int32_t max_height = 0;
for (size_t i = 0; i < view_count; ++i)
{
int32_t max_width = 0;
int32_t max_height = 0;
for (size_t i = 0; i < view_count; ++i)
extents[i] = stream_defoveator::defoveated_size(foveation[i]);
max_width = std::max(max_width, extents[i].width);
max_height = std::max(max_height, extents[i].height);
}
if (not swapchain)
setup_reprojection_swapchain(max_width, max_height);
else if (swapchain.width() < max_width or swapchain.height() < max_height)
{
// If the defoveated image is larger than the swapchain, try to reallocate one
try
{
extents[i] = stream_defoveator::defoveated_size(foveation[i]);
max_width = std::max(max_width, extents[i].width);
max_height = std::max(max_height, extents[i].height);
}
if (not swapchain)
spdlog::info("Recreating swapchain, from {}x{} to {}x{}",
swapchain.width(),
swapchain.height(),
max_width,
max_height);
setup_reprojection_swapchain(max_width, max_height);
else if (swapchain.width() < max_width or swapchain.height() < max_height)
}
catch (std::exception & e)
{
// If the defoveated image is larger than the swapchain, try to reallocate one
try
spdlog::warn("failed to increase swapchain size");
for (size_t i = 0; i < view_count; ++i)
{
spdlog::info("Recreating swapchain, from {}x{} to {}x{}",
swapchain.width(),
swapchain.height(),
max_width,
max_height);
setup_reprojection_swapchain(max_width, max_height);
}
catch (std::exception & e)
{
spdlog::warn("failed to increase swapchain size");
for (size_t i = 0; i < view_count; ++i)
{
extents[i].width = std::min(extents[i].width, swapchain.width());
extents[i].height = std::min(extents[i].height, swapchain.height());
}
extents[i].width = std::min(extents[i].width, swapchain.width());
extents[i].height = std::min(extents[i].height, swapchain.height());
}
}
}
assert(swapchain);
// defoveate the image, apply scale/bias
int image_index = swapchain.acquire();
swapchain.wait();
}
assert(swapchain);
// defoveate the image
int image_index = swapchain.acquire();
swapchain.wait();
defoveator->defoveate(command_buffer, foveation, images, image_index);
command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1);
command_buffer.end();
vk::SubmitInfo submit_info;
submit_info.setCommandBuffers(*command_buffer);
inplace_vector<vk::Semaphore, decoder_count> semaphores;
inplace_vector<uint64_t, decoder_count> semaphore_vals;
inplace_vector<vk::PipelineStageFlags, decoder_count> wait_stages;
for (auto b: current_blit_handles)
{
if (b and b->semaphore)
{
assert(b->semaphore_val);
semaphores.push_back(b->semaphore);
semaphore_vals.push_back(*b->semaphore_val);
wait_stages.push_back(vk::PipelineStageFlagBits::eFragmentShader);
}
}
submit_info.setWaitDstStageMask(wait_stages);
submit_info.setWaitSemaphores(semaphores);
vk::TimelineSemaphoreSubmitInfo sem_info{
.waitSemaphoreValueCount = uint32_t(semaphore_vals.size()),
.pWaitSemaphoreValues = semaphore_vals.data(),
};
submit_info.pNext = &sem_info;
queue.lock()->submit(submit_info, *fence);
#if WIVRN_FEATURE_RENDERDOC
renderdoc_end(*vk_instance);
#endif
swapchain.release();
if (use_alpha)
session.enable_passthrough(system);
else
session.disable_passthrough();
render_start(use_alpha, frame_state.predictedDisplayTime);
// Add the layer with the streamed content
std::array<XrCompositionLayerProjectionView, view_count> layer_view;
for (uint32_t view = 0; view < view_count; view++)
{
layer_view[view] =
{
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW,
.pose = pose[view],
.fov = fov[view],
.subImage = {
.swapchain = swapchain,
.imageRect = {
.offset = {0, 0},
.extent = extents[view],
},
.imageArrayIndex = view,
},
};
}
add_projection_layer(
XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT,
application::space(xr::spaces::world),
layer_view);
if (composition_layer_color_scale_bias_supported)
{
switch (gui_status)
{
case stream_tab::hidden:
case stream_tab::bitrate_settings:
case stream_tab::foveation_settings:
case stream_tab::compact:
case stream_tab::overlay_only:
@@ -1040,101 +1069,30 @@ void scenes::stream::render(const XrFrameState & frame_state)
dimming = std::clamp<float>(dimming, 0, 1);
float x = dimming * dimming * (3 - 2 * dimming); // Easing function
const float scale = std::lerp(1, constants::stream::dimming_scale, x);
const float bias = std::lerp(0, constants::stream::dimming_bias, x);
float scale = std::lerp(1, constants::stream::dimming_scale, x);
float bias = std::lerp(0, constants::stream::dimming_bias, x);
defoveator->defoveate(command_buffer,
foveation,
images,
{scale, scale, scale, 1.},
{bias, bias, bias, 0.},
image_index);
set_color_scale_bias({scale, scale, scale, 1}, {bias, bias, bias, 0});
}
command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1);
if (const configuration::openxr_post_processing_settings openxr_post_processing = application::get_config().openxr_post_processing;
(openxr_post_processing.sharpening | openxr_post_processing.super_sampling) > 0)
set_layer_settings(openxr_post_processing.sharpening | openxr_post_processing.super_sampling);
command_buffer.end();
vk::SubmitInfo submit_info;
submit_info.setCommandBuffers(*command_buffer);
accumulate_metrics(frame_state.predictedDisplayTime, current_blit_handles, timestamps);
inplace_vector<vk::Semaphore, decoder_count> semaphores;
inplace_vector<uint64_t, decoder_count> semaphore_vals;
inplace_vector<vk::PipelineStageFlags, decoder_count> wait_stages;
for (auto b: current_blit_handles)
{
if (b and b->semaphore)
{
assert(b->semaphore_val);
semaphores.push_back(b->semaphore);
semaphore_vals.push_back(*b->semaphore_val);
wait_stages.push_back(vk::PipelineStageFlagBits::eFragmentShader);
}
}
submit_info.setWaitDstStageMask(wait_stages);
submit_info.setWaitSemaphores(semaphores);
vk::TimelineSemaphoreSubmitInfo sem_info{
.waitSemaphoreValueCount = uint32_t(semaphore_vals.size()),
.pWaitSemaphoreValues = semaphore_vals.data(),
};
submit_info.pNext = &sem_info;
draw_gui(frame_state.predictedDisplayTime, frame_state.predictedDisplayPeriod);
device.resetFences(*fence);
queue.lock()->submit(submit_info, *fence);
#if WIVRN_FEATURE_RENDERDOC
renderdoc_end(*vk_instance);
#endif
swapchain.release();
if (use_alpha)
session.enable_passthrough(system);
try
{
render_end();
}
catch (std::system_error & e)
{
if (e.code().category() == xr::error_category() and e.code().value() == XR_ERROR_POSE_INVALID)
spdlog::info("Invalid pose submitted");
else
session.disable_passthrough();
render_start(use_alpha, frame_state.predictedDisplayTime);
// Add the layer with the streamed content
std::array<XrCompositionLayerProjectionView, view_count> layer_view;
for (uint32_t view = 0; view < view_count; view++)
{
layer_view[view] =
{
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW,
.pose = pose[view],
.fov = fov[view],
.subImage = {
.swapchain = swapchain,
.imageRect = {
.offset = {0, 0},
.extent = extents[view],
},
.imageArrayIndex = view,
},
};
}
add_projection_layer(
use_alpha ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT : 0,
application::space(xr::spaces::world),
layer_view);
if (const configuration::openxr_post_processing_settings openxr_post_processing = application::get_config().openxr_post_processing;
(openxr_post_processing.sharpening | openxr_post_processing.super_sampling) > 0)
set_layer_settings(openxr_post_processing.sharpening | openxr_post_processing.super_sampling);
accumulate_metrics(frame_state.predictedDisplayTime, current_blit_handles, timestamps);
draw_gui(frame_state.predictedDisplayTime, frame_state.predictedDisplayPeriod);
try
{
render_end();
}
catch (std::system_error & e)
{
if (e.code().category() == xr::error_category() and e.code().value() == XR_ERROR_POSE_INVALID)
spdlog::info("Invalid pose submitted");
else
throw;
}
throw;
}
// Network operations may be blocking, do them once everything was submitted
@@ -1169,7 +1127,7 @@ void scenes::stream::render(const XrFrameState & frame_state)
read_actions();
if (application::get_config().enable_stream_gui)
if (plots_toggle_1 and plots_toggle_2)
{
XrActionStateGetInfo get_info{
.type = XR_TYPE_ACTION_STATE_GET_INFO,
@@ -1184,7 +1142,7 @@ void scenes::stream::render(const XrFrameState & frame_state)
if (state_1.currentState and state_2.currentState and (state_1.changedSinceLastSync or state_2.changedSinceLastSync))
{
// Arbitrary transitions can happen from network commands
// Arbitraty transitions can happen from network commands
// Ensure we can't have a set of 2 non interactable states
if (is_gui_interactable())
next_gui_status = stream_tab::hidden;
@@ -1205,8 +1163,7 @@ void scenes::stream::exit()
void scenes::stream::setup(const to_headset::video_stream_description & description)
{
spdlog::info("setup, refresh rate {}", description.refresh_rate);
session.set_refresh_rate(description.refresh_rate);
session.set_refresh_rate(description.fps);
std::unique_lock lock(decoder_mutex);
if (video_stream_description == description)
@@ -1230,8 +1187,7 @@ void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint
assert(swapchain_width);
assert(swapchain_height);
device.waitIdle();
spdlog::info("swapchain setup, refresh rate {}", video_stream_description->refresh_rate);
session.set_refresh_rate(video_stream_description->refresh_rate);
session.set_refresh_rate(video_stream_description->fps);
auto views = system.view_configuration_views(viewconfig);
@@ -1275,8 +1231,6 @@ scene::meta & scenes::stream::get_meta_scene()
{"recenter_left", XR_ACTION_TYPE_BOOLEAN_INPUT},
{"recenter_right", XR_ACTION_TYPE_BOOLEAN_INPUT},
{"gui_distance_left", XR_ACTION_TYPE_FLOAT_INPUT},
{"gui_distance_right", XR_ACTION_TYPE_FLOAT_INPUT},
{"settings_adjust", XR_ACTION_TYPE_FLOAT_INPUT},
{"foveation_distance", XR_ACTION_TYPE_FLOAT_INPUT},
@@ -1294,7 +1248,6 @@ scene::meta & scenes::stream::get_meta_scene()
"/interaction_profiles/bytedance/pico_neo3_controller",
"/interaction_profiles/bytedance/pico4_controller",
"/interaction_profiles/bytedance/pico4s_controller",
"/interaction_profiles/yvr/touch_controller_yvr",
"/interaction_profiles/htc/vive_focus3_controller",
},
{
@@ -1311,8 +1264,6 @@ scene::meta & scenes::stream::get_meta_scene()
{"recenter_left", "/user/hand/left/input/squeeze/value"},
{"recenter_right", "/user/hand/right/input/squeeze/value"},
{"gui_distance_left", "/user/hand/left/input/thumbstick/y"},
{"gui_distance_right", "/user/hand/right/input/thumbstick/y"},
{"settings_adjust", "/user/hand/right/input/thumbstick/y"},
{"foveation_distance", "/user/hand/left/input/thumbstick/y"},
{"foveation_ok", "/user/hand/right/input/a/click"},
@@ -1380,7 +1331,6 @@ void scenes::stream::on_xr_event(const xr::event & event)
case XR_TYPE_EVENT_DATA_USER_PRESENCE_CHANGED_EXT:
network_session->send_control(from_headset::user_presence_changed{
.present = (bool)event.user_presence_changed.isUserPresent,
.change_time = instance.now(),
});
break;
case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED:
@@ -1391,10 +1341,9 @@ void scenes::stream::on_xr_event(const xr::event & event)
}
}
bool scenes::stream::forward_hid_input(from_headset::hid::input_t packet, bool device_enabled)
bool scenes::stream::forward_hid_input(from_headset::hid::input_t packet)
{
// hid_forwarding is whether the server permits it; device_enabled is the headset toggle.
if (not hid_forwarding or not device_enabled)
if (not hid_forwarding)
return false;
network_session->send_control(from_headset::hid::input{packet});
return true;
@@ -1402,25 +1351,25 @@ bool scenes::stream::forward_hid_input(from_headset::hid::input_t packet, bool d
bool scenes::stream::on_input_key_down(uint8_t key_code)
{
return forward_hid_input(from_headset::hid::key_down{key_code}, application::get_config().forward_keyboard);
return forward_hid_input(from_headset::hid::key_down{key_code});
}
bool scenes::stream::on_input_key_up(uint8_t key_code)
{
return forward_hid_input(from_headset::hid::key_up{key_code}, application::get_config().forward_keyboard);
return forward_hid_input(from_headset::hid::key_up{key_code});
}
bool scenes::stream::on_input_mouse_move(float x, float y)
{
return forward_hid_input(from_headset::hid::mouse_move{x, y}, application::get_config().forward_mouse);
return forward_hid_input(from_headset::hid::mouse_move{x, y});
}
bool scenes::stream::on_input_button_down(uint8_t button)
{
return forward_hid_input(from_headset::hid::button_down{button}, application::get_config().forward_mouse);
return forward_hid_input(from_headset::hid::button_down{button});
}
bool scenes::stream::on_input_button_up(uint8_t button)
{
return forward_hid_input(from_headset::hid::button_up{button}, application::get_config().forward_mouse);
return forward_hid_input(from_headset::hid::button_up{button});
}
bool scenes::stream::on_input_scroll(float h, float v)
{
return forward_hid_input(from_headset::hid::mouse_scroll{h, v}, application::get_config().forward_mouse);
return forward_hid_input(from_headset::hid::mouse_scroll{h, v});
}
+4 -33
View File
@@ -32,7 +32,6 @@
#include "wivrn_packets.h"
#include "xr/space.h"
#include <mutex>
#include <optional>
#include <queue>
#include <shared_mutex>
#include <thread>
@@ -77,7 +76,7 @@ private:
std::unique_ptr<wivrn_session> network_session;
std::thread network_thread;
thread_safe<to_headset::tracking_control> tracking_control{};
std::array<std::atomic<interaction_profile>, 3> interaction_profiles; // left hand, right hand, gamepad
std::array<std::atomic<interaction_profile>, 2> interaction_profiles; // left and right hand
std::atomic<bool> interaction_profile_changed = false;
std::atomic<XrTime> scheduled_derived_pose = 0; // Tracking thread will compute derived pose when time is reached
std::atomic<bool> recenter_requested = false;
@@ -132,7 +131,6 @@ private:
uint32_t height;
std::optional<imgui_context> imgui_ctx;
ImTextureID wivrn_logo = 0; // wordmark logo shown in the top bar, like the lobby
struct gui_toast
{
std::string content;
@@ -142,20 +140,6 @@ private:
static bool is_interactable(stream_tab);
bool is_gui_interactable() const;
// settings sub-page, client-only: the wire stream_tab stays settings
enum class settings_page
{
video,
audio,
streaming,
post_processing,
devices,
tracking,
theme,
system,
};
settings_page current_settings_page = settings_page::video;
// Tab currently being displayed
stream_tab gui_status = stream_tab::hidden;
// Tab that we will switch to if button is pressed
@@ -173,28 +157,22 @@ private:
XrAction plots_toggle_2 = XR_NULL_HANDLE;
XrAction recenter_left = XR_NULL_HANDLE;
XrAction recenter_right = XR_NULL_HANDLE;
XrAction gui_distance_left = XR_NULL_HANDLE;
XrAction gui_distance_right = XR_NULL_HANDLE;
XrAction settings_adjust = XR_NULL_HANDLE;
XrAction foveation_distance = XR_NULL_HANDLE;
XrAction foveation_ok = XR_NULL_HANDLE;
XrAction foveation_cancel = XR_NULL_HANDLE;
// Position of the GUI relative to the view space, in view space axes, used when the GUI is not interactable
// Position of the GUI relative to the view space, in view space axes
glm::vec3 head_gui_position{-0.1, -0.3, -1.2}; // Shift 10cm left by default so that the stats are centered accounting for the tab list
glm::quat head_gui_orientation{1, 0, 0, 0};
// Position of the GUI relative to the world space, in world space axes, used when the GUI is interactable
glm::vec3 world_gui_position;
glm::quat world_gui_orientation;
bool override_foveation_enable;
float override_foveation_pitch; // The pitch is the opposite as the height displayed in the GUI
float override_foveation_distance;
// Which controller is used for recentering and position of the GUI relative to the controller, in controller axes, during recentering
std::optional<std::tuple<xr::spaces, glm::vec3, glm::quat>> recentering_context;
void update_gui_position(xr::spaces controller, float predicted_display_period);
void update_gui_position(xr::spaces controller);
// Keep a reference to the resources needed to blit the images until vkWaitForFences
std::array<std::shared_ptr<wivrn::shard_accumulator::blit_handle>, decoder_count> current_blit_handles;
@@ -204,7 +182,7 @@ private:
stream(std::string server_name, scene & parent_scene);
bool forward_hid_input(from_headset::hid::input_t, bool device_enabled);
bool forward_hid_input(from_headset::hid::input_t);
public:
~stream();
@@ -255,13 +233,6 @@ public:
return state_;
}
// Whether the server mirrors forwarded input devices to uinput. The gamepad is also exposed
// through OpenXR regardless, so this only affects forwarded keyboard and mouse.
bool hid_forwarding_enabled() const
{
return hid_forwarding;
}
void exit();
void start_application(std::string appid);
+3 -9
View File
@@ -43,8 +43,6 @@ struct vert_pc
{
glm::ivec4 rgb_rect;
glm::ivec4 a_rect;
std::array<float, 4> scale;
std::array<float, 4> bias;
};
void stream_defoveator::ensure_vertices(size_t num_vertices)
@@ -106,7 +104,7 @@ stream_defoveator::pipeline_t & stream_defoveator::ensure_pipeline(size_t view,
// pipeline layout
vk::PushConstantRange pc_range{
.stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
.stageFlags = vk::ShaderStageFlagBits::eVertex,
.size = sizeof(vert_pc),
};
@@ -127,7 +125,7 @@ stream_defoveator::pipeline_t & stream_defoveator::ensure_pipeline(size_t view,
// Fragment shader
auto specialization = make_specialization_constants(
int32_t(alpha),
VkBool32(application::get_hmd_traits().needs_srgb_conversion));
VkBool32(need_srgb_conversion(guess_model())));
auto fragment_shader = load_shader(device, "reprojection.frag");
vk::pipeline_builder pipeline_info{
@@ -306,8 +304,6 @@ static size_t required_vertices(const wivrn::to_headset::foveation_parameter & p
void stream_defoveator::defoveate(vk::raii::CommandBuffer & command_buffer,
const std::array<wivrn::to_headset::foveation_parameter, 2> & foveation,
const std::array<input, 2> & inputs,
std::array<float, 4> scale,
std::array<float, 4> bias,
int destination)
{
if (destination < 0 || destination >= (int)output_images.size())
@@ -428,8 +424,6 @@ void stream_defoveator::defoveate(vk::raii::CommandBuffer & command_buffer,
input.rect_a.offset.y,
input.rect_a.extent.width,
input.rect_a.extent.height),
.scale = scale,
.bias = bias,
};
device.updateDescriptorSets(descriptor_writes, {});
@@ -437,7 +431,7 @@ void stream_defoveator::defoveate(vk::raii::CommandBuffer & command_buffer,
command_buffer.beginRenderPass(begin_info, vk::SubpassContents::eInline);
command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *pipeline.pipeline);
command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *pipeline.layout, 0, pipeline.ds, {});
command_buffer.pushConstants<vert_pc>(*pipeline.layout, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0, pc);
command_buffer.pushConstants<vert_pc>(*pipeline.layout, vk::ShaderStageFlagBits::eVertex, 0, pc);
command_buffer.bindVertexBuffers(0, vk::Buffer(buffer), vertices_size * view);
command_buffer.draw(required_vertices(foveation[view]), 1, 0, 0);
command_buffer.endRenderPass();
-2
View File
@@ -87,8 +87,6 @@ public:
vk::raii::CommandBuffer & command_buffer,
const std::array<wivrn::to_headset::foveation_parameter, 2> & foveation,
const std::array<input, 2> & inputs,
std::array<float, 4> scale,
std::array<float, 4> bias,
int destination);
static XrExtent2Di defoveated_size(const wivrn::to_headset::foveation_parameter &);
+329 -342
View File
@@ -17,21 +17,18 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#define IMGUI_DEFINE_MATH_OPERATORS
#include "stream.h"
#include "application.h"
#include "configuration.h"
#include "constants.h"
#include "gui_common.h"
#include "gui_settings.h"
#include "imgui.h"
#include "imgui_internal.h"
#include "implot.h"
#include "render/ui_theme.h"
#include "render/ui_widgets.h"
#include "utils/i18n.h"
#include "utils/ranges.h"
#include <IconsFontAwesome7.h>
#include <IconsFontAwesome6.h>
#include <chrono>
#include <cmath>
#include <glm/ext.hpp>
@@ -168,7 +165,6 @@ void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std
void scenes::stream::gui_performance_metrics()
{
const ImGuiStyle & style = ImGui::GetStyle();
const wivrn::ui::theme & t = wivrn::ui::current();
ImVec2 window_size = ImGui::GetWindowSize() - ImVec2(2, 2) * style.WindowPadding;
@@ -193,10 +189,7 @@ void scenes::stream::gui_performance_metrics()
window_size.x / n_cols - style.ItemSpacing.x * (n_cols - 1) / n_cols,
(window_size.y - 2 * ImGui::GetCurrentContext()->FontSize - 2 * style.ItemSpacing.y) / n_rows - style.ItemSpacing.y * (n_rows - 1) / n_rows);
ImPlot::PushStyleColor(ImPlotCol_PlotBg, ImVec4{t.background.x, t.background.y, t.background.z, 0.8f});
ImPlot::PushStyleColor(ImPlotCol_PlotBorder, t.border);
ImPlot::PushStyleColor(ImPlotCol_LegendBg, ImVec4{t.card.x, t.card.y, t.card.z, 0.9f});
ImPlot::PushStyleColor(ImPlotCol_InlayText, t.text);
ImPlot::PushStyleColor(ImPlotCol_PlotBg, IM_COL32(32, 32, 32, 64));
ImPlot::PushStyleColor(ImPlotCol_FrameBg, IM_COL32(0, 0, 0, 0));
ImPlot::PushStyleColor(ImPlotCol_AxisBg, IM_COL32(0, 0, 0, 0));
ImPlot::PushStyleColor(ImPlotCol_AxisBgActive, IM_COL32(0, 0, 0, 0));
@@ -225,11 +218,8 @@ void scenes::stream::gui_performance_metrics()
std::string title_with_units = std::string(title) + " [" + prefix + unit + "]";
ImPlot::SetupAxes(nullptr, title_with_units.c_str(), ImPlotAxisFlags_NoDecorations, 0);
ImPlot::SetupAxesLimits(0, global_metrics.size() - 1, min_v * multiplier, axis_scale[n] * multiplier, ImGuiCond_Always);
ImPlotSpec spec;
spec.LineColor = color;
spec.FillColor = color;
spec.FillAlpha = 0.25;
spec.Flags = ImPlotLineFlags_Shaded;
ImPlot::SetNextLineStyle(color);
ImPlot::SetNextFillStyle(color, 0.25);
for (const auto & [subtitle, data]: subplots)
{
@@ -238,12 +228,12 @@ void scenes::stream::gui_performance_metrics()
.stride = sizeof(global_metric),
.multiplier = multiplier,
};
ImPlot::PlotLineG(subtitle.c_str(), getter, &gdata, global_metrics.size(), spec);
ImPlot::PlotLineG(subtitle.c_str(), getter, &gdata, global_metrics.size(), ImPlotLineFlags_Shaded);
double x[] = {double(metrics_offset), double(metrics_offset)};
double y[] = {0, axis_scale[n] * multiplier};
spec.LineColor = ImVec4(1, 1, 1, 1);
ImPlot::PlotLine("", x, y, 2, spec);
ImPlot::SetNextLineStyle(ImVec4(1, 1, 1, 1));
ImPlot::PlotLine("", x, y, 2);
}
ImPlot::EndPlot();
}
@@ -337,7 +327,8 @@ void scenes::stream::gui_performance_metrics()
double x[] = {double(metrics_offset), double(metrics_offset)};
double y[] = {0, 1e9};
ImPlot::PlotLine("", x, y, 2, {ImPlotProp_LineColor, ImVec4(1, 1, 1, 1)});
ImPlot::SetNextLineStyle(ImVec4(1, 1, 1, 1));
ImPlot::PlotLine("", x, y, 2);
ImPlot::EndPlot();
}
@@ -346,7 +337,7 @@ void scenes::stream::gui_performance_metrics()
ImGui::SameLine();
}
ImPlot::PopStyleColor(8);
ImPlot::PopStyleColor(5);
{
ImGui::TextUnformatted(
fmt::format(
@@ -386,75 +377,208 @@ void scenes::stream::gui_compact_view()
}
}
static void send_settings_changed_packet(xr::session & session, wivrn_session * network, const configuration & config)
static void send_settings_changed_packet(xr::session & session, wivrn_session * network, const configuration & config, float predicted_display_period)
{
network->send_control(
from_headset::settings_changed{
.preferred_refresh_rate = config.preferred_refresh_rate,
.minimum_refresh_rate = config.minimum_refresh_rate.value_or(0),
.fps_divider = config.fps_divider,
.bitrate_bps = config.bitrate_bps,
.mirror_gamepad = config.forward_gamepad,
.enabled_body_parts = config.body_part_mask,
});
const auto & refresh_rates = session.get_refresh_rates();
from_headset::settings_changed packet{
.bitrate_bps = config.bitrate_bps,
};
if (not refresh_rates.empty())
{
packet.preferred_refresh_rate = config.preferred_refresh_rate;
packet.minimum_refresh_rate = config.minimum_refresh_rate.value_or(0);
}
else
{
packet.preferred_refresh_rate = predicted_display_period;
}
network->send_control(std::move(packet));
}
void scenes::stream::gui_settings(float)
std::string openxr_post_processing_flag_name(XrCompositionLayerSettingsFlagsFB flag); // TODO declaration in a .h file
void scenes::stream::gui_settings(float predicted_display_period)
{
// same pages as the lobby, with in_game enabling the in-stream controls
wivrn::gui::settings_context ctx{
.config = application::get_config(),
.default_config = application::get_default_config(),
.instance = instance,
.session = session,
.system = system,
.imgui_ctx = *imgui_ctx,
.recommended_width = width,
.recommended_height = height,
.in_game = true,
.server_hid_forwarding = hid_forwarding_enabled(),
.on_streaming_changed = [this] { send_settings_changed_packet(session, network_session.get(), application::get_config()); },
.enter_foveation_adjust = [this] { next_gui_status = stream_tab::foveation_settings; },
.on_foveation_override_changed = [this] {
const auto & config = application::get_config();
override_foveation_enable = config.override_foveation_enable;
override_foveation_pitch = config.override_foveation_pitch;
override_foveation_distance = config.override_foveation_distance;
network_session->send_control(from_headset::override_foveation_center{
.enabled = override_foveation_enable,
.pitch = override_foveation_pitch,
.distance = override_foveation_distance,
}); },
};
const ImGuiStyle & style = ImGui::GetStyle();
auto & config = application::get_config();
switch (current_settings_page)
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(20, 20));
if (instance.has_extension(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME))
{
case settings_page::video:
wivrn::gui::settings_video(ctx);
break;
case settings_page::audio:
wivrn::gui::settings_audio(ctx);
break;
case settings_page::streaming:
wivrn::gui::settings_streaming(ctx);
break;
case settings_page::post_processing:
wivrn::gui::settings_post_processing(ctx);
break;
case settings_page::devices:
wivrn::gui::settings_devices(ctx);
break;
case settings_page::tracking:
if (wivrn::gui::settings_tracking(ctx))
send_settings_changed_packet(session, network_session.get(), ctx.config);
break;
case settings_page::system:
wivrn::gui::settings_system(ctx);
break;
case settings_page::theme:
wivrn::gui::settings_theme(ctx);
break;
const auto & refresh_rates = session.get_refresh_rates();
if (not refresh_rates.empty())
{
float active_rate = config.preferred_refresh_rate;
if (ImGui::BeginCombo(_S("Refresh rate"), active_rate ? fmt::format("{}", active_rate).c_str() : _cS("automatic refresh rate", "Automatic")))
{
if (ImGui::Selectable(_cS("automatic refresh rate", "Automatic"), active_rate == 0, ImGuiSelectableFlags_SelectOnRelease))
{
config.preferred_refresh_rate = 0;
send_settings_changed_packet(session, network_session.get(), config, predicted_display_period);
config.save();
}
if (ImGui::IsItemHovered())
imgui_ctx->tooltip(_("Select refresh rate based on measured application performance.\nMay cause flicker when a change happens."));
for (float rate: refresh_rates)
{
if (ImGui::Selectable(fmt::format("{}", rate).c_str(), rate == active_rate, ImGuiSelectableFlags_SelectOnRelease))
{
session.set_refresh_rate(rate);
config.preferred_refresh_rate = rate;
send_settings_changed_packet(session, network_session.get(), config, predicted_display_period);
config.save();
}
}
ImGui::EndCombo();
}
imgui_ctx->vibrate_on_hover();
if (active_rate == 0 and refresh_rates.size() > 2)
{
float min_rate = config.minimum_refresh_rate.value_or(refresh_rates.front());
if (ImGui::BeginCombo(_S("Minimum refresh rate"), fmt::format("{}", min_rate).c_str()))
{
for (float rate: refresh_rates | std::views::take(refresh_rates.size() - 1))
{
if (ImGui::Selectable(fmt::format("{}", rate).c_str(), rate == config.minimum_refresh_rate, ImGuiSelectableFlags_SelectOnRelease))
{
config.minimum_refresh_rate = rate;
send_settings_changed_packet(session, network_session.get(), config, predicted_display_period);
config.save();
}
}
ImGui::EndCombo();
}
imgui_ctx->vibrate_on_hover();
}
}
}
{
const auto text = _("Bitrate:");
const auto size = ImGui::CalcTextSize(text.c_str());
ImGui::Text("%s", text.c_str());
ImGui::SameLine(0.f, 10.f);
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (size.y / 4.f) - style.FramePadding.y * 3.f);
if (ImGui::Button(fmt::format("{}Mbit/s", config.bitrate_bps / 1'000'000).c_str()))
next_gui_status = stream_tab::bitrate_settings;
imgui_ctx->vibrate_on_hover();
if (ImGui::IsItemHovered())
imgui_ctx->tooltip(_("Click to adjust bitrate"));
}
if (application::get_openxr_post_processing_supported())
{
ImGui::Text("%s", _S("OpenXR post-processing"));
ImGui::Indent();
{
XrCompositionLayerSettingsFlagsFB current = config.openxr_post_processing.super_sampling;
if (ImGui::BeginCombo(_S("Supersampling"), openxr_post_processing_flag_name(current).c_str()))
{
const XrCompositionLayerSettingsFlagsFB selectable_options[]{
0,
XR_COMPOSITION_LAYER_SETTINGS_NORMAL_SUPER_SAMPLING_BIT_FB,
XR_COMPOSITION_LAYER_SETTINGS_QUALITY_SUPER_SAMPLING_BIT_FB};
for (XrCompositionLayerSettingsFlagsFB option: selectable_options)
{
if (ImGui::Selectable(openxr_post_processing_flag_name(option).c_str(), current == option, ImGuiSelectableFlags_SelectOnRelease))
{
spdlog::info("Setting OpenXR super sampling to {}", openxr_post_processing_flag_name(option));
config.openxr_post_processing.super_sampling = option;
config.save();
}
imgui_ctx->vibrate_on_hover();
}
ImGui::EndCombo();
}
imgui_ctx->vibrate_on_hover();
if (ImGui::IsItemHovered())
{
imgui_ctx->tooltip(_("Reduce flicker for high contrast edges.\nUseful when the input resolution is high compared to the headset display"));
}
}
{
XrCompositionLayerSettingsFlagsFB current = config.openxr_post_processing.sharpening;
if (ImGui::BeginCombo(_S("Sharpening"), openxr_post_processing_flag_name(current).c_str()))
{
const XrCompositionLayerSettingsFlagsFB selectable_options[]{
0,
XR_COMPOSITION_LAYER_SETTINGS_NORMAL_SHARPENING_BIT_FB,
XR_COMPOSITION_LAYER_SETTINGS_QUALITY_SHARPENING_BIT_FB};
for (XrCompositionLayerSettingsFlagsFB option: selectable_options)
{
if (ImGui::Selectable(openxr_post_processing_flag_name(option).c_str(), current == option, ImGuiSelectableFlags_SelectOnRelease))
{
spdlog::info("Setting OpenXR sharpening to {}", openxr_post_processing_flag_name(option));
config.openxr_post_processing.sharpening = option;
config.save();
}
imgui_ctx->vibrate_on_hover();
}
ImGui::EndCombo();
}
imgui_ctx->vibrate_on_hover();
if (ImGui::IsItemHovered())
{
imgui_ctx->tooltip(_("Improve clarity of high contrast edges and counteract blur.\nUseful when the input resolution is low compared to the headset display"));
}
}
ImGui::Unindent();
}
bool send_packet = false;
bool save_config = false;
ImGui::Text("%s", _S("Foveation center override"));
ImGui::Indent();
{
if (ImGui::Checkbox(_S("Enable"), &override_foveation_enable))
{
send_packet = true;
save_config = true;
}
imgui_ctx->vibrate_on_hover();
ImGui::BeginDisabled(!override_foveation_enable);
ImGui::Text("%s", fmt::format(_F("Height {:.1f} deg"), -override_foveation_pitch * 180 / M_PI).c_str());
ImGui::Text("%s", fmt::format(_F("Distance {:.2f} m"), override_foveation_distance).c_str());
if (ImGui::Button(_S("Default")))
{
override_foveation_distance = configuration{}.override_foveation_distance;
override_foveation_pitch = configuration{}.override_foveation_pitch;
send_packet = true;
save_config = true;
}
imgui_ctx->vibrate_on_hover();
ImGui::SameLine();
if (ImGui::Button(_S("Change")))
next_gui_status = stream_tab::foveation_settings;
imgui_ctx->vibrate_on_hover();
ImGui::EndDisabled();
}
ImGui::Unindent();
if (send_packet)
{
network_session->send_control(from_headset::override_foveation_center{
.enabled = override_foveation_enable,
.pitch = override_foveation_pitch,
.distance = override_foveation_distance,
});
}
if (save_config)
{
auto & config = application::get_config();
config.override_foveation_enable = override_foveation_enable;
config.override_foveation_pitch = override_foveation_pitch;
config.override_foveation_distance = override_foveation_distance;
config.save();
}
ImGui::PopStyleVar();
}
void scenes::stream::gui_bitrate_settings(float predicted_display_period)
@@ -479,7 +603,7 @@ void scenes::stream::gui_bitrate_settings(float predicted_display_period)
next_gui_status = stream_tab::settings;
}
send_settings_changed_packet(session, network_session.get(), application::get_config());
send_settings_changed_packet(session, network_session.get(), application::get_config(), predicted_display_period);
}
void scenes::stream::gui_foveation_settings(float predicted_display_period)
@@ -487,7 +611,7 @@ void scenes::stream::gui_foveation_settings(float predicted_display_period)
ImGui::PushFont(nullptr, constants::gui::font_size_large);
ImGui::Text("%s", _S("Use the thumbsticks to move the foveation center"));
ImGui::Text("%s", _S("Press A to save or B to cancel"));
ImGui::Text("%s", fmt::format(_F("Height {:.1f} °"), -override_foveation_pitch * 180 / M_PI).c_str());
ImGui::Text("%s", fmt::format(_F("Height {:.1f} deg"), -override_foveation_pitch * 180 / M_PI).c_str());
ImGui::Text("%s", fmt::format(_F("Distance {:.2f} m"), override_foveation_distance).c_str());
ImGui::PopFont();
@@ -495,10 +619,10 @@ void scenes::stream::gui_foveation_settings(float predicted_display_period)
float delta_pitch = application::read_action_float(settings_adjust).value_or(std::pair{0, 0}).second * predicted_display_period;
// Maximum speed 2m/s @ 1m
float delta_distance = std::pow(constants::stream::gui_max_foveation_speed, application::read_action_float(foveation_distance).value_or(std::pair{0, 0}).second * predicted_display_period);
float delta_distance = std::exp(std::log(2) * application::read_action_float(foveation_distance).value_or(std::pair{0, 0}).second * predicted_display_period);
override_foveation_pitch = std::clamp<float>(override_foveation_pitch + delta_pitch, constants::stream::gui_min_foveation_pitch, constants::stream::gui_max_foveation_pitch);
override_foveation_distance = std::clamp<float>(override_foveation_distance * delta_distance, constants::stream::gui_min_foveation_distance, constants::stream::gui_max_foveation_distance);
override_foveation_pitch = std::clamp<float>(override_foveation_pitch + delta_pitch, -M_PI / 3, M_PI / 3);
override_foveation_distance = std::clamp<float>(override_foveation_distance * delta_distance, 0.5, 100);
bool ok = application::read_action_bool(foveation_ok).value_or(std::pair{0, false}).second;
bool cancel = application::read_action_bool(foveation_cancel).value_or(std::pair{0, false}).second;
@@ -541,77 +665,68 @@ void scenes::stream::gui_applications()
network_session->send_control(from_headset::get_running_applications{});
}
wivrn::ui::page_header(_cS("page header title", "Applications"), _cS("page header subtitle", "Running XR applications on the server."));
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {10, 10});
ImGui::PushFont(nullptr, constants::gui::font_size_large);
CenterTextH(_("Running XR applications:"));
ImGui::PopFont();
auto apps = running_applications.lock();
ImVec2 button_size(ImGui::GetWindowSize().x - ImGui::GetCursorPosX() - 20, 0);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(ImGui::GetStyle().ItemSpacing.x, 20));
ImGui::Spacing();
std::ranges::sort(apps->applications, [](auto & l, auto & r) {
if (l.overlay == r.overlay)
return false;
return r.overlay;
});
const float gap = ImGui::GetStyle().ItemSpacing.x;
const float ctrl_h = ImGui::GetFrameHeight() * wivrn::ui::metrics::control_height;
const std::string stop_label = wivrn::ui::icon_label(ICON_FA_XMARK, _C("button label to ask an application to quit", "Stop"));
const float stop_w = wivrn::ui::button_width(stop_label);
const std::string active_label = wivrn::ui::icon_label(ICON_FA_CIRCLE_CHECK, _C("chip displayed next to a running application while streaming", "Active"));
const float active_w = wivrn::ui::chip_width(active_label, false, stop_w);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, wivrn::ui::metrics::card_item_spacing);
wivrn::ui::begin_list_card("##running");
bool overlay = false;
for (const auto & app: apps->applications)
{
if (apps->applications.empty())
if (app.overlay and not overlay)
{
ImGui::PushStyleColor(ImGuiCol_Text, wivrn::ui::current().text_muted);
ImGui::TextUnformatted(_S("No XR application is currently running."));
ImGui::PopStyleColor();
ImGui::Separator();
CenterTextH(_S("Overlays"));
overlay = true;
}
bool overlay = false;
bool first = true;
for (const auto & app: apps->applications)
int colors = 1;
ImGui::PushStyleColor(ImGuiCol_Button, IM_COL32_BLACK_TRANS);
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 20));
if (app.active or app.overlay)
{
if (app.overlay and not overlay)
{
overlay = true;
ImGui::PushStyleColor(ImGuiCol_Text, wivrn::ui::current().text_muted);
ImGui::TextUnformatted(_S("Overlays"));
ImGui::PopStyleColor();
first = true;
}
ImGui::PushID(static_cast<int>(app.id));
if (not first)
wivrn::ui::row_separator();
first = false;
// overlays and the active app aren't selectable, only their stop button acts
const bool interactive = not(app.active or app.overlay);
const float trailing = stop_w + (app.active ? gap + active_w : 0) + wivrn::ui::metrics::list_row_pad;
const auto row = wivrn::ui::begin_list_row("##row", ICON_FA_CUBE, 0, app.name, {}, app.active, trailing, 0, false, interactive);
float x = row.max.x;
ImGui::SetCursorScreenPos(row.trailing(x, {stop_w, ctrl_h}));
if (wivrn::ui::button(stop_label, wivrn::ui::button_style::danger, {stop_w, 0}))
network_session->send_control(from_headset::stop_application{.id = app.id});
if (ImGui::IsItemHovered())
imgui_ctx->tooltip(_S("Request to quit, may be ignored by the application"));
x -= stop_w + gap;
if (app.active)
{
ImGui::SetCursorScreenPos(row.trailing(x, {active_w, ctrl_h}));
wivrn::ui::chip(active_label, wivrn::ui::chip_style::success, false, ctrl_h);
}
if (row.clicked and interactive)
network_session->send_control(from_headset::set_active_application{.id = app.id});
wivrn::ui::end_list_row();
ImGui::PopID();
ImGui::PushStyleColor(ImGuiCol_ButtonActive, IM_COL32_BLACK_TRANS);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, IM_COL32_BLACK_TRANS);
colors += 2;
}
ImGui::SetNextItemAllowOverlap();
const bool clicked = RadioButtonWithoutCheckBox(
std::format("{}{}##{}", app.active ? ICON_FA_CHEVRON_RIGHT " " : " ", app.name, app.id).c_str(),
app.active,
button_size);
if (clicked and not(app.active or app.overlay))
{
network_session->send_control(from_headset::set_active_application{.id = app.id});
imgui_ctx->vibrate_on_hover();
}
ImGui::PopStyleColor(colors);
ImGui::PopStyleVar(2);
ImGui::SameLine();
auto right = ImGui::GetWindowSize().x;
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 10);
ImGui::SetCursorPosX(right - ImGui::CalcTextSize(ICON_FA_XMARK).x - ImGui::GetStyle().FramePadding.x - 40);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f));
if (ImGui::Button(std::format(ICON_FA_XMARK "##{}", app.id).c_str()))
network_session->send_control(from_headset::stop_application{.id = app.id});
imgui_ctx->vibrate_on_hover();
ImGui::PopStyleColor(3);
if (ImGui::IsItemHovered())
imgui_ctx->tooltip(_S("Request to quit, may be ignored by the application"));
}
wivrn::ui::end_card();
ImGui::PopStyleVar();
ImGui::PopStyleVar(3);
}
void scenes::stream::gui_toasts()
@@ -632,24 +747,6 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
if (auto new_status = next_gui_status.load(); new_status != gui_status)
{
spdlog::info("Switch tab from {} to {}", magic_enum::enum_name(gui_status), magic_enum::enum_name(new_status));
if (not is_gui_interactable() and is_interactable(new_status))
{
if (auto head_position = application::locate_controller(application::space(xr::spaces::view), application::space(xr::spaces::world), predicted_display_time))
{
world_gui_orientation = head_position->second * head_gui_orientation;
world_gui_position = head_position->first + glm::mat3_cast(head_position->second) * head_gui_position;
}
}
else if (is_gui_interactable() and not is_interactable(new_status))
{
if (auto head_position = application::locate_controller(application::space(xr::spaces::view), application::space(xr::spaces::world), predicted_display_time))
{
head_gui_orientation = glm::conjugate(head_position->second) * world_gui_orientation;
head_gui_position = glm::mat3_cast(glm::conjugate(head_position->second)) * (world_gui_position - head_position->first);
}
}
stored_gui_status = gui_status;
gui_status = new_status;
gui_status_last_change = predicted_display_time;
@@ -674,6 +771,7 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
switch (gui_status)
{
case stream_tab::hidden:
case stream_tab::bitrate_settings:
case stream_tab::foveation_settings:
case stream_tab::overlay_only:
case stream_tab::compact:
@@ -685,7 +783,7 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
case stream_tab::application_launcher:
break;
}
imgui_ctx->set_controllers_enabled(interactable and not recentering_context);
imgui_ctx->set_controllers_enabled(interactable);
if (interactable)
{
if (system.hand_tracking_supported())
@@ -729,6 +827,7 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
glm::mat3 M = glm::mat3_cast(head_position->second);
switch (gui_status)
{
case stream_tab::bitrate_settings:
case stream_tab::foveation_settings:
imgui_ctx->layers()[0].orientation = head_position->second;
imgui_ctx->layers()[0].position = head_position->first + M * glm::vec3{0, override_foveation_distance * sin(override_foveation_pitch), -override_foveation_distance};
@@ -742,67 +841,48 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
case stream_tab::overlay_only:
case stream_tab::compact:
imgui_ctx->layers()[0].orientation = head_position->second * head_gui_orientation;
imgui_ctx->layers()[0].position = head_position->first + M * head_gui_position;
break;
case stream_tab::stats:
case stream_tab::settings:
case stream_tab::applications:
case stream_tab::application_launcher:
imgui_ctx->layers()[0].orientation = world_gui_orientation;
imgui_ctx->layers()[0].position = world_gui_position;
imgui_ctx->layers()[0].orientation = head_position->second * head_gui_orientation;
imgui_ctx->layers()[0].position = head_position->first + M * head_gui_position;
break;
}
}
// popup layer floats in front of the main panel so combos and modals pop as their own quad
imgui_ctx->place_layer_relative(2, 0, constants::gui::popup_position);
const float tab_width = wivrn::ui::metrics::sidebar_width;
const float top_bar_h = wivrn::ui::metrics::top_bar_height;
const float content_margin = wivrn::ui::metrics::content_margin;
const float tab_width = 300;
const ImVec2 margin_around_window{50, 50};
ImGuiStyle & style = ImGui::GetStyle();
const ImGuiStyle & style = ImGui::GetStyle();
imgui_ctx->new_frame(predicted_display_time);
// theme the shared cards like the lobby, widget hooks are global so re-point at this scene
style.FontScaleMain = wivrn::ui::current().font_scale * wivrn::ui::metrics::font_base;
style.WindowRounding = wivrn::ui::current().card_rounding;
style.ChildRounding = wivrn::ui::current().card_rounding;
style.PopupRounding = wivrn::ui::current().card_rounding;
style.FrameRounding = wivrn::ui::current().rounding;
style.GrabRounding = wivrn::ui::current().rounding;
style.TabRounding = wivrn::ui::current().rounding;
style.Colors[ImGuiCol_Text] = wivrn::ui::current().text;
style.Colors[ImGuiCol_TextDisabled] = wivrn::ui::current().text_muted;
wivrn::ui::set_popup_center(imgui_ctx->layers()[2].vp_center(), float(imgui_ctx->layers()[2].vp_size.y));
wivrn::ui::set_hover_haptic([this] { imgui_ctx->vibrate_on_hover(); });
wivrn::ui::set_tooltip_hook([this](const char * text) { imgui_ctx->tooltip(text); });
ImVec2 viewport_size(imgui_ctx->layers()[0].vp_size.x, imgui_ctx->layers()[0].vp_size.y);
ImVec2 content_size{viewport_size - ImVec2{tab_width, 0} - margin_around_window * 2};
ImVec2 content_center = margin_around_window + content_size / 2 + ImVec2{tab_width, 0};
bool display_tabs = false;
bool always_auto_resize = false;
bool display_tabs, always_auto_resize;
switch (gui_status)
{
case stream_tab::overlay_only:
ImGui::SetNextWindowPos(content_center, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::SetNextWindowSize(content_size);
always_auto_resize = false;
display_tabs = false;
break;
case stream_tab::hidden:
case stream_tab::bitrate_settings:
case stream_tab::foveation_settings:
ImGui::SetNextWindowPos(viewport_size / 2, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
always_auto_resize = true;
display_tabs = false;
break;
case stream_tab::compact:
ImGui::SetNextWindowPos(content_center, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
always_auto_resize = true;
display_tabs = false;
break;
case stream_tab::stats:
@@ -810,11 +890,14 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
case stream_tab::applications:
ImGui::SetNextWindowPos(margin_around_window);
ImGui::SetNextWindowSize(viewport_size - margin_around_window * 2);
always_auto_resize = false;
display_tabs = true;
break;
case stream_tab::application_launcher:
ImGui::SetNextWindowPos(margin_around_window);
ImGui::SetNextWindowSize(viewport_size - margin_around_window * 2);
always_auto_resize = false;
display_tabs = false;
break;
}
@@ -824,10 +907,6 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 4);
}
// themed translucent background, matching the lobby
const wivrn::ui::theme & th = wivrn::ui::current();
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4{th.background.x, th.background.y, th.background.z, wivrn::ui::background_alpha()});
ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0);
if (always_auto_resize)
{
@@ -867,28 +946,21 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
break;
case stream_tab::stats:
ImGui::SetCursorPos({tab_width + content_margin, top_bar_h});
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {20, 20});
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX() - content_margin, 0));
ImGui::SetCursorPosY(20);
wivrn::ui::page_header(_S("Statistics"), _S("Live streaming performance."));
ImGui::BeginChild("plots", {0, 0});
ImGui::SetCursorPos({tab_width + 20, 20});
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0));
gui_performance_metrics();
ImGui::EndChild();
ImGui::EndChild();
ImGui::PopStyleVar();
break;
case stream_tab::settings:
ImGui::SetCursorPos({tab_width + content_margin, top_bar_h});
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {20, 20});
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX() - content_margin, 0));
ImGui::SetCursorPosY(20);
ImGui::SetCursorPos({tab_width + 20, 20});
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0));
gui_settings(predicted_display_period * 1.e-9f);
ImGui::Dummy(ImVec2(0, 20));
ScrollWhenDragging();
ImGui::EndChild();
ImGui::PopStyleVar();
break;
case stream_tab::bitrate_settings:
gui_bitrate_settings(predicted_display_period * 1.e-9f);
break;
case stream_tab::foveation_settings:
@@ -896,15 +968,10 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
break;
case stream_tab::applications:
ImGui::SetCursorPos({tab_width + content_margin, top_bar_h});
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {20, 20});
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX() - content_margin, 0));
ImGui::SetCursorPosY(20);
ImGui::SetCursorPos({tab_width + 20, 20});
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0));
gui_applications();
ImGui::Dummy(ImVec2(0, 20));
ScrollWhenDragging();
ImGui::EndChild();
ImGui::PopStyleVar();
break;
case stream_tab::application_launcher:
@@ -916,96 +983,18 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
if (display_tabs)
{
// top bar: logo left, battery/connection status/window controls right
const float side = ImGui::GetFrameHeight() * wivrn::ui::metrics::control_height;
std::vector<wivrn::ui::top_bar_item> top_items;
if (auto bat = wivrn::gui::battery_status_indicator(instance.now()))
top_items.push_back({wivrn::ui::chip_width(bat->label, false, side),
[bat = *bat, side] { wivrn::ui::chip(bat.label, bat.style, false, side); }});
const std::string conn = _C("status in the title bar", "Connected");
top_items.push_back({wivrn::ui::chip_width(conn, true, side),
[conn, side] { wivrn::ui::chip(conn, wivrn::ui::chip_style::success, true, side); }});
const std::string close_label = _S("Close");
top_items.push_back({wivrn::ui::button_width(ICON_FA_XMARK, close_label),
[this, close_label, side] {
if (wivrn::ui::button(ICON_FA_XMARK, close_label, wivrn::ui::button_style::secondary, {0, side}))
next_gui_status = stream_tab::hidden;
}});
// disconnect asks for confirmation, OpenPopup/confirm_modal share the window id stack
bool request_disconnect = false;
const std::string disconnect_label = _S("Disconnect");
top_items.push_back({wivrn::ui::button_width(ICON_FA_DOOR_OPEN, disconnect_label),
[&request_disconnect, disconnect_label, side] {
if (wivrn::ui::button(ICON_FA_DOOR_OPEN, disconnect_label, wivrn::ui::button_style::danger, {0, side}))
request_disconnect = true;
}});
wivrn::ui::top_bar(top_bar_h, wivrn_logo, top_items);
if (request_disconnect)
ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 255));
ImGui::SetCursorPos(style.WindowPadding);
{
network_session->send_control(from_headset::get_running_applications{});
ImGui::OpenPopup("confirm disconnect");
}
ImGui::BeginChild("Tabs", {tab_width, ImGui::GetContentRegionMax().y - ImGui::GetWindowContentRegionMin().y});
if (wivrn::ui::begin_modal("confirm disconnect", _("Disconnect")))
{
const std::string kill_apps = ICON_FA_XMARK " " + _("Stop all applications");
const std::string disconnect_only = ICON_FA_DOOR_OPEN " " + _("Disconnect");
const std::string cancel = _("Cancel");
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 10));
const float gap = ImGui::GetStyle().ItemSpacing.x;
auto target = next_gui_status.load();
RadioButtonWithoutCheckBox(ICON_FA_LIST " " + _("Applications"), target, stream_tab::applications, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
const float kill_apps_w = ImGui::CalcTextSize(kill_apps.c_str()).x + wivrn::ui::metrics::button_padding.x * 2;
const float disconnect_only_w = ImGui::CalcTextSize(disconnect_only.c_str()).x + wivrn::ui::metrics::button_padding.x * 2;
const float cancel_w = ImGui::CalcTextSize(cancel.c_str()).x + wivrn::ui::metrics::button_padding.x * 2;
const float buttons_width = disconnect_only_w + cancel_w + kill_apps_w + 2 * gap;
ImGui::Dummy({std::max<float>(500, buttons_width), 0});
const auto & t = wivrn::ui::current();
ImGui::PushStyleColor(ImGuiCol_Text, t.text_muted);
ImGui::TextWrapped("%s", _S("Disconnect from the server and return to the lobby?"));
ImGui::TextWrapped("%s", _S("The following applications/overlays are open:"));
for (const auto & app: running_applications.lock()->applications)
ImGui::TextWrapped("• %s", app.name.c_str());
ImGui::PopStyleColor();
ImGui::Dummy({0, 12});
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - buttons_width);
if (button(kill_apps, wivrn::ui::button_style::danger, {kill_apps_w, 0}))
{
for (const auto & app: running_applications.lock()->applications)
network_session->send_control(from_headset::stop_application{.id = app.id});
exit();
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (button(disconnect_only, wivrn::ui::button_style::primary, {disconnect_only_w, 0}))
{
exit();
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (button(cancel, wivrn::ui::button_style::secondary, {cancel_w, 0}))
{
ImGui::CloseCurrentPopup();
}
wivrn::ui::end_modal();
}
// navigation sidebar, the settings items swap the page but keep the coarse settings tab
wivrn::ui::begin_sidebar(top_bar_h, tab_width, 2);
{
wivrn::ui::nav_section(_cS("tab group", "STREAM"));
if (wivrn::ui::nav_item(ICON_FA_LIST, _cS("tab label", "Applications"), gui_status == stream_tab::applications))
next_gui_status = stream_tab::applications;
if (wivrn::ui::nav_item(ICON_FA_ROCKET, _cS("tab label", "Start"), false))
if (RadioButtonWithoutCheckBox(ICON_FA_ROCKET " " + _("Start"), target, stream_tab::application_launcher, {tab_width, 0}))
{
apps.reset();
network_session->send_control(from_headset::get_application_list{
@@ -1013,42 +1002,40 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
.country = application::get_messages_info().country,
.variant = application::get_messages_info().variant,
});
next_gui_status = stream_tab::application_launcher;
}
if (wivrn::ui::nav_item(ICON_FA_COMPUTER, _S("Statistics"), gui_status == stream_tab::stats))
next_gui_status = stream_tab::stats;
imgui_ctx->vibrate_on_hover();
wivrn::ui::nav_section(_cS("tab group", "SETTINGS"));
auto settings_item = [&](const char * icon, const std::string & label, settings_page page) {
if (wivrn::ui::nav_item(icon, label, gui_status == stream_tab::settings and current_settings_page == page))
{
current_settings_page = page;
next_gui_status = stream_tab::settings;
}
};
settings_item(ICON_FA_IMAGE, _cS("tab label", "Video"), settings_page::video);
settings_item(ICON_FA_VOLUME_HIGH, _cS("tab label", "Audio"), settings_page::audio);
settings_item(ICON_FA_TOWER_BROADCAST, _cS("tab label", "Streaming"), settings_page::streaming);
settings_item(ICON_FA_WAND_MAGIC_SPARKLES, _cS("tab label", "Post-processing"), settings_page::post_processing);
settings_item(ICON_FA_KEYBOARD, _cS("tab label", "Devices"), settings_page::devices);
settings_item(ICON_FA_LOCATION_CROSSHAIRS, _cS("tab label", "Tracking"), settings_page::tracking);
settings_item(ICON_FA_GEARS, _cS("tab label", "System"), settings_page::system);
settings_item(ICON_FA_PALETTE, _cS("tab label", "Theme"), settings_page::theme);
RadioButtonWithoutCheckBox(ICON_FA_GEARS " " + _("Settings"), target, stream_tab::settings, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
// pinned to the bottom
wivrn::ui::sidebar_footer();
if (wivrn::ui::nav_item(ICON_FA_CHART_LINE, _cS("tab label", "Statistics overlay"), false))
next_gui_status = stream_tab::overlay_only;
if (wivrn::ui::nav_item(ICON_FA_MINIMIZE, _cS("tab label", "Compact view"), false))
next_gui_status = stream_tab::compact;
RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " " + _("Stats"), target, stream_tab::stats, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
int n_items_at_end = 4;
ImGui::SetCursorPosY(ImGui::GetContentRegionMax().y - n_items_at_end * ImGui::GetCurrentContext()->FontSize - (n_items_at_end * 2) * style.FramePadding.y - (n_items_at_end - 1) * style.ItemSpacing.y - style.WindowPadding.y);
RadioButtonWithoutCheckBox(ICON_FA_CHART_LINE " " + _("Statistics overlay"), target, stream_tab::overlay_only, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
RadioButtonWithoutCheckBox(ICON_FA_MINIMIZE " " + _("Compact view"), target, stream_tab::compact, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
RadioButtonWithoutCheckBox(ICON_FA_XMARK " " + _("Close"), target, stream_tab::hidden, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
bool dummy = false;
if (RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " " + _("Disconnect"), dummy, true, {tab_width, 0}))
exit();
imgui_ctx->vibrate_on_hover();
ImGui::PopStyleVar(); // ImGuiStyleVar_FramePadding
ImGui::EndChild();
next_gui_status = target;
}
wivrn::ui::end_sidebar();
wivrn::ui::shell_dividers(top_bar_h, tab_width);
ImGui::PopStyleColor(); // ImGuiCol_ChildBg
}
ImGui::End();
ImGui::PopStyleVar(2); // ImGuiStyleVar_ChildBorderSize, ImGuiStyleVar_WindowPadding
ImGui::PopStyleColor(); // ImGuiCol_WindowBg
ImGui::PopStyleVar(2); // ImGuiStyleVar_ChildBorderSize, ImGuiStyleVar_WindowPadding
auto layers = imgui_ctx->end_frame();
@@ -1073,14 +1060,14 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
}
if (state)
update_gui_position(controller, predicted_display_period * 1e-9f);
update_gui_position(controller);
else
recentering_context.reset();
}
else if (auto state = application::read_action_bool(recenter_left); state and state->second)
update_gui_position(xr::spaces::aim_left, predicted_display_period * 1e-9f);
update_gui_position(xr::spaces::aim_left);
else if (auto state = application::read_action_bool(recenter_right); state and state->second)
update_gui_position(xr::spaces::aim_right, predicted_display_period * 1e-9f);
update_gui_position(xr::spaces::aim_right);
else
recentering_context.reset();
@@ -1130,13 +1117,13 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte
}
}
// Add the layer with the GUI
for (auto [_, layer]: layers)
{
add_quad_layer(layer.layerFlags, layer.space, layer.eyeVisibility, layer.subImage, layer.pose, layer.size);
if (composition_layer_depth_test_supported)
set_depth_test(true, XR_COMPARE_OP_LESS_FB);
else if (alpha < 1 and composition_layer_color_scale_bias_supported)
if (alpha < 1 and composition_layer_color_scale_bias_supported)
set_color_scale_bias({alpha, alpha, alpha, alpha}, {});
}
+5 -11
View File
@@ -19,8 +19,10 @@
#include "stream.h"
#ifdef __ANDROID__
#include "application.h"
#include "utils/i18n.h"
#endif
#include "utils/named_thread.h"
#include <spdlog/spdlog.h>
@@ -85,12 +87,6 @@ void scenes::stream::operator()(to_headset::feature_control && control)
{
case wivrn::to_headset::feature_control::hid_input:
hid_forwarding = control.state;
if (not control.state and (application::get_config().forward_keyboard or application::get_config().forward_mouse or application::get_config().forward_gamepad))
{
auto toast = gui_toast.lock();
toast->emplace(_("The server does not allow forwarded input devices"), true);
gui_status_last_change = instance.now();
}
return;
case wivrn::to_headset::feature_control::microphone:
if (audio_handle)
@@ -98,7 +94,6 @@ void scenes::stream::operator()(to_headset::feature_control && control)
return;
}
}
void scenes::stream::operator()(to_headset::audio_stream_description && desc)
{
audio_handle.emplace(desc, *network_session, instance);
@@ -116,11 +111,10 @@ void scenes::stream::operator()(to_headset::video_stream_description && desc)
void scenes::stream::operator()(to_headset::refresh_rate_change && rate)
{
spdlog::info("refresh rate change request: {}", rate.hz);
session.set_refresh_rate(rate.hz);
session.set_refresh_rate(rate.fps);
std::shared_lock lock(decoder_mutex);
if (video_stream_description)
video_stream_description->refresh_rate = rate.hz;
video_stream_description->fps = rate.fps;
}
void scenes::stream::operator()(to_headset::stream_tab_change && tab)
+125 -87
View File
@@ -35,6 +35,30 @@
#include "android/battery.h"
#endif
static uint8_t cast_flags(XrSpaceLocationFlags location, XrSpaceVelocityFlags velocity)
{
uint8_t flags = 0;
if (location & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
flags |= from_headset::tracking::orientation_valid;
if (location & XR_SPACE_LOCATION_POSITION_VALID_BIT)
flags |= from_headset::tracking::position_valid;
if (velocity & XR_SPACE_VELOCITY_LINEAR_VALID_BIT)
flags |= from_headset::tracking::linear_velocity_valid;
if (velocity & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT)
flags |= from_headset::tracking::angular_velocity_valid;
if (location & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)
flags |= from_headset::tracking::orientation_tracked;
if (location & XR_SPACE_LOCATION_POSITION_TRACKED_BIT)
flags |= from_headset::tracking::position_tracked;
return flags;
}
namespace
{
@@ -57,7 +81,7 @@ from_headset::tracking::pose locate_space(device_id device, XrSpace space, XrSpa
.linear_velocity = velocity.linearVelocity,
.angular_velocity = velocity.angularVelocity,
.device = device,
.flags = from_headset::to_pose_flags(location.locationFlags, velocity.velocityFlags),
.flags = cast_flags(location.locationFlags, velocity.velocityFlags),
};
spdlog::warn("xrLocateSpace failed for {}: {}", magic_enum::enum_name(device), xr::to_string(res));
return {.device = device};
@@ -144,7 +168,7 @@ public:
.linear_velocity = velocity.linearVelocity,
.angular_velocity = velocity.angularVelocity,
.device = devices[i],
.flags = from_headset::to_pose_flags(location.locationFlags, velocity.velocityFlags),
.flags = cast_flags(location.locationFlags, velocity.velocityFlags),
});
}
}
@@ -167,15 +191,31 @@ static std::optional<std::array<from_headset::hand_tracking::pose, XR_HAND_JOINT
std::array<from_headset::hand_tracking::pose, XR_HAND_JOINT_COUNT_EXT> poses;
for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++)
{
const auto & joint = (*joints)[i];
poses[i] = {
.position = joint.first.pose.position,
.orientation = pack(joint.first.pose.orientation),
.linear_velocity = joint.second.linearVelocity,
.angular_velocity = joint.second.angularVelocity,
.radius = uint16_t(joint.first.radius * 10'000),
.flags = from_headset::to_pose_flags(joint.first.locationFlags, joint.second.velocityFlags),
.position = (*joints)[i].first.pose.position,
.orientation = pack((*joints)[i].first.pose.orientation),
.linear_velocity = (*joints)[i].second.linearVelocity,
.angular_velocity = (*joints)[i].second.angularVelocity,
.radius = uint16_t((*joints)[i].first.radius * 10'000),
};
if ((*joints)[i].first.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
poses[i].flags |= from_headset::hand_tracking::orientation_valid;
if ((*joints)[i].first.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT)
poses[i].flags |= from_headset::hand_tracking::position_valid;
if ((*joints)[i].second.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT)
poses[i].flags |= from_headset::hand_tracking::linear_velocity_valid;
if ((*joints)[i].second.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT)
poses[i].flags |= from_headset::hand_tracking::angular_velocity_valid;
if ((*joints)[i].first.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)
poses[i].flags |= from_headset::hand_tracking::orientation_tracked;
if ((*joints)[i].first.locationFlags & XR_SPACE_LOCATION_POSITION_TRACKED_BIT)
poses[i].flags |= from_headset::hand_tracking::position_tracked;
}
return poses;
@@ -276,7 +316,7 @@ void scenes::stream::tracking()
XrTime t0 = instance.now();
from_headset::tracking tracking;
std::vector<from_headset::hand_tracking> hands;
std::vector<std::variant<from_headset::meta_body, from_headset::bd_body, from_headset::htc_body>> body;
std::vector<from_headset::body_tracking> body;
std::vector<XrView> views;
std::vector<serialization_packet> packets;
@@ -298,7 +338,7 @@ void scenes::stream::tracking()
decltype(to_headset::tracking_control::pattern) pattern;
size_t pattern_position = 0;
XrDuration frame_duration{};
XrDuration frame_duration;
XrTime pattern_begin = instance.now();
while (state_ != state::shutdown)
@@ -365,7 +405,9 @@ void scenes::stream::tracking()
instance,
system,
session,
application::get_generic_trackers());
application::get_generic_trackers(),
config.fb_lower_body,
config.fb_hip);
}
else
body_tracker.emplace<std::monostate>();
@@ -401,7 +443,6 @@ void scenes::stream::tracking()
tracking.interaction_profiles = {
interaction_profiles[0].load(),
interaction_profiles[1].load(),
interaction_profiles[2].load(),
};
tracking.production_timestamp = t0;
@@ -452,31 +493,36 @@ void scenes::stream::tracking()
break;
case wivrn::device_id::EYE_GAZE:
// Eye gaze uses view pose as the origin
if (application::get_hmd_traits().view_locate)
tracking.device_poses.push_back(locate_space(item.device, spaces[item.device], spaces[wivrn::device_id::HEAD], tracking.timestamp));
else
switch (guess_model())
{
// Pico headsets fail to locate gaze relative to view
auto gaze = locate_space(item.device, spaces[item.device], world_space, tracking.timestamp);
auto view_pose = locate_space(item.device, view_space, world_space, tracking.timestamp);
glm::quat gaze_quat(gaze.pose.orientation.w, gaze.pose.orientation.x, gaze.pose.orientation.y, gaze.pose.orientation.z);
glm::quat view_quat(view_pose.pose.orientation.w, view_pose.pose.orientation.x, view_pose.pose.orientation.y, view_pose.pose.orientation.z);
gaze_quat = glm::conjugate(view_quat) * gaze_quat;
using flags = from_headset::pose_flags;
tracking.device_poses.push_back(
from_headset::tracking::pose{
// Zero position and velocities
.pose = {
.orientation = {
.x = gaze_quat.x,
.y = gaze_quat.y,
.z = gaze_quat.z,
.w = gaze_quat.w,
},
},
.device = item.device,
.flags = uint8_t(gaze.flags & view_pose.flags & ~(flags::linear_velocity_valid | flags::angular_velocity_valid)),
});
case model::pico_4_pro:
case model::pico_4_enterprise: {
// Pico headsets fail to locate gaze relative to view
auto gaze = locate_space(item.device, spaces[item.device], world_space, tracking.timestamp);
auto view_pose = locate_space(item.device, view_space, world_space, tracking.timestamp);
glm::quat gaze_quat(gaze.pose.orientation.w, gaze.pose.orientation.x, gaze.pose.orientation.y, gaze.pose.orientation.z);
glm::quat view_quat(view_pose.pose.orientation.w, view_pose.pose.orientation.x, view_pose.pose.orientation.y, view_pose.pose.orientation.z);
gaze_quat = glm::conjugate(view_quat) * gaze_quat;
using flags = from_headset::tracking::flags;
tracking.device_poses.push_back(
from_headset::tracking::pose{
// Zero position and velocities
.pose = {
.orientation = {
.x = gaze_quat.x,
.y = gaze_quat.y,
.z = gaze_quat.z,
.w = gaze_quat.w,
},
},
.device = item.device,
.flags = uint8_t(gaze.flags & view_pose.flags & ~(flags::linear_velocity_valid | flags::angular_velocity_valid)),
});
}
break;
default:
tracking.device_poses.push_back(locate_space(item.device, spaces[item.device], spaces[wivrn::device_id::HEAD], tracking.timestamp));
break;
}
break;
case wivrn::device_id::FACE:
@@ -512,10 +558,11 @@ void scenes::stream::tracking()
std::visit(utils::overloaded{
[](std::monostate &) {},
[&](auto & b) {
auto packet = b.locate_spaces(at_time, world_space);
packet.timestamp = at_time;
packet.production_timestamp = tracking.production_timestamp;
body.push_back(packet);
body.push_back(from_headset::body_tracking{
.production_timestamp = tracking.production_timestamp,
.timestamp = at_time,
.poses = b.locate_spaces(at_time, world_space),
});
},
},
body_tracker);
@@ -548,18 +595,6 @@ void scenes::stream::tracking()
}
#endif
if (auto fb = std::get_if<xr::fb_body_tracker>(&body_tracker); fb and fb->should_send_skeleton())
{
try
{
network_session->send_control(fb->get_skeleton());
}
catch (std::exception & e)
{
spdlog::warn("Failed to send body skeleton: {}", e.what());
}
}
packets.resize(std::max(packets.size(), 1 + hands.size() + body.size()));
size_t packet_count = 0;
@@ -578,14 +613,12 @@ void scenes::stream::tracking()
}
for (const auto & i: body)
{
auto & packet = packets[packet_count++];
packet.clear();
std::visit(utils::overloaded{
[&](auto & p) {
wivrn_session::stream_socket_t::serialize(packet, p);
},
},
i);
if (i.poses)
{
auto & packet = packets[packet_count++];
packet.clear();
wivrn_session::stream_socket_t::serialize(packet, i);
}
}
network_session->send_stream(std::span(packets.data(), packet_count));
@@ -636,7 +669,6 @@ void scenes::stream::on_interaction_profile_changed(const XrEventDataInteraction
std::array path = {
"/user/hand/left",
"/user/hand/right",
"/user/gamepad",
};
#define DO_PROFILE(vendor, name) \
if (profile == "/interaction_profiles/" #vendor "/" #name) \
@@ -645,7 +677,7 @@ void scenes::stream::on_interaction_profile_changed(const XrEventDataInteraction
continue; \
}
for (size_t i = 0; i < path.size(); ++i)
for (size_t i = 0; i < 2; ++i)
{
try
{
@@ -673,7 +705,6 @@ void scenes::stream::on_interaction_profile_changed(const XrEventDataInteraction
DO_PROFILE(meta, touch_controller_rift_cv1)
DO_PROFILE(meta, touch_controller_quest_1_rift_s)
DO_PROFILE(meta, touch_controller_quest_2)
DO_PROFILE(yvr, touch_controller_yvr)
DO_PROFILE(samsung, odyssey_controller)
DO_PROFILE(valve, index_controller)
@@ -728,36 +759,43 @@ void scenes::stream::send_derived_pose()
{
// This may happen if the runtime does not support palm ext
// check if we have a device specific offset
if (not application::get_hmd_traits().hand_interaction_grip_surface)
switch (guess_model())
{
switch (target)
{
case device_id::LEFT_PALM:
case device_id::RIGHT_PALM: {
glm::quat q(glm::vec3(glm::radians(-60.), 0, 0));
network_session->send_control(from_headset::derived_pose{
.source = source,
.target = target,
.relation = {
.orientation = {
.x = q.x,
.y = q.y,
.z = q.z,
.w = q.w,
},
},
});
}
break;
default:
case model::oculus_quest:
case model::oculus_quest_2:
case model::meta_quest_pro:
case model::meta_quest_3:
case model::meta_quest_3s:
switch (target)
{
case device_id::LEFT_PALM:
case device_id::RIGHT_PALM: {
glm::quat q(glm::vec3(glm::radians(-60.), 0, 0));
network_session->send_control(from_headset::derived_pose{
.source = source,
.target = target,
.relation = {
.orientation = {
.x = q.x,
.y = q.y,
.z = q.z,
.w = q.w,
},
},
});
}
break;
}
default:
break;
}
default:
break;
}
}
else
{
if (auto pose = locate_space(target, target_space, source_space, now);
pose.flags & from_headset::pose_flags::position_valid and pose.flags & from_headset::pose_flags::orientation_valid)
pose.flags & from_headset::tracking::position_valid and pose.flags & from_headset::tracking::orientation_valid)
{
network_session->send_control(from_headset::derived_pose{
.source = source,
+1 -3
View File
@@ -133,9 +133,7 @@ void main()
discard;
}
// https://registry.khronos.org/OpenXR/specs/1.1/html/xrspec.html#fundamentals-colors
// alpha can't be 0 or it will zero RGB values too
out_color = vec4(mesh.emissive_factor * texture(emissive_texture, texcoord).rgb, 1.0 / 255.0);
out_color = vec4(mesh.emissive_factor * texture(emissive_texture, texcoord).rgb, 0);
#endif // HTC_WORKAROUND
}
+7 -31
View File
@@ -18,14 +18,6 @@
*/
#version 450
layout(push_constant) uniform pc
{
ivec4 rgb_rect;
ivec4 a_rect;
vec4 scale;
vec4 bias;
};
#ifdef VERT_SHADER
layout (location = 0) in vec2 vPosition;
@@ -33,6 +25,12 @@ layout (location = 1) in uvec2 vUV;
layout(location = 0) out vec4 outUV;
layout(push_constant) uniform pc
{
ivec4 rgb_rect;
ivec4 a_rect;
};
void main()
{
gl_Position = vec4(vPosition, 0.0, 1.0);
@@ -72,14 +70,7 @@ vec4 sRGB_to_linear_rgba(vec4 x)
void main()
{
if (alpha == 1)
{
// Avoid sampling between the eyes
vec2 a = inUV.zw;
float d = a.x - 0.5;
if (abs(d) *a_rect.z < 1)
a.x += (d > 0 ? 1 : -1) / float(a_rect.z);
outColor = vec4(texture(rgb[0], inUV.xy).rgb, texture(rgb[1], a).r);
}
outColor = vec4(texture(rgb[0], inUV.xy).rgb, texture(rgb[1], inUV.zw).r);
else
outColor = texture(rgb[0], inUV.xy).rgba;
@@ -87,21 +78,6 @@ void main()
{
outColor = sRGB_to_linear_rgba(outColor);
}
if (alpha == 0)
{
outColor = outColor * scale + bias;
}
else if (outColor.a < 0.02)
{
outColor = vec4(0);
}
else
{
outColor.rgb /= outColor.a;
outColor = outColor * scale + bias;
outColor.rgb *= outColor.a;
}
}
#endif
-1
View File
@@ -23,7 +23,6 @@
#define _(x) boost::locale::gettext(x)
#define _F(x) fmt::runtime(boost::locale::gettext(x))
#define _cF(c, x) fmt::runtime(boost::locale::pgettext(c, x))
#define _S(x) boost::locale::gettext(x).c_str()
#define _C(c, x) boost::locale::pgettext(c, x)
#define _cS(c, x) _C(c, x).c_str()
+8 -20
View File
@@ -18,7 +18,7 @@
*/
#include "wivrn_client.h"
#include "application.h"
#include "hardware.h"
#include "protocol_version.h"
#include "secrets.h"
#include "smp.h"
@@ -59,15 +59,6 @@ void init_stream(T & stream)
{
stream.set_receive_buffer_size(1024 * 1024 * 5);
}
auto & port(sockaddr_in & sa)
{
return sa.sin_port;
}
auto & port(sockaddr_in6 & sa)
{
return sa.sin6_port;
}
} // namespace
template <typename T>
@@ -111,7 +102,7 @@ void wivrn_session::handshake(T address, bool tcp_only, crypto::key & headset_ke
send_control(from_headset::crypto_handshake{
.protocol_version = wivrn::protocol_version,
.public_key = headset_keypair.public_key(),
.name = application::get_hmd_traits().model_name(),
.name = model_name(),
});
to_headset::crypto_handshake crypto_handshake = std::get<to_headset::crypto_handshake>(receive(10s));
@@ -129,9 +120,7 @@ void wivrn_session::handshake(T address, bool tcp_only, crypto::key & headset_ke
{
stream = decltype(stream)();
port(address) = htons(h.stream_port);
stream.connect(address);
stream.connect(address, h.stream_port);
init_stream(stream);
}
break;
@@ -182,8 +171,7 @@ void wivrn_session::handshake(T address, bool tcp_only, crypto::key & headset_ke
stream = decltype(stream)();
stream.set_aes_key_and_ivs(s.stream_key, s.stream_iv_header_to_headset, s.stream_iv_header_from_headset);
port(address) = htons(h.stream_port);
stream.connect(address);
stream.connect(address, h.stream_port);
init_stream(stream);
}
break;
@@ -221,8 +209,8 @@ void wivrn_session::handshake(T address, bool tcp_only, crypto::key & headset_ke
}
}
wivrn_session::wivrn_session(sockaddr_in6 address, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter) :
control(address), stream(-1), address(address.sin6_addr)
wivrn_session::wivrn_session(in6_addr address, int port, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter) :
control(address, port), stream(-1), address(address)
{
try
{
@@ -234,8 +222,8 @@ wivrn_session::wivrn_session(sockaddr_in6 address, bool tcp_only, crypto::key &
}
}
wivrn_session::wivrn_session(sockaddr_in address, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter) :
control(address), stream(-1), address(address.sin_addr)
wivrn_session::wivrn_session(in_addr address, int port, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter) :
control(address, port), stream(-1), address(address)
{
try
{
+2 -2
View File
@@ -55,8 +55,8 @@ private:
public:
std::variant<in_addr, in6_addr> address;
wivrn_session(sockaddr_in6 address, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter);
wivrn_session(sockaddr_in address, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter);
wivrn_session(in6_addr address, int port, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter);
wivrn_session(in_addr address, int port, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter);
wivrn_session(const wivrn_session &) = delete;
wivrn_session & operator=(const wivrn_session &) = delete;
+118 -196
View File
@@ -1,9 +1,6 @@
#include "wivrn_discover.h"
#include "application.h"
#include "mdns.h"
#include "utils/named_thread.h"
#include "utils/overloaded.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>
@@ -36,150 +33,31 @@ std::string ip_address_to_string(const in6_addr & address)
return "";
}
struct if_addr
std::string ip_address_to_string(const sockaddr * address)
{
std::string if_name;
std::variant<sockaddr_in6, sockaddr_in> addr;
};
std::string to_string(const std::variant<sockaddr_in6, sockaddr_in> & addr)
{
return std::visit(utils::overloaded{
[](const sockaddr_in6 & a) {
return ip_address_to_string(a.sin6_addr);
},
[](const sockaddr_in & a) {
return ip_address_to_string(a.sin_addr);
},
},
addr);
}
std::set<if_addr> get_if_addrs(int port)
{
struct Deleter
if (address->sa_family == AF_INET)
{
void operator()(ifaddrs * a)
{
freeifaddrs(a);
}
};
using ifaddr_ptr = std::unique_ptr<ifaddrs, Deleter>;
ifaddrs * addresses_raw;
if (getifaddrs(&addresses_raw) < 0)
{
spdlog::error("Cannot get network interfaces: {}", strerror(errno));
return {};
return ip_address_to_string(((struct sockaddr_in *)address)->sin_addr);
}
ifaddr_ptr addresses{addresses_raw};
const int required_flags = IFF_UP | IFF_MULTICAST;
const int forbidden_flags = IFF_LOOPBACK;
std::set<if_addr> result;
for (ifaddrs * i = addresses.get(); i; i = i->ifa_next)
else if (address->sa_family == AF_INET6)
{
spdlog::debug("interface {}, address {} flags 0x{:x} required 0x{:x} forbidden 0x{:x}", i->ifa_name, uintptr_t(i->ifa_addr), i->ifa_flags, required_flags, forbidden_flags);
if (i->ifa_addr == nullptr)
continue;
if ((i->ifa_flags & required_flags) != required_flags)
continue;
if ((i->ifa_flags & forbidden_flags) != 0)
continue;
if (i->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6 * saddr = (struct sockaddr_in6 *)i->ifa_addr;
static const unsigned char localhost[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
static const unsigned char localhost_mapped[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1};
if (memcmp(saddr->sin6_addr.s6_addr, localhost, 16) &&
memcmp(saddr->sin6_addr.s6_addr, localhost_mapped, 16))
{
saddr->sin6_port = htons(port);
result.insert({.if_name = i->ifa_name, .addr = *saddr});
}
}
else if (i->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in * saddr = (struct sockaddr_in *)i->ifa_addr;
if (saddr->sin_addr.s_addr != htonl(INADDR_LOOPBACK))
{
saddr->sin_port = htons(port);
result.insert({.if_name = i->ifa_name, .addr = *saddr});
}
}
else
{
spdlog::warn("unknown family {}", i->ifa_addr->sa_family);
}
return ip_address_to_string(((struct sockaddr_in6 *)address)->sin6_addr);
}
return result;
}
return "";
}
} // namespace
static std::strong_ordering operator<=>(const in_addr & a, const in_addr & b) noexcept
static bool operator==(const in_addr & a, const in_addr & b)
{
auto x = memcmp(&a, &b, sizeof(a));
if (x < 0)
return std::strong_ordering::less;
if (x > 0)
return std::strong_ordering::greater;
return std::strong_ordering::equal;
return memcmp(&a, &b, sizeof(a)) == 0;
}
static std::strong_ordering operator<=>(const in6_addr & a, const in6_addr & b) noexcept
static bool operator==(const in6_addr & a, const in6_addr & b)
{
auto x = memcmp(&a, &b, sizeof(a));
if (x < 0)
return std::strong_ordering::less;
if (x > 0)
return std::strong_ordering::greater;
return std::strong_ordering::equal;
return memcmp(&a, &b, sizeof(a)) == 0;
}
static std::strong_ordering operator<=>(const sockaddr_in & a, const sockaddr_in & b) noexcept
{
if (auto comp = a.sin_addr <=> b.sin_addr; comp != std::strong_ordering::equal)
return comp;
return a.sin_port <=> b.sin_port;
}
static std::strong_ordering operator<=>(const sockaddr_in6 & a, const sockaddr_in6 & b) noexcept
{
if (auto comp = a.sin6_addr <=> b.sin6_addr; comp != std::strong_ordering::equal)
return comp;
return a.sin6_port <=> b.sin6_port;
}
static bool operator==(const sockaddr_in & a, const sockaddr_in & b) noexcept
{
return (a <=> b) == std::strong_ordering::equal;
}
static bool operator==(const sockaddr_in6 & a, const sockaddr_in6 & b) noexcept
{
return (a <=> b) == std::strong_ordering::equal;
}
namespace
{
static std::strong_ordering operator<=>(const if_addr & a, const if_addr & b) noexcept
{
// Sort by interface name first
// We'll get eth < usb < wlan
if (auto comp = a.if_name <=> b.if_name; comp != std::strong_ordering::equal)
return comp;
return a.addr <=> b.addr;
}
[[maybe_unused]] static bool operator==(const if_addr & a, const if_addr & b) noexcept
{
return (a <=> b) == std::strong_ordering::equal;
}
} // namespace
class dnssd_cache
{
public:
@@ -190,8 +68,8 @@ public:
int port;
bool operator==(const srv &) const noexcept = default;
};
using a = sockaddr_in;
using aaaa = sockaddr_in6;
using a = in_addr;
using aaaa = in6_addr;
struct txt
{
std::string key;
@@ -205,7 +83,6 @@ private:
steady_clock::time_point timeout;
std::string name;
std::variant<ptr, srv, a, aaaa, txt> record;
std::string if_name;
bool operator==(const cache_entry & other) const noexcept
{
@@ -216,34 +93,99 @@ private:
std::vector<cache_entry> cache;
std::vector<std::tuple<steady_clock::time_point, mdns_record_type, std::string>> last_queries;
std::set<if_addr> addresses;
std::map<int, std::string> if_names; // socket fd to interface name
// pollfds[0] is used for inter-thread communication, the others are for mDNS
std::vector<pollfd> pollfds;
int itc_fd;
void open_client_sockets()
void open_client_sockets(int port = 0)
{
close_client_sockets();
for (const auto & addr: addresses)
{
int sock = std::visit(utils::overloaded{
[](sockaddr_in6 const & a) { return mdns_socket_open_ipv6(&a); },
[](sockaddr_in const & a) { return mdns_socket_open_ipv4(&a); },
},
addr.addr);
if (sock >= 0)
{
if_names.emplace(sock, addr.if_name);
std::vector<int> sockets;
spdlog::info("Local address ({}): {}", addr.if_name, to_string(addr.addr));
}
else
spdlog::warn("Failed to open socket for {} {}", addr.if_name, to_string(addr.addr));
ifaddrs * addresses;
if (getifaddrs(&addresses) < 0)
{
spdlog::error("Cannot get network interfaces: {}", strerror(errno));
return;
}
pollfds.reserve(if_names.size() + 1);
const int required_flags = IFF_UP | IFF_MULTICAST;
const int forbidden_flags = IFF_LOOPBACK;
// std::vector<std::string> interfaces_ipv4;
// std::vector<std::string> interfaces_ipv6;
for (ifaddrs * i = addresses; i; i = i->ifa_next)
{
if (i->ifa_addr == nullptr)
continue;
if ((i->ifa_flags & required_flags) != required_flags)
continue;
if ((i->ifa_flags & forbidden_flags) != 0)
continue;
if (i->ifa_addr->sa_family == AF_INET6)
{
// if (std::any_of(interfaces_ipv6.begin(), interfaces_ipv6.end(), [&](const auto & j) { return j == i->ifa_name; }))
// continue;
struct sockaddr_in6 * saddr = (struct sockaddr_in6 *)i->ifa_addr;
// Ignore link-local addresses
if (saddr->sin6_scope_id)
{
spdlog::trace("Ignoring link-local address {}", ip_address_to_string(i->ifa_addr));
continue;
}
static const unsigned char localhost[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
static const unsigned char localhost_mapped[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1};
if (memcmp(saddr->sin6_addr.s6_addr, localhost, 16) &&
memcmp(saddr->sin6_addr.s6_addr, localhost_mapped, 16))
{
saddr->sin6_port = htons(port);
int sock = mdns_socket_open_ipv6(saddr);
if (sock >= 0)
{
sockets.push_back(sock);
spdlog::info("Local IPv6 address: {}", ip_address_to_string(i->ifa_addr));
// interfaces_ipv6.push_back(i->ifa_name);
}
else
{
spdlog::info("Cannot open socket bound to {}: {}", ip_address_to_string(i->ifa_addr), strerror(errno));
}
}
}
else if (i->ifa_addr->sa_family == AF_INET)
{
// if (std::any_of(interfaces_ipv4.begin(), interfaces_ipv4.end(), [&](const auto & j) { return j == i->ifa_name; }))
// continue;
struct sockaddr_in * saddr = (struct sockaddr_in *)i->ifa_addr;
if (saddr->sin_addr.s_addr != htonl(INADDR_LOOPBACK))
{
saddr->sin_port = htons(port);
int sock = mdns_socket_open_ipv4(saddr);
if (sock >= 0)
{
sockets.push_back(sock);
spdlog::info("Local IPv4 address: {}", ip_address_to_string(i->ifa_addr));
// interfaces_ipv4.push_back(i->ifa_name);
}
else
{
spdlog::info("Cannot open socket bound to {}: {}", ip_address_to_string(i->ifa_addr), strerror(errno));
}
}
}
}
freeifaddrs(addresses);
pollfds.reserve(sockets.size() + 1);
int fds[2];
if (pipe(fds) < 0)
@@ -255,7 +197,7 @@ private:
itc_fd = fds[1];
pollfds.push_back({.fd = fds[0], .events = POLLIN});
for (auto [socket, _]: if_names)
for (int socket: sockets)
pollfds.push_back(pollfd{.fd = socket, .events = POLLIN});
}
@@ -265,7 +207,6 @@ private:
mdns_socket_close(socket.fd);
pollfds.clear();
if_names.clear();
itc_fd = -1;
}
@@ -288,13 +229,13 @@ private:
{
type = "A";
auto addr = std::get<a>(entry.record);
record = ip_address_to_string(addr.sin_addr);
record = ip_address_to_string(addr);
}
else if (std::holds_alternative<aaaa>(entry.record))
{
type = "AAAA";
auto addr = std::get<aaaa>(entry.record);
record = ip_address_to_string(addr.sin6_addr);
record = ip_address_to_string(addr);
}
else if (std::holds_alternative<txt>(entry.record))
{
@@ -333,7 +274,7 @@ private:
spdlog::info("Sending query for {}, type {}", service_name, record_type_name(record_type));
}
void update(mdns_string_t entry, std::variant<ptr, srv, a, aaaa, txt> record, int ttl, std::string if_name)
void update(mdns_string_t entry, std::variant<ptr, srv, a, aaaa, txt> record, int ttl)
{
auto now = steady_clock::now();
@@ -342,7 +283,6 @@ private:
.timeout = now + seconds(ttl),
.name = std::string(entry.str, entry.length),
.record = std::move(record),
.if_name = std::move(if_name),
};
// log_entry(e);
@@ -391,28 +331,26 @@ private:
case MDNS_RECORDTYPE_PTR: {
char namebuffer[256];
auto ptr_record = mdns_record_parse_ptr(data, size, record_offset, record_length, namebuffer, sizeof(namebuffer));
self->update(entrystr, std::string{ptr_record.str, ptr_record.length}, ttl, self->if_names[sock]);
self->update(entrystr, std::string{ptr_record.str, ptr_record.length}, ttl);
break;
}
case MDNS_RECORDTYPE_SRV: {
char namebuffer[256];
auto srv_record = mdns_record_parse_srv(data, size, record_offset, record_length, namebuffer, sizeof(namebuffer));
self->update(entrystr, srv{{srv_record.name.str, srv_record.name.length}, srv_record.port}, ttl, self->if_names[sock]);
self->update(entrystr, srv{{srv_record.name.str, srv_record.name.length}, srv_record.port}, ttl);
break;
}
case MDNS_RECORDTYPE_A: {
sockaddr_in ipv4_buffer;
self->update(entrystr, *mdns_record_parse_a(data, size, record_offset, record_length, &ipv4_buffer), ttl, self->if_names[sock]);
self->update(entrystr, mdns_record_parse_a(data, size, record_offset, record_length, &ipv4_buffer)->sin_addr, ttl);
break;
}
case MDNS_RECORDTYPE_AAAA: {
sockaddr_in6 ipv6_buffer;
mdns_record_parse_aaaa(data, size, record_offset, record_length, &ipv6_buffer);
ipv6_buffer.sin6_scope_id = ((sockaddr_in6 *)from)->sin6_scope_id;
self->update(entrystr, ipv6_buffer, ttl, self->if_names[sock]);
self->update(entrystr, mdns_record_parse_aaaa(data, size, record_offset, record_length, &ipv6_buffer)->sin6_addr, ttl);
break;
}
@@ -424,7 +362,7 @@ private:
{
std::string key{txt_buffer[i].key.str, txt_buffer[i].key.length};
std::string value{txt_buffer[i].value.str, txt_buffer[i].value.length};
self->update(entrystr, txt{key, value}, ttl, self->if_names[sock]);
self->update(entrystr, txt{key, value}, ttl);
}
break;
}
@@ -453,12 +391,6 @@ public:
}
}
if (auto addr = get_if_addrs(5353); addr != addresses)
{
std::swap(addr, addresses);
open_client_sockets();
}
log_query(record, service_name);
std::array<uint8_t, 2048> buffer;
for (size_t i = 1; i < pollfds.size(); i++)
@@ -502,9 +434,9 @@ public:
}
template <typename T>
std::vector<std::tuple<T, std::string, steady_clock::time_point>> read(const std::string & name)
std::vector<std::pair<T, steady_clock::time_point>> read(const std::string & name)
{
std::vector<std::tuple<T, std::string, steady_clock::time_point>> entries;
std::vector<std::pair<T, steady_clock::time_point>> entries;
auto now = steady_clock::now();
std::erase_if(cache, [now](const cache_entry & i) {
@@ -514,7 +446,7 @@ public:
for (const auto & i: cache)
{
if (i.name == name && std::holds_alternative<T>(i.record))
entries.emplace_back(std::get<T>(i.record), i.if_name, i.timeout);
entries.emplace_back(std::get<T>(i.record), i.timeout);
}
return entries;
@@ -522,8 +454,7 @@ public:
dnssd_cache()
{
addresses = get_if_addrs(5353);
open_client_sockets();
open_client_sockets(5353);
}
dnssd_cache(const dnssd_cache &) = delete;
@@ -558,7 +489,7 @@ void wivrn_discover::discover(std::string service_name)
}
poll_timeout = std::min(poll_timeout, duration_cast<milliseconds>(next_query - now));
for (auto [ptr, _, ttl]: cache->read<dnssd_cache::ptr>(service_name))
for (auto [ptr, ttl]: cache->read<dnssd_cache::ptr>(service_name))
{
bool srv_found = false;
auto srv_min_ttl = milliseconds::max();
@@ -570,9 +501,7 @@ void wivrn_discover::discover(std::string service_name)
else
s.name = ptr;
std::multimap<std::string, decltype(service::address::address)> addr_by_if_name;
for (auto [srv, _, ttl]: cache->read<dnssd_cache::srv>(ptr))
for (auto [srv, ttl]: cache->read<dnssd_cache::srv>(ptr))
{
srv_found = true;
srv_min_ttl = std::min(duration_cast<milliseconds>(ttl - now), srv_min_ttl);
@@ -590,26 +519,21 @@ void wivrn_discover::discover(std::string service_name)
bool address_found = false;
auto address_min_ttl = milliseconds::max();
for (auto [a, if_name, ttl]: cache->read<dnssd_cache::a>(srv.hostname))
for (auto [a, ttl]: cache->read<dnssd_cache::a>(srv.hostname))
{
address_found = true;
address_min_ttl = std::min(duration_cast<milliseconds>(ttl - now), address_min_ttl);
a.sin_port = htons(srv.port);
addr_by_if_name.emplace(if_name, a);
s.addresses.push_back(a);
}
for (auto [aaaa, if_name, ttl]: cache->read<dnssd_cache::aaaa>(srv.hostname))
for (auto [aaaa, ttl]: cache->read<dnssd_cache::aaaa>(srv.hostname))
{
address_found = true;
address_min_ttl = std::min(duration_cast<milliseconds>(ttl - now), address_min_ttl);
aaaa.sin6_port = htons(srv.port);
addr_by_if_name.emplace(if_name, aaaa);
s.addresses.push_back(aaaa);
}
for (auto && [if_name, addr]: addr_by_if_name)
s.addresses.push_back({.interface = std::move(if_name), .address = addr});
for (auto [txt_record, _, ttl]: cache->read<dnssd_cache::txt>(ptr))
for (auto [txt_record, ttl]: cache->read<dnssd_cache::txt>(ptr))
{
s.txt[txt_record.key] = txt_record.value;
}
@@ -643,9 +567,7 @@ void wivrn_discover::discover(std::string service_name)
}
wivrn_discover::wivrn_discover(std::string service_name) :
multicast{application::get_wifi_lock().get_multicast_lock()},
cache(std::make_unique<dnssd_cache>()),
dnssd_thread(utils::named_thread("dnssd_thread", &wivrn_discover::discover, this, service_name))
cache(std::make_unique<dnssd_cache>()), dnssd_thread(utils::named_thread("dnssd_thread", &wivrn_discover::discover, this, service_name))
{
}
+1 -10
View File
@@ -1,11 +1,8 @@
#pragma once
#include "wifi_lock.h"
#include <chrono>
#include <map>
#include <memory>
#include <mutex>
#include <netinet/in.h>
#include <string>
#include <thread>
@@ -19,17 +16,12 @@ class wivrn_discover
public:
struct service
{
struct address
{
std::string interface;
std::variant<sockaddr_in, sockaddr_in6> address;
};
std::string name;
std::string hostname;
int port;
bool tcp_only = false;
std::vector<address> addresses;
std::vector<std::variant<in_addr, in6_addr>> addresses;
std::map<std::string, std::string> txt;
std::chrono::steady_clock::time_point ttl;
std::string pin;
@@ -40,7 +32,6 @@ public:
static inline const std::chrono::milliseconds discover_period{5000};
private:
wifi_lock::multicast multicast;
std::unique_ptr<dnssd_cache> cache;
std::thread dnssd_thread;
+24 -25
View File
@@ -18,19 +18,18 @@
#include "body_tracker.h"
#include "xr/fb_body_tracker.h"
#include "xr/htc_exts.h"
#include "xr/instance.h"
#include "xr/system.h"
#include <openxr/openxr.h>
xr::body_tracker_type xr::body_tracker_supported(xr::instance & instance, xr::system & system)
{
if (instance.has_extension(XR_FB_BODY_TRACKING_EXTENSION_NAME))
if (instance.has_extension(XR_FB_BODY_TRACKING_EXTENSION_NAME) and
instance.has_extension(XR_META_BODY_TRACKING_FULL_BODY_EXTENSION_NAME) and
instance.has_extension(XR_META_BODY_TRACKING_FIDELITY_EXTENSION_NAME))
{
if (instance.has_extension(XR_META_BODY_TRACKING_FULL_BODY_EXTENSION_NAME) and system.meta_body_tracking_properties().supportsFullBodyTracking)
return body_tracker_type::meta;
if (system.fb_body_tracking_properties().supportsBodyTracking)
auto fb_body_properties = system.fb_body_tracking_properties();
if (fb_body_properties.supportsBodyTracking)
return body_tracker_type::fb;
}
@@ -48,33 +47,33 @@ xr::body_tracker_type xr::body_tracker_supported(xr::instance & instance, xr::sy
return xr::body_tracker_type::none;
}
xr::body_tracker xr::make_body_tracker(xr::instance & instance, xr::system & system, xr::session & session, std::vector<std::pair<XrPath, xr::space>> & generic_trackers)
xr::body_tracker xr::make_body_tracker(xr::instance & instance, xr::system & system, xr::session & session, std::vector<std::pair<XrPath, xr::space>> & generic_trackers, bool full_body, bool hips)
{
switch (body_tracker_supported(instance, system))
if (instance.has_extension(XR_FB_BODY_TRACKING_EXTENSION_NAME) and
instance.has_extension(XR_META_BODY_TRACKING_FULL_BODY_EXTENSION_NAME) and
instance.has_extension(XR_META_BODY_TRACKING_FIDELITY_EXTENSION_NAME))
{
case body_tracker_type::meta:
auto fb_body_properties = system.fb_body_tracking_properties();
if (fb_body_properties.supportsBodyTracking)
return xr::body_tracker(std::in_place_type_t<xr::fb_body_tracker>(),
instance,
session,
true);
case body_tracker_type::fb:
return xr::body_tracker(std::in_place_type_t<xr::fb_body_tracker>(),
instance,
session,
false);
case body_tracker_type::pico:
full_body,
hips);
}
if (not generic_trackers.empty())
return xr::body_tracker(std::in_place_type_t<xr::htc_body_tracker>(),
session,
generic_trackers);
if (instance.has_extension(XR_BD_BODY_TRACKING_EXTENSION_NAME))
{
auto bd_body_properties = system.bd_body_tracking_properties();
if (bd_body_properties.supportsBodyTracking)
return xr::body_tracker(std::in_place_type_t<xr::pico_body_tracker>(),
instance,
session);
case body_tracker_type::htc:
if (not generic_trackers.empty())
return xr::body_tracker(std::in_place_type_t<xr::htc_body_tracker>(),
session,
generic_trackers);
break;
default:
break;
}
return std::monostate();
+1 -1
View File
@@ -36,7 +36,7 @@ class session;
using body_tracker = std::variant<std::monostate, xr::fb_body_tracker, xr::htc_body_tracker, xr::pico_body_tracker>;
body_tracker make_body_tracker(xr::instance &, xr::system &, xr::session &, std::vector<std::pair<XrPath, xr::space>> & generic_trackers);
body_tracker make_body_tracker(xr::instance &, xr::system &, xr::session &, std::vector<std::pair<XrPath, xr::space>> & generic_trackers, bool full_body, bool hips);
body_tracker_type body_tracker_supported(xr::instance &, xr::system &);
+23 -13
View File
@@ -18,7 +18,7 @@
#include "face_tracker.h"
#include "application.h"
#include "hardware.h"
#include "xr/instance.h"
#include "xr/system.h"
@@ -45,13 +45,18 @@ xr::face_tracker_type xr::face_tracker_supported(xr::instance & instance, xr::sy
return xr::face_tracker_type::htc;
}
if (application::get_hmd_traits().pico_face_tracker)
switch (guess_model())
{
// The extension used by Pico is not published
// it doesn't even need to be requested...
if (instance.has_extension(XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME) and
system.eye_gaze_interaction_properties().supportsEyeGazeInteraction)
return xr::face_tracker_type::pico;
case model::pico_4_pro:
case model::pico_4_enterprise:
// The extension used by Pico is not published
// it doesn't even need to be requested...
if (instance.has_extension(XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME) and
system.eye_gaze_interaction_properties().supportsEyeGazeInteraction)
return xr::face_tracker_type::pico;
break;
default:
break;
}
return xr::face_tracker_type::none;
@@ -85,13 +90,18 @@ xr::face_tracker xr::make_face_tracker(xr::instance & instance, xr::system & sys
properties.supportLipFacialTracking);
}
if (application::get_hmd_traits().pico_face_tracker)
switch (guess_model())
{
// The extension used by Pico is not published
// it doesn't even need to be requested...
if (instance.has_extension(XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME) and
system.eye_gaze_interaction_properties().supportsEyeGazeInteraction)
return xr::face_tracker(std::in_place_type_t<xr::pico_face_tracker>(), instance, session);
case model::pico_4_pro:
case model::pico_4_enterprise:
// The extension used by Pico is not published
// it doesn't even need to be requested...
if (instance.has_extension(XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME) and
system.eye_gaze_interaction_properties().supportsEyeGazeInteraction)
return xr::face_tracker(std::in_place_type_t<xr::pico_face_tracker>(), instance, session);
break;
default:
break;
}
return std::monostate();
+56 -81
View File
@@ -18,41 +18,56 @@
#include "fb_body_tracker.h"
#include "spdlog/spdlog.h"
#include "utils/overloaded.h"
#include "wivrn_packets.h"
#include "xr/instance.h"
#include "xr/meta_body_tracking_fidelity.h"
#include "xr/session.h"
#include "xr/to_string.h"
#include <stdexcept>
#include <variant>
#include <ranges>
#include <openxr/openxr.h>
xr::fb_body_tracker::fb_body_tracker(instance & inst, session & s, bool full_body) :
static_assert(xr::fb_body_tracker::joint_whitelist.size() <= wivrn::from_headset::body_tracking::max_tracked_poses);
std::vector<XrFullBodyJointMETA> xr::fb_body_tracker::get_whitelisted_joints(bool full_body, bool hip)
{
auto whitelisted_joints = std::ranges::filter_view(xr::fb_body_tracker::joint_whitelist, [=](auto joint) {
if (!full_body && (joint == XR_FULL_BODY_JOINT_HIPS_META || joint >= XR_FULL_BODY_JOINT_LEFT_UPPER_LEG_META))
return false;
if (!hip && joint == XR_FULL_BODY_JOINT_HIPS_META)
return false;
return true;
});
return {whitelisted_joints.begin(), whitelisted_joints.end()};
}
xr::fb_body_tracker::fb_body_tracker(instance & inst, session & s, bool full_body, bool hip) :
handle(inst.get_proc<PFN_xrDestroyBodyTrackerFB>("xrDestroyBodyTrackerFB")),
xrRequestBodyTrackingFidelityMETA(inst.has_extension(XR_META_BODY_TRACKING_FIDELITY_EXTENSION_NAME)
? inst.get_proc<PFN_xrRequestBodyTrackingFidelityMETA>("xrRequestBodyTrackingFidelityMETA")
: nullptr),
xrRequestBodyTrackingFidelityMETA(inst.get_proc<PFN_xrRequestBodyTrackingFidelityMETA>("xrRequestBodyTrackingFidelityMETA")),
xrLocateBodyJointsFB(inst.get_proc<PFN_xrLocateBodyJointsFB>("xrLocateBodyJointsFB")),
xrGetBodySkeletonFB(inst.get_proc<PFN_xrGetBodySkeletonFB>("xrGetBodySkeletonFB")),
joint_set(full_body ? XR_BODY_JOINT_SET_FULL_BODY_META : XR_BODY_JOINT_SET_DEFAULT_FB)
full_body(full_body),
hip(hip)
{
auto xrCreateBodyTrackerFB = inst.get_proc<PFN_xrCreateBodyTrackerFB>("xrCreateBodyTrackerFB");
XrBodyTrackerCreateInfoFB create_info{
.type = XR_TYPE_BODY_TRACKER_CREATE_INFO_FB,
.bodyJointSet = joint_set,
.bodyJointSet = full_body
? XR_BODY_JOINT_SET_FULL_BODY_META
: XR_BODY_JOINT_SET_DEFAULT_FB,
};
CHECK_XR(xrCreateBodyTrackerFB(s, &create_info, &id));
// Enable IOBT.
if (xrRequestBodyTrackingFidelityMETA)
xrRequestBodyTrackingFidelityMETA(id, XR_BODY_TRACKING_FIDELITY_HIGH_META);
CHECK_XR(xrRequestBodyTrackingFidelityMETA(id, XR_BODY_TRACKING_FIDELITY_HIGH_META));
whitelisted_joints = get_whitelisted_joints(full_body, hip);
}
xr::fb_body_tracker::packet_type xr::fb_body_tracker::locate_spaces(XrTime time, XrSpace reference)
std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses>> xr::fb_body_tracker::locate_spaces(XrTime time, XrSpace reference)
{
xr::fb_body_tracker::packet_type ret{};
if (!id)
return std::nullopt;
assert(xrLocateBodyJointsFB);
@@ -67,84 +82,44 @@ xr::fb_body_tracker::packet_type xr::fb_body_tracker::locate_spaces(XrTime time,
XrBodyJointLocationsFB joint_locations{
.type = XR_TYPE_BODY_JOINT_LOCATIONS_FB,
.next = nullptr,
.jointCount = (uint32_t)(joint_set == XR_BODY_JOINT_SET_FULL_BODY_META
? std::to_underlying(XR_FULL_BODY_JOINT_COUNT_META)
: std::to_underlying(XR_BODY_JOINT_COUNT_FB)),
.jointCount = (uint32_t)(full_body ? XR_FULL_BODY_JOINT_COUNT_META : (XrFullBodyJointMETA)XR_BODY_JOINT_COUNT_FB),
.jointLocations = joints.data(),
};
if (auto res = xrLocateBodyJointsFB(id, &locate_info, &joint_locations); !XR_SUCCEEDED(res))
{
spdlog::warn("xrLocateBodyJointsFB returned {}", xr::to_string(res));
return ret;
return std::nullopt;
}
if (!joint_locations.isActive)
{
return ret;
spdlog::warn("Body tracker is not active.");
return std::nullopt;
}
skeleton_generation = joint_locations.skeletonChangedCount;
ret.confidence = joint_locations.confidence;
const auto & root = joints[XR_BODY_JOINT_ROOT_FB];
if (joint_set == XR_BODY_JOINT_SET_FULL_BODY_META)
ret.joints.emplace<wivrn::from_headset::meta_body::meta_joints>();
else
ret.joints.emplace<wivrn::from_headset::meta_body::fb_joints>();
std::visit(utils::overloaded{
[](std::monostate) {},
[&root, &joints](auto & o) {
o.root = {
.position = root.pose.position,
.orientation = pack(root.pose.orientation),
.flags = wivrn::from_headset::to_pose_flags(root.locationFlags),
};
for (size_t joint = XR_BODY_JOINT_HIPS_FB; joint < std::size(o.joints) + 1; joint++)
{
const auto & loc = joints[joint];
o.joints[joint - 1] = {
.position = {
.x = int16_t((loc.pose.position.x - root.pose.position.x) * 10'000.f),
.y = int16_t((loc.pose.position.y - root.pose.position.y) * 10'000.f),
.z = int16_t((loc.pose.position.z - root.pose.position.z) * 10'000.f)},
.orientation = pack(loc.pose.orientation),
.flags = wivrn::from_headset::to_pose_flags(loc.locationFlags),
};
}
},
},
ret.joints);
return ret;
}
bool xr::fb_body_tracker::should_send_skeleton()
{
return last_sent_skeleton_generation != skeleton_generation;
}
wivrn::from_headset::meta_body_skeleton xr::fb_body_tracker::get_skeleton()
{
wivrn::from_headset::meta_body_skeleton ret{};
if (joint_set == XR_BODY_JOINT_SET_FULL_BODY_META)
ret.skeleton.emplace<wivrn::from_headset::meta_body_skeleton::meta_skeleton>();
else
ret.skeleton.emplace<wivrn::from_headset::meta_body_skeleton::fb_skeleton>();
XrBodySkeletonFB skeleton{
.type = XR_TYPE_BODY_SKELETON_FB,
};
std::visit(utils::overloaded{
[&skeleton](auto & s) {
skeleton.joints = s.joints.data();
skeleton.jointCount = s.joints.size();
}},
ret.skeleton);
if (auto res = xrGetBodySkeletonFB(id, &skeleton); !XR_SUCCEEDED(res))
std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses> poses{};
int num_poses = 0;
for (auto joint: whitelisted_joints)
{
throw std::runtime_error(std::format("xrGetBodySkeletonFB returned {}", xr::to_string(res)));
}
const auto & joint_loc = joints[joint];
wivrn::from_headset::body_tracking::pose pose{
.pose = joint_loc.pose,
.flags = 0,
};
last_sent_skeleton_generation = skeleton_generation;
return ret;
if (joint_loc.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
{
pose.flags |= wivrn::from_headset::body_tracking::orientation_valid;
pose.flags |= wivrn::from_headset::body_tracking::orientation_tracked;
}
if (joint_loc.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT)
{
pose.flags |= wivrn::from_headset::body_tracking::position_valid;
pose.flags |= wivrn::from_headset::body_tracking::position_tracked;
}
poses[num_poses++] = pose;
}
return poses;
}
+21 -9
View File
@@ -21,6 +21,9 @@
#include "wivrn_packets.h"
#include "utils/handle.h"
#include "xr/meta_body_tracking_fidelity.h"
#include <array>
#include <optional>
#include <openxr/openxr.h>
namespace xr
@@ -32,19 +35,28 @@ class fb_body_tracker : public utils::handle<XrBodyTrackerFB>
{
PFN_xrRequestBodyTrackingFidelityMETA xrRequestBodyTrackingFidelityMETA{};
PFN_xrLocateBodyJointsFB xrLocateBodyJointsFB{};
PFN_xrGetBodySkeletonFB xrGetBodySkeletonFB{};
XrBodyJointSetFB joint_set{};
uint32_t last_sent_skeleton_generation = static_cast<uint32_t>(-1);
uint32_t skeleton_generation = 0;
bool full_body{};
bool hip{};
std::vector<XrFullBodyJointMETA> whitelisted_joints{};
public:
using packet_type = wivrn::from_headset::meta_body;
static constexpr std::array joint_whitelist{
XR_FULL_BODY_JOINT_HIPS_META,
XR_FULL_BODY_JOINT_CHEST_META,
XR_FULL_BODY_JOINT_LEFT_ARM_LOWER_META,
XR_FULL_BODY_JOINT_RIGHT_ARM_LOWER_META,
fb_body_tracker(instance & inst, session & s, bool full_body);
XR_FULL_BODY_JOINT_LEFT_LOWER_LEG_META,
XR_FULL_BODY_JOINT_RIGHT_LOWER_LEG_META,
packet_type locate_spaces(XrTime time, XrSpace reference);
bool should_send_skeleton();
wivrn::from_headset::meta_body_skeleton get_skeleton() noexcept(false);
XR_FULL_BODY_JOINT_LEFT_FOOT_TRANSVERSE_META,
XR_FULL_BODY_JOINT_RIGHT_FOOT_TRANSVERSE_META,
};
static std::vector<XrFullBodyJointMETA> get_whitelisted_joints(bool full_body, bool hip);
fb_body_tracker(instance & inst, session & s, bool full_body, bool hip);
std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses>> locate_spaces(XrTime time, XrSpace reference);
};
} // namespace xr
-120
View File
@@ -21,10 +21,7 @@
#include "xr/check.h"
#include "xr/instance.h"
#include "xr/session.h"
#include "xr/to_string.h"
#include <algorithm>
#include <cassert>
#include <spdlog/spdlog.h>
xr::hand_tracker::hand_tracker(instance & inst, session & session, const XrHandTrackerCreateInfoEXT & info) :
handle(inst.get_proc<PFN_xrDestroyHandTrackerEXT>("xrDestroyHandTrackerEXT"))
@@ -32,8 +29,6 @@ xr::hand_tracker::hand_tracker(instance & inst, session & session, const XrHandT
auto xrCreateHandTrackerEXT = inst.get_proc<PFN_xrCreateHandTrackerEXT>("xrCreateHandTrackerEXT");
assert(xrCreateHandTrackerEXT);
xrLocateHandJointsEXT = inst.get_proc<PFN_xrLocateHandJointsEXT>("xrLocateHandJointsEXT");
if (inst.has_extension(XR_FB_HAND_TRACKING_MESH_EXTENSION_NAME))
xrGetHandMeshFB = inst.get_proc<PFN_xrGetHandMeshFB>("xrGetHandMeshFB");
CHECK_XR(xrCreateHandTrackerEXT(session, &info, &id));
}
@@ -92,121 +87,6 @@ std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> xr::
return joints;
}
const xr::hand_tracker::mesh_data * xr::hand_tracker::mesh()
{
if (hand_mesh_fb_fetched)
return cached_hand_mesh_fb ? &*cached_hand_mesh_fb : nullptr;
hand_mesh_fb_fetched = true;
if (!id || !xrGetHandMeshFB)
return nullptr;
XrHandTrackingMeshFB mesh{
.type = XR_TYPE_HAND_TRACKING_MESH_FB,
};
XrResult result = xrGetHandMeshFB(id, &mesh);
if (XR_FAILED(result))
{
spdlog::warn("xrGetHandMeshFB count query failed: {}", xr::to_string(result));
return nullptr;
}
if (mesh.jointCountOutput != XR_HAND_JOINT_COUNT_EXT)
{
spdlog::warn("Unsupported hand mesh joint count {}", mesh.jointCountOutput);
return nullptr;
}
if (mesh.jointCountOutput > 32)
{
spdlog::warn("Hand mesh joint count {} exceeds renderer limit", mesh.jointCountOutput);
return nullptr;
}
if (mesh.vertexCountOutput == 0 || mesh.indexCountOutput == 0)
{
spdlog::warn("Hand mesh data is empty");
return nullptr;
}
mesh_data data;
data.joint_bind_poses.resize(mesh.jointCountOutput);
data.joint_radii.resize(mesh.jointCountOutput);
data.joint_parents.resize(mesh.jointCountOutput);
data.vertex_positions.resize(mesh.vertexCountOutput);
data.vertex_normals.resize(mesh.vertexCountOutput);
data.vertex_uvs.resize(mesh.vertexCountOutput);
data.vertex_blend_indices.resize(mesh.vertexCountOutput);
data.vertex_blend_weights.resize(mesh.vertexCountOutput);
data.indices.resize(mesh.indexCountOutput);
mesh.jointCapacityInput = data.joint_bind_poses.size();
mesh.jointBindPoses = data.joint_bind_poses.data();
mesh.jointRadii = data.joint_radii.data();
mesh.jointParents = data.joint_parents.data();
mesh.vertexCapacityInput = data.vertex_positions.size();
mesh.vertexPositions = data.vertex_positions.data();
mesh.vertexNormals = data.vertex_normals.data();
mesh.vertexUVs = data.vertex_uvs.data();
mesh.vertexBlendIndices = data.vertex_blend_indices.data();
mesh.vertexBlendWeights = data.vertex_blend_weights.data();
mesh.indexCapacityInput = data.indices.size();
mesh.indices = data.indices.data();
result = xrGetHandMeshFB(id, &mesh);
if (XR_FAILED(result))
{
spdlog::warn("xrGetHandMeshFB data query failed: {}", xr::to_string(result));
return nullptr;
}
auto count_changed = [](const char * what, uint32_t output, size_t expected) {
if (output == expected)
return false;
spdlog::warn("Hand mesh {} count changed from {} to {}", what, expected, output);
return true;
};
if (count_changed("joint", mesh.jointCountOutput, data.joint_bind_poses.size()) ||
count_changed("vertex", mesh.vertexCountOutput, data.vertex_positions.size()) ||
count_changed("index", mesh.indexCountOutput, data.indices.size()))
{
return nullptr;
}
if (mesh.indexCountOutput % 3 != 0)
{
spdlog::warn("Hand mesh index count {} is not a triangle list", mesh.indexCountOutput);
return nullptr;
}
const int joint_count = static_cast<int>(mesh.jointCountOutput);
if (!std::ranges::all_of(data.vertex_blend_indices, [joint_count](const XrVector4sFB & blend_indices) {
return 0 <= blend_indices.x && blend_indices.x < joint_count &&
0 <= blend_indices.y && blend_indices.y < joint_count &&
0 <= blend_indices.z && blend_indices.z < joint_count &&
0 <= blend_indices.w && blend_indices.w < joint_count;
}))
{
spdlog::warn("Hand mesh has out-of-range blend indices");
return nullptr;
}
const int vertex_count = static_cast<int>(mesh.vertexCountOutput);
if (!std::ranges::all_of(data.indices, [vertex_count](int16_t index) {
return 0 <= index && index < vertex_count;
}))
{
spdlog::warn("Hand mesh has out-of-range indices");
return nullptr;
}
cached_hand_mesh_fb = std::move(data);
return &*cached_hand_mesh_fb;
}
bool xr::hand_tracker::check_flags(const std::array<joint, XR_HAND_JOINT_COUNT_EXT> & joints, XrSpaceLocationFlags position, XrSpaceVelocityFlags velocity)
{
return std::ranges::all_of(joints, [position, velocity](const auto & joint) {
+2 -22
View File
@@ -22,7 +22,6 @@
#include "utils/handle.h"
#include <array>
#include <optional>
#include <vector>
#include <openxr/openxr.h>
namespace xr
@@ -32,33 +31,14 @@ class session;
class hand_tracker : public utils::handle<XrHandTrackerEXT>
{
public:
using joint = std::pair<XrHandJointLocationEXT, XrHandJointVelocityEXT>;
struct mesh_data
{
std::vector<XrPosef> joint_bind_poses;
std::vector<float> joint_radii;
std::vector<XrHandJointEXT> joint_parents;
std::vector<XrVector3f> vertex_positions;
std::vector<XrVector3f> vertex_normals;
std::vector<XrVector2f> vertex_uvs;
std::vector<XrVector4sFB> vertex_blend_indices;
std::vector<XrVector4f> vertex_blend_weights;
std::vector<int16_t> indices;
};
private:
PFN_xrLocateHandJointsEXT xrLocateHandJointsEXT{};
PFN_xrGetHandMeshFB xrGetHandMeshFB{};
std::optional<mesh_data> cached_hand_mesh_fb;
bool hand_mesh_fb_fetched = false;
public:
hand_tracker(instance & inst, session & session, const XrHandTrackerCreateInfoEXT & info);
using joint = std::pair<XrHandJointLocationEXT, XrHandJointVelocityEXT>;
std::optional<std::array<joint, XR_HAND_JOINT_COUNT_EXT>> locate(XrSpace space, XrTime time);
const mesh_data * mesh();
static bool check_flags(const std::array<joint, XR_HAND_JOINT_COUNT_EXT> & joints, XrSpaceLocationFlags position, XrSpaceVelocityFlags velocity);
};
+25 -18
View File
@@ -19,10 +19,8 @@
*/
#include "htc_body_tracker.h"
#include "wivrn_packets.h"
#include "xr/details/enumerate.h"
#include "xr/session.h"
#include "xr/to_string.h"
#include <openxr/openxr.h>
// Note: This utilizes extensions not present in the OpenXR spec!
@@ -59,7 +57,7 @@ XrSpace xr::vive_xr_tracker::get_space() const
return space;
}
static wivrn::from_headset::htc_body::pose locate_space(XrSpace space, XrSpace reference, XrTime time)
static wivrn::from_headset::body_tracking::pose locate_space(XrSpace space, XrSpace reference, XrTime time)
{
XrSpaceVelocity velocity{
.type = XR_TYPE_SPACE_VELOCITY,
@@ -70,19 +68,25 @@ static wivrn::from_headset::htc_body::pose locate_space(XrSpace space, XrSpace r
.next = &velocity,
};
if (auto res = xrLocateSpace(space, reference, time, &location); !XR_SUCCEEDED(res))
{
spdlog::warn("xrLocateSpace failed for HTC body tracker: {}", xr::to_string(res));
return {};
}
xrLocateSpace(space, reference, time, &location);
wivrn::from_headset::htc_body::pose res{
wivrn::from_headset::body_tracking::pose res{
.pose = location.pose,
.linear_velocity = velocity.linearVelocity,
.angular_velocity = velocity.angularVelocity,
.flags = wivrn::from_headset::to_pose_flags(location.locationFlags, velocity.velocityFlags),
.flags = 0,
};
if (location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
res.flags |= wivrn::from_headset::body_tracking::orientation_valid;
if (location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT)
res.flags |= wivrn::from_headset::body_tracking::position_valid;
if (location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)
res.flags |= wivrn::from_headset::body_tracking::orientation_tracked;
if (location.locationFlags & XR_SPACE_LOCATION_POSITION_TRACKED_BIT)
res.flags |= wivrn::from_headset::body_tracking::position_tracked;
return res;
}
@@ -100,19 +104,22 @@ void xr::htc_body_tracker::update_active()
tracker.update_active(s);
}
xr::htc_body_tracker::packet_type xr::htc_body_tracker::locate_spaces(XrTime time, XrSpace reference)
std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses> xr::htc_body_tracker::locate_spaces(XrTime time, XrSpace reference)
{
xr::htc_body_tracker::packet_type ret{};
std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses> poses{};
for (size_t i = 0; i < trackers.size(); i++)
for (int i = 0; i < trackers.size(); i++)
{
auto & tracker = trackers[i];
wivrn::from_headset::htc_body::pose pose{};
wivrn::from_headset::body_tracking::pose pose{
.pose = {},
.flags = 0,
};
if (tracker.get_active())
pose = locate_space(tracker.get_space(), reference, time);
ret.poses[i] = pose;
poses[i] = pose;
}
return ret;
return poses;
}
+1 -2
View File
@@ -49,10 +49,9 @@ class htc_body_tracker
std::vector<vive_xr_tracker> trackers;
public:
using packet_type = wivrn::from_headset::htc_body;
htc_body_tracker(session & s, std::vector<std::pair<XrPath, xr::space>> & trackers);
void update_active();
packet_type locate_spaces(XrTime time, XrSpace reference);
std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses> locate_spaces(XrTime time, XrSpace reference);
};
} // namespace xr
+14 -11
View File
@@ -19,7 +19,7 @@
#include "instance.h"
#include "application.h"
#include "hardware.h"
#include "xr/details/enumerate.h"
#include "xr/htc_exts.h"
#include "xr/to_string.h"
@@ -94,18 +94,24 @@ const std::map<XrVersion, version_info> version_info::versions = {{
static std::pair<XrVersion, XrInstance> create_instance(XrInstanceCreateInfo & info, std::vector<const char *> & in_extensions)
{
XrResult res = XR_ERROR_API_VERSION_UNSUPPORTED;
XrResult res;
for (XrVersion version: {
XR_API_VERSION_1_1,
XR_API_VERSION_1_0,
})
{
if (version > application::get_hmd_traits().max_openxr_api_version)
switch (guess_model())
{
spdlog::info("skip OpenXR {} due to headset quirk max version {}",
xr::to_string(version),
xr::to_string(application::get_hmd_traits().max_openxr_api_version));
continue;
case model::htc_vive_focus_3:
case model::htc_vive_xr_elite:
case model::htc_vive_focus_vision:
if (version > XR_API_VERSION_1_0)
{
spdlog::info("skip OpenXR 1.1 for HTC");
continue;
}
default:
break;
}
std::vector<const char *> extensions;
info.applicationInfo.apiVersion = version;
@@ -199,10 +205,7 @@ xr::instance::instance(std::string_view application_name, std::vector<const char
std::ranges::sort(all_extensions, [](const char * a, const char * b) { return strcmp(a, b) < 0; }, &XrExtensionProperties::extensionName);
for (XrExtensionProperties & i: all_extensions)
{
if (application::get_hmd_traits().blacklisted_extensions.contains(i.extensionName))
spdlog::info(" {} (version {}) (blacklisted)", i.extensionName, i.extensionVersion);
else
spdlog::info(" {} (version {})", i.extensionName, i.extensionVersion);
spdlog::info(" {} (version {})", i.extensionName, i.extensionVersion);
#ifndef NDEBUG
if (!strcmp(i.extensionName, "XR_EXT_debug_utils"))
{
+24 -14
View File
@@ -18,12 +18,13 @@
#include "pico_body_tracker.h"
#include "spdlog/spdlog.h"
#include "wivrn_packets.h"
#include "xr/instance.h"
#include "xr/session.h"
#include "xr/to_string.h"
#include <openxr/openxr.h>
static_assert(xr::pico_body_tracker::joint_whitelist.size() <= wivrn::from_headset::body_tracking::max_tracked_poses);
xr::pico_body_tracker::pico_body_tracker(instance & inst, session & s) :
handle(inst.get_proc<PFN_xrDestroyBodyTrackerBD>("xrDestroyBodyTrackerBD"))
{
@@ -40,11 +41,10 @@ xr::pico_body_tracker::pico_body_tracker(instance & inst, session & s) :
CHECK_XR(xrCreateBodyTrackerBD(s, &create_info, &id));
}
xr::pico_body_tracker::packet_type xr::pico_body_tracker::locate_spaces(XrTime time, XrSpace reference)
std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses>> xr::pico_body_tracker::locate_spaces(XrTime time, XrSpace reference)
{
xr::pico_body_tracker::packet_type ret{};
if (!xrLocateBodyJointsBD)
return ret;
return std::nullopt;
XrBodyJointsLocateInfoBD locate_info{
.type = XR_TYPE_BODY_JOINTS_LOCATE_INFO_BD,
@@ -64,19 +64,29 @@ xr::pico_body_tracker::packet_type xr::pico_body_tracker::locate_spaces(XrTime t
if (auto res = xrLocateBodyJointsBD(id, &locate_info, &joint_locations); !XR_SUCCEEDED(res))
{
spdlog::warn("Unable to get body joints: xrLocateBodyJointsBD returned {}", xr::to_string(res));
return ret;
return std::nullopt;
}
ret.all_tracked = joint_locations.allJointPosesTracked;
for (size_t joint = XR_BODY_JOINT_PELVIS_BD; joint < XR_BODY_JOINT_COUNT_BD; joint++)
std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses> poses{};
int num_poses = 0;
for (auto joint: joint_whitelist)
{
auto & joint_loc = joints[joint];
ret.joints[joint] = {
.position = joint_loc.pose.position,
.orientation = pack(joint_loc.pose.orientation),
.flags = wivrn::from_headset::to_pose_flags(joint_loc.locationFlags),
const auto & joint_loc = joints[joint];
wivrn::from_headset::body_tracking::pose pose{
.pose = joint_loc.pose,
.flags = 0,
};
}
return ret;
if (joint_loc.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
pose.flags |= wivrn::from_headset::body_tracking::orientation_valid;
if (joint_loc.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT)
pose.flags |= wivrn::from_headset::body_tracking::position_valid;
if (joint_loc.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)
pose.flags |= wivrn::from_headset::body_tracking::orientation_tracked;
if (joint_loc.locationFlags & XR_SPACE_LOCATION_POSITION_TRACKED_BIT)
pose.flags |= wivrn::from_headset::body_tracking::position_tracked;
poses[num_poses++] = pose;
}
return poses;
}
+14 -2
View File
@@ -21,6 +21,8 @@
#include "utils/handle.h"
#include "wivrn_packets.h"
#include <array>
#include <optional>
#include <openxr/openxr.h>
namespace xr
@@ -33,9 +35,19 @@ class pico_body_tracker : public utils::handle<XrBodyTrackerBD>
PFN_xrLocateBodyJointsBD xrLocateBodyJointsBD{};
public:
using packet_type = wivrn::from_headset::bd_body;
static constexpr std::array joint_whitelist{
XR_BODY_JOINT_PELVIS_BD,
XR_BODY_JOINT_LEFT_ELBOW_BD,
XR_BODY_JOINT_RIGHT_ELBOW_BD,
XR_BODY_JOINT_LEFT_KNEE_BD,
XR_BODY_JOINT_RIGHT_KNEE_BD,
XR_BODY_JOINT_LEFT_FOOT_BD,
XR_BODY_JOINT_RIGHT_FOOT_BD,
};
pico_body_tracker(instance & inst, session & s);
packet_type locate_spaces(XrTime time, XrSpace reference);
std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses>> locate_spaces(XrTime time, XrSpace reference);
};
} // namespace xr
-1
View File
@@ -304,7 +304,6 @@ void xr::session::set_refresh_rate(float refresh_rate)
{
if (xrRequestDisplayRefreshRateFB)
{
spdlog::info("set refresh rate to {}Hz", refresh_rate);
if (auto res = xrRequestDisplayRefreshRateFB(id, refresh_rate); res != XR_SUCCESS)
spdlog::warn("Refresh rate change failed: {}", xr::to_string(res));
}
-26
View File
@@ -28,7 +28,6 @@
#include "xr/check.h"
#include "xr/instance.h"
#include <cassert>
#include <stdexcept>
#include <openxr/openxr_platform.h>
xr::system::system(xr::instance & inst, XrFormFactor formfactor)
@@ -48,9 +47,6 @@ xr::system::system(xr::instance & inst, XrFormFactor formfactor)
if (inst.has_extension(XR_EXT_HAND_TRACKING_EXTENSION_NAME))
hand_tracking_supported_ = hand_tracking_properties().supportsHandTracking;
if (hand_tracking_supported_ and inst.has_extension(XR_FB_HAND_TRACKING_MESH_EXTENSION_NAME))
hand_mesh_fb_supported_ = true;
body_tracker = xr::body_tracker_supported(inst, *this);
face_tracker = xr::face_tracker_supported(inst, *this);
}
@@ -206,23 +202,6 @@ XrSystemBodyTrackingPropertiesFB xr::system::fb_body_tracking_properties() const
return body_tracking_prop;
}
XrSystemPropertiesBodyTrackingFullBodyMETA xr::system::meta_body_tracking_properties() const
{
if (!id)
throw std::invalid_argument("this");
XrSystemPropertiesBodyTrackingFullBodyMETA body_tracking_prop{
.type = XR_TYPE_SYSTEM_PROPERTIES_BODY_TRACKING_FULL_BODY_META,
};
XrSystemProperties prop{
.type = XR_TYPE_SYSTEM_PROPERTIES,
.next = &body_tracking_prop,
};
CHECK_XR(xrGetSystemProperties(*inst, id, &prop));
return body_tracking_prop;
}
XrSystemBodyTrackingPropertiesBD xr::system::bd_body_tracking_properties() const
{
@@ -296,11 +275,6 @@ bool xr::system::hand_tracking_supported() const
return hand_tracking_supported_;
}
bool xr::system::hand_mesh_fb_supported() const
{
return hand_mesh_fb_supported_;
}
vk::raii::PhysicalDevice xr::system::physical_device(vk::raii::Instance & vulkan) const
{
auto xrGetVulkanGraphicsDevice2KHR =

Some files were not shown because too many files have changed in this diff Show More