Compare commits

...
Author SHA1 Message Date
Vindicus999 5ed95327c0 Merge remote-tracking branch 'upstream/master' 2025-10-20 23:17:55 +00:00
Cláudio 'Patola' Sampaio 51c25624b7 Updated 1 message 2025-10-20 21:41:48 +02:00
Morand Axel 275a8195eb Fix typo in ufw allow command for ports
Corrected a typo in the firewall instructions for ufw.
2025-10-20 20:56:28 +02:00
aomiki 4061119aef fix typo in wizard 2025-10-20 20:55:13 +02:00
Vindicus999 0125adebed Merge remote-tracking branch 'upstream/master' 2025-10-19 23:17:37 +00:00
Jayden 3e0f6bf6fa updated zh-TW translation 2025-10-19 21:10:59 +02:00
Vindicus999 070dcb473e Merge remote-tracking branch 'upstream/master' 2025-10-13 23:17:02 +00:00
Patrick Nicolas 1dd0ed4fe3 Add note to load translations from build folder 2025-10-13 23:19:52 +02:00
Patrick Nicolas 56f32f4ae6 Remove flags in locale CI check 2025-10-13 23:13:08 +02:00
Alexander Afanasenko e3f35aad54 Russian translation (#525) 2025-10-13 23:07:56 +02:00
Vindicus999 abda962e38 Merge remote-tracking branch 'upstream/master' 2025-10-12 11:14:13 +00:00
mitsuami-megane c1111fe036 update ja locale 2025-10-12 08:44:55 +02:00
Vindicus999 18b076957e Merge remote-tracking branch 'upstream/master' 2025-10-11 23:16:59 +00:00
BlackCherryCat 14333ce208 Update es locale 2025-10-11 21:15:25 +02:00
Cláudio 'Patola' Sampaio 2d5b619429 Translated one new string 2025-10-11 20:55:11 +02:00
Patrick Nicolas 38efb9ff28 Fix typo, add \n in ufw config file 2025-10-11 19:53:59 +02:00
Patrick Nicolas 12e3df5b9c Update fr locale 2025-10-11 19:52:20 +02:00
Patrick Nicolas 56a94bfc10 Add toggle to hide system checks 2025-10-11 19:51:12 +02:00
Vindicus999 079e5f5b36 Merge remote-tracking branch 'upstream/master' 2025-10-09 11:16:31 +00:00
Patrick Nicolas 19d46db554 Skip broken OpenXR 1.1 support on HTC 2025-10-08 16:29:59 +02:00
Vindicus999 acb7410f7e Merge remote-tracking branch 'upstream/master' 2025-10-07 11:16:32 +00:00
galister c6e05754c8 update monado 2025-10-07 09:52:57 +02:00
mitsuami-megane 26f087c906 update ja locale 2025-10-07 09:49:29 +02:00
Vindicus999 56ba1eb22e Merge remote-tracking branch 'upstream/master' 2025-10-06 23:17:26 +00:00
Kresny 903a02d881 More documentation improvements (#521) 2025-10-06 20:19:32 +02:00
Vindicus999 deb28ca8e7 Merge remote-tracking branch 'upstream/master' 2025-10-06 17:17:44 +00:00
Kresny 1365f4f527 Documentation improvements (#517)
* Fixed flatpack info
* logs
* ufw instructions
* fixed Pico name
2025-10-06 15:02:01 +02:00
Patrick Nicolas cb7e6dabfc Update encoder configuration printing 2025-10-06 14:09:11 +02:00
Patrick Nicolas e4acf2401e Default passthrough encoder to encoder[0] settings 2025-10-06 13:47:28 +02:00
Vindicus999 4a9d159e52 Merge remote-tracking branch 'upstream/master' 2025-10-06 11:16:21 +00:00
Patrick Nicolas 5f373460a1 Silence qml "Created graphical object..." warning 2025-10-06 12:57:25 +02:00
Patrick Nicolas 25a81b6f5f Don't fail locales if issues are disabled 2025-10-06 09:39:58 +02:00
BlackCherryCat 70ec7acbec Update es locale 2025-10-06 09:17:15 +02:00
Vindicus999 28537ff611 Merge remote-tracking branch 'upstream/master' 2025-10-05 23:16:10 +00:00
Cláudio 'Patola' Sampaio 421d935dde fixed message that should not be translated 2025-10-05 22:51:33 +02:00
Cláudio 'Patola' Sampaio 7ea256a4c2 Updated pt_BR strings 2025-10-05 22:51:33 +02:00
Patrick Nicolas db91edf4c1 Update fr locale 2025-10-05 20:26:07 +02:00
Patrick Nicolas aca45420dd Show server error on GUI (encoders currently) 2025-10-05 20:26:07 +02:00
Patrick Nicolas 98fc4ad4bb firewalld support 2025-10-05 20:26:07 +02:00
Patrick Nicolas 8e4e4c9596 Add ufw detection and setup 2025-10-05 20:26:07 +02:00
Patrick Nicolas 34494f18e6 Split firewall troubleshoot messages 2025-10-05 20:26:07 +02:00
Patrick Nicolas f4d66eb4e7 Default foveation to 50% when switching to manual 2025-10-05 20:26:07 +02:00
Patrick Nicolas 39b7c6c45a Move default port into wivrn_config.h 2025-10-05 20:26:07 +02:00
Vindicus999 71375f082f Merge remote-tracking branch 'upstream/master' 2025-10-04 23:17:13 +00:00
Patrick Nicolas b81d010841 Fix build with ffmpeg 8 2025-10-04 23:16:22 +02:00
Vindicus999 b01b38b818 Merge remote-tracking branch 'upstream/master' 2025-10-03 17:16:10 +00:00
Patrick Nicolas db70d3975c Update spdlog 2025-10-03 17:03:43 +02:00
Vindicus999 379bba946f Merge remote-tracking branch 'upstream/master' 2025-10-02 11:15:39 +00:00
Guillaume Meunier 64355ff916 Fix dependency handling when compiling shaders 2025-10-02 11:53:25 +02:00
Vindicus999 4e32cd3afe Merge remote-tracking branch 'upstream/master' 2025-10-01 17:17:15 +00:00
Patrick Nicolas ed51bcc3b6 Fix leftover active_runtime.json after crash
If the server hard crashes (kill -9, system reboot etc), the
active_runtime.json remains there and will be preserved thanks to the
backup mechanism. If this happens, detect that it's already a symlink
and prevent doing the backup instead.
2025-10-01 14:17:52 +02:00
galister 4baa98c8f1 fix index controller mapping 2025-10-01 20:29:58 +09:00
Vindicus999 1feedafc62 Merge remote-tracking branch 'upstream/master' 2025-09-29 23:17:35 +00:00
Patrick Nicolas 4516beb2a5 Update Monado 2025-09-29 18:44:06 +02:00
Patrick Nicolas 092dbc893d Update Monado 2025-09-29 18:44:06 +02:00
Patrick Nicolas 2c1996eca1 Update Monado 2025-09-29 18:44:06 +02:00
Vindicus999 7c8b560d6e Merge remote-tracking branch 'upstream/master' 2025-09-29 11:16:45 +00:00
Sapphire fb3786fc2d Disable Rift driver build 2025-09-29 08:43:39 +02:00
Sapphire 190f4ae8bb Remove stale overrides from nix package 2025-09-29 08:43:13 +02:00
Sapphire 79a34bcdd5 Print full nix build logs in CI 2025-09-29 08:43:13 +02:00
Sapphire 0ec2cd5a3e Filter src in flake 2025-09-29 08:43:13 +02:00
Sapphire db66b0dbb7 Update flake inputs 2025-09-29 08:43:13 +02:00
Vindicus999 615eb37a9d Merge remote-tracking branch 'upstream/master' 2025-09-29 05:20:24 +00:00
Mitsuami ba18eac4a7 update ja local (#508) 2025-09-29 00:17:05 +00:00
Vindicus999 8c35775cec Merge remote-tracking branch 'upstream/master' 2025-09-28 23:17:18 +00:00
BlackCherryCat b0573c4265 Update es locale 2025-09-28 22:34:35 +02:00
Vindicus999 1d9fb638a5 Merge remote-tracking branch 'upstream/master' 2025-09-27 23:17:07 +00:00
Patola 46a36fcd55 Updated pt_BR strings (#506)
* Updated pt_BR strings

* Better tranlation

* Better tranlation 2
2025-09-27 22:40:28 +02:00
Vindicus999 c679d94fbd Merge remote-tracking branch 'upstream/master' 2025-09-27 17:14:46 +00:00
Patrick Nicolas a5bb9c2678 Fix imgui error for duplicate app name 2025-09-27 17:11:17 +02:00
Patrick Nicolas 5b6e20bdbe fr, it locales 2025-09-27 16:58:20 +02:00
Patrick Nicolas 1667065084 Add app launcher in stream gui 2025-09-27 16:57:23 +02:00
Patrick Nicolas 67918b7fe7 Move app launcher out of lobby_gui 2025-09-27 16:53:25 +02:00
Patrick Nicolas f03c460aa6 Return to last screen on thumbstick press 2025-09-27 16:28:59 +02:00
Patrick Nicolas e7c69e9464 Support stopping application 2025-09-27 16:28:59 +02:00
Patrick Nicolas 6e64dd03b3 Select active application from stream GUI 2025-09-27 10:08:51 +02:00
Patrick Nicolas 7fb8f4c1a8 List running applications 2025-09-27 10:08:51 +02:00
Patrick Nicolas fcbdda9908 Don't fake user presence, use focused instead 2025-09-27 10:08:51 +02:00
Vindicus999 bb05aef061 Merge remote-tracking branch 'upstream/master' 2025-09-26 17:16:46 +00:00
Patrick Nicolas 4e5eca204f Disable fragment shading rate
Causes artifacts due to triangle edges, the performance gain is not
worth it
2025-09-26 16:33:01 +02:00
Patrick Nicolas 6932f9461d Add support for raw video 2025-09-26 16:33:01 +02:00
Vindicus999 6cccd4fbd8 Configure build actions 2025-09-25 16:46:51 -04:00
Patrick Nicolas 7861d508c7 Fix double UTC offset 2025-09-24 22:57:14 +02:00
Patrick Nicolas 1290a15b7f Fix fr typo 2025-09-24 22:52:14 +02:00
Patrick Nicolas 5873de80b8 Don't shard when using TCP 2025-09-24 20:53:03 +02:00
Patrick Nicolas 66ca73981d Fix tagged version download 2025-09-24 07:53:21 +02:00
Patrick Nicolas a193b4084c Fix null byte written in json file 2025-09-23 18:01:33 +02:00
Patrick Nicolas f159e58c12 Abbreviate pressure vessel variable in flatpak 2025-09-23 16:36:56 +02:00
Patrick Nicolas 8bc6a3f388 Update Monado 2025-09-23 00:00:26 +02:00
Patrick Nicolas e3356acc16 Update Monado 2025-09-22 23:35:28 +02:00
Patrick Nicolas 6e9afab96b Update Monado 2025-09-22 22:56:48 +02:00
Patrick Nicolas 13c7f8fbc2 Drop GNU c++ extensions 2025-09-22 22:29:26 +02:00
Patrick Nicolas 668a94bae0 Update OpenComposite (sync with flathub version) 2025-09-22 22:05:00 +02:00
Patrick Nicolas d8707e0b4c Add ~/.steam to flatpak permissions 2025-09-22 21:37:16 +02:00
Marc Meier 6f696a92fb Add missing stdlib includes to improve portability (#499) 2025-09-22 14:58:09 +02:00
mitsuami-megane 3e6c407406 update ja locale 2025-09-21 08:22:34 +02:00
Patrick Nicolas 98347fc832 Request again OpenXR 1.1 2025-09-19 19:27:22 +02:00
BlackCherryCat 6ddde98714 Update es locale 2025-09-18 17:42:33 +02:00
Cláudio 'Patola' Sampaio 1477120888 updated pt_BR strings concerning language changes 2025-09-18 16:58:58 +02:00
Patrick Nicolas 5edc7f2f56 Add language names
source https://en.wikipedia.org/wiki/List_of_language_names
2025-09-18 15:50:08 +02:00
Patrick Nicolas b411afb946 Add option to manually set language 2025-09-18 15:50:08 +02:00
Patrick Nicolas f33dc57ec9 Prepare 25.9 release 2025-09-17 20:00:53 +02:00
Patrick Nicolas 509311604c Fix off-by-one in imgui call 2025-09-15 14:36:52 +02:00
Jayden 88ae120c52 upate zh-TW translation 2025-09-14 09:03:40 +02:00
Patrick Nicolas ea54031627 Don't try OpenXR 1.1
The promoted extension mechanism is flawed: it should use the new names
for FB interaction profiles, but keep the BD ones with the original name
2025-09-13 18:15:30 +02:00
Patrick Nicolas 8b9beb272d Silence cmake warning for unused variable 2025-09-12 19:30:45 +02:00
Patrick Nicolas 0e5a09cc45 Update libktx, switch to https download 2025-09-12 18:38:28 +02:00
BlackCherryCat b0144b96fc Update es translations 2025-09-12 17:35:42 +02:00
Hüseyin Fahri Uzun 3269fecef2 TR updated translation 2025-09-12 16:51:21 +02:00
mitsuami-megane 7e2b0cb973 update ja locale 2025-09-12 16:21:53 +02:00
Patrick Nicolas 608cf0c7b2 Drop Ubuntu oracular 2025-09-12 15:22:37 +02:00
Patrick Nicolas bd820a4f4a Update dashboard default encoder presets 2025-09-12 14:54:47 +02:00
Patrick Nicolas 891a087ccc Correctly handle larger swapchains 2025-09-10 22:23:02 +02:00
Patrick Nicolas adc07e8f50 Fix alpha channel in no-blit path 2025-09-10 22:21:48 +02:00
Patrick Nicolas 200586a0af Remove Snapdragon Game Super Resolution 2025-09-10 21:44:22 +02:00
Patrick Nicolas 80933a3392 Fix visibility mask (fixes UE games)
The returned mask type was offset, changing its meaning
2025-09-09 19:21:19 +02:00
Patrick Nicolas 3c08a3de2f Fix defoveation for low scale values
The effective image size may be different from the size in description,
we have to only consider the useful size
2025-09-09 19:00:08 +02:00
Patrick Nicolas ccf430d26a Fix width/height typo 2025-09-09 18:08:38 +02:00
Jonathan Steffan 5405176890 Update render type for Vulkan Info in bug report template 2025-09-08 17:47:16 +02:00
Jonathan Steffan b1c7160bba Update bug_report.yml to include plain render type
Added render type as plain for multiple fields in bug report template.
2025-09-08 17:47:16 +02:00
Patrick Nicolas 9a5af1a0ca Default to 2 encoder split 2025-09-04 17:26:08 +02:00
Patrick Nicolas 6b99cf4cc3 Use inheritance for decoder implementations 2025-09-04 17:15:29 +02:00
Patrick Nicolas cc5990a513 Run spirv-opt when compiling shaders 2025-09-04 17:06:19 +02:00
Patrick Nicolas c80ba550eb Fix defoveator descriptor pool size 2025-09-04 13:54:26 +02:00
Patrick Nicolas 9186bafd28 Pack shading rate in position variable 2025-09-04 10:43:44 +02:00
Patrick Nicolas 633f7feeb1 Skip blit when possible 2025-09-02 15:24:04 +02:00
Patrick Nicolas 435c2be127 Add renderdoc support in stream scene 2025-09-02 15:24:04 +02:00
Sapphire 692d4dec04 Enable XRT_FEATURE_OPENXR_LAYER_COLOR_SCALE_BIAS by default 2025-09-02 08:30:32 +02:00
Patrick Nicolas 5ff85ef7a7 Limit number of foveation samples per pixel 2025-08-31 17:08:45 +02:00
Guillaume Meunier 74ff55d5cb Fix gradle deprecation warnings 2025-08-27 20:56:30 +02:00
Patrick Nicolas f97c241f9f Don't request promoted extensions 2025-08-27 19:36:13 +02:00
Patrick Nicolas 9f2aa0157c Squash foveation Monado patches 2025-08-26 23:17:39 +02:00
Patrick Nicolas 2f91217e02 Update Monado 2025-08-26 23:12:25 +02:00
Patrick Nicolas d4665eb713 Update Monado 2025-08-26 22:58:33 +02:00
Patrick Nicolas 8f8e583eb6 Remove imageviews from xr::swapchain 2025-08-24 21:13:56 +02:00
Patrick Nicolas 05c8de4733 Don't abort on runtime's validation errors 2025-08-24 21:13:16 +02:00
Patrick Nicolas 90fa63a8fb Update vulkan validation layers 2025-08-24 21:05:47 +02:00
Patrick Nicolas 33f343e454 Update gradle 2025-08-24 20:46:11 +02:00
Patrick Nicolas cdd6064f2f Update validation layers 2025-08-24 19:42:06 +02:00
Patrick Nicolas d8d623fd7b Fix apk CI 2025-08-24 15:49:24 +02:00
Patrick Nicolas dd7bd8469e Fix shader fragment rate vulkan validation error 2025-08-24 14:22:48 +02:00
Patrick Nicolas 348a5a8313 Add glslang from vulkan tools 2025-08-24 14:22:48 +02:00
Patrick Nicolas 66b7b1fabb Return image to swapchain after encode is done
Vulkan video encode may use the original image, only mark it as free
once it is done encoding.
2025-08-23 11:07:48 +02:00
Patrick Nicolas aade274777 Search for flatpak Steam before system Steam 2025-08-23 10:27:31 +02:00
Patrick Nicolas b5c94c24a4 Fix crash on connection 2025-08-22 20:20:28 +02:00
Patrick Nicolas 211922ea02 Remove all AUTO options in cmake 2025-08-22 13:42:46 +02:00
Patrick Nicolas 959661c830 Fix const char* comparison 2025-08-21 20:46:49 +02:00
Patrick Nicolas 4a2c83a70d Use variable shading rate if supported by headset 2025-08-21 20:46:49 +02:00
Patrick Nicolas b5e5586ef6 Fix HTC face tracker
The tracker must be created precisely between the session creation and
session begin, or else it would fail when we access it with
XR_RUNTIME_FAILURE.
As it is not possible to recreate one later, disable the destroy and
store the handles in static variables so we can access them later,
behaving as if we were actually destroying and recreating one.
2025-08-20 22:11:43 +02:00
Patrick Nicolas bebd2cd97e Fix incorrect error reported on socket creation 2025-08-20 22:11:43 +02:00
Patrick Nicolas fadec7a7a0 Move generic tracker active status in own class 2025-08-20 22:11:43 +02:00
Patrick Nicolas 87b68aaa7b Prevent negative deltatime in imgui 2025-08-20 22:11:43 +02:00
Patrick Nicolas 1e6d8b5a95 Remove application::path_to_string/string_to_path 2025-08-20 22:11:43 +02:00
Patrick Nicolas 8dd3c75139 Remove xr_extensions from application.h 2025-08-20 22:11:43 +02:00
Patrick Nicolas ec4a95efb2 Remove application::get_xr_extensions() 2025-08-20 22:11:43 +02:00
Patrick Nicolas 1390ade131 Remove application::get_device() 2025-08-20 22:11:43 +02:00
Patrick Nicolas d18d33a615 Remove application::get_physical_device() 2025-08-20 22:11:43 +02:00
Patrick Nicolas 1574f82b8e Remove application::now() 2025-08-20 22:11:43 +02:00
Patrick Nicolas a82ee8c038 Remove application::queue_family_index() 2025-08-20 22:11:43 +02:00
Patrick Nicolas 5c397e125c Don't include application.h in xr/session.cpp 2025-08-20 22:11:43 +02:00
Patrick Nicolas 48c9bf0726 Remove xr.h 2025-08-20 22:11:43 +02:00
Patrick Nicolas cb5a7ad9cd Allow handles to hold the pointer to destructor 2025-08-20 22:11:40 +02:00
Patrick Nicolas ae75d95d7c Fix debug utils not enabled 2025-08-20 22:07:08 +02:00
Patrick Nicolas 68edc66fb7 Move *_supported into xr::system 2025-08-20 22:07:08 +02:00
Patrick Nicolas d2ea30e70f Remove unused variable 2025-08-20 22:07:08 +02:00
Patrick Nicolas 9f80c1da7c Remove body trackers from application.h 2025-08-20 22:07:06 +02:00
Patrick Nicolas 4b8295b7c7 Remove face tracker from application.h 2025-08-19 19:14:10 +02:00
Patrick Nicolas 1e37261cfa Use macros for interaction profile extension names 2025-08-19 19:14:10 +02:00
Patrick Nicolas 0acfe7cd24 Remove hand tracker from application.h 2025-08-19 19:14:10 +02:00
Patrick Nicolas 5f6641c38f load_icons: read files only once 2025-08-19 19:14:10 +02:00
Guillaume Meunier c2f23223a2 Don't trust the file extension when loading icons
Fixes #439
2025-08-18 21:16:08 +02:00
Patola 94aceb3f0f Update pr_BR strings for small GUI activation option change (#460) 2025-08-17 21:18:47 +02:00
Patrick Nicolas bce3e498e8 Fix destruction of textures still in use 2025-08-16 14:15:29 +02:00
Patrick Nicolas b9052c6ebb controller/hand_interaction: fix ODR, race condition 2025-08-16 14:15:29 +02:00
Patrick Nicolas c15de9bf27 Automatically name image/buffer allocations 2025-08-16 14:15:29 +02:00
Patrick Nicolas dc04f7edcc Add utility to write specialization constants 2025-08-16 14:15:29 +02:00
Patrick Nicolas b1d6d50a4a Replace unused frames() method with empty() 2025-08-15 23:40:40 +02:00
Patrick Nicolas 5784cbd4fa remove unused include 2025-08-15 23:28:35 +02:00
Patrick Nicolas 757e0fd97b merge tracking control and its mutex 2025-08-15 23:27:44 +02:00
Patrick Nicolas 31c347475e Cleanup some redundant variables 2025-08-15 23:20:11 +02:00
Patrick Nicolas 6d0cc60626 Use subgroups in distortion shader 2025-08-14 21:02:56 +02:00
Patrick Nicolas 50c44c8422 Add iGPU no-copy for distortion UBO 2025-08-14 17:04:09 +02:00
Patrick Nicolas a5b3178f36 Fix uninitialized data in foveation params 2025-08-14 17:04:09 +02:00
Guillaume Meunier 49ab1af542 Avoid showing the spinner when the predicted display time is close to 0 2025-08-12 20:17:35 +02:00
Patrick Nicolas c7fc144a66 Add simple controller binding for hand interaction 2025-08-12 17:36:17 +02:00
Patrick Nicolas c8b8d798d1 Update fr, it locale 2025-08-12 13:42:49 +02:00
Patrick Nicolas 5e4edc9857 Fix lang issue closing for no reason 2025-08-11 15:56:18 +02:00
Patrick Nicolas 461de7c540 Remove "v" at the beginning of the version 2025-08-11 15:31:23 +02:00
Patrick Nicolas a2e470799e Add --version option 2025-08-11 14:53:32 +02:00
Patrick Nicolas d2191a354e Improve issue template
Add an installation method entry
Recommend file attachments for long entries
2025-08-11 14:45:08 +02:00
Patrick Nicolas 9725ae7fc0 Add an option to disable in-stream GUI 2025-08-11 10:44:44 +02:00
BlackCherryCat e7b218bfb6 Simplify es locale 2025-08-11 09:16:53 +02:00
Patrick Nicolas 93ba9b8367 Add required to libarchive and png dependencies 2025-08-10 23:01:46 +02:00
Patrick Nicolas 30ceab5b30 Forward PATH when starting application in systemd mode 2025-08-10 22:06:59 +02:00
Patrick Nicolas 810c9bd2fa Manage localisation issues from CI 2025-08-10 15:15:13 +02:00
Patrick Nicolas 869911fcd5 pythonize check_messages (merged into check_po) 2025-08-10 15:15:13 +02:00
Patrick Nicolas e744a91488 prepare 25.8 release 2025-08-10 10:48:50 +02:00
Patrick Nicolas e603e30229 Reduce flatpak permissions 2025-08-10 10:21:48 +02:00
Patrick Nicolas 5ccc725ef7 Hide Steam launch options in wizard if empty 2025-08-09 22:47:00 +02:00
Guillaume Meunier 03cfe1c12d Keep the GUI locked to the controller that started repositionning in the lobby 2025-08-09 15:50:48 +02:00
Guillaume Meunier acea81c13f Allow dragging with hand tracking in the app list 2025-08-09 15:44:47 +02:00
Guillaume Meunier 8dcd14b168 Unbreak CI 2025-08-09 15:09:18 +02:00
Guillaume Meunier 45d5d6dd7a Read Linux steam icons 2025-08-09 15:02:28 +02:00
Guillaume Meunier d5ef8c1a85 Added checks and try-catch when attempting to load icons
Fixes #437
2025-08-09 10:12:58 +02:00
Patrick Nicolas b036731b51 Hide Steam info when not needed 2025-08-09 00:07:35 +02:00
Patrick Nicolas e02d115a4e Use PRESSURE_VESSEL_IMPORT_OPENXR_1_RUNTIMES 2025-08-09 00:07:35 +02:00
epsypolym 00e979065b Update slovak translation (#436)
* Update slovak translation

- Replaced multiple instances of informal form with formal form, also by extension replaced some cases of gendered form with gender neutral version.
- Fixed a few typos

* additional adjustments to sk locale

- re-added a space i accidentally removed (oops)
- fixed other miscellaneous typos found during 2nd review
- removed instance of word "fičura" - informal slang translation of word "feature" - replaced with "funkcia" - ie: function as direct translation of "feature" doesn't exist
2025-08-08 23:03:55 +02:00
Hüseyin Fahri Uzun c7b7bc6fbd added TR translation 2025-08-08 21:40:35 +02:00
Guillaume Meunier 58b6b9d19f Remove useless newline in fr and it locales 2025-08-08 21:09:39 +02:00
Guillaume Meunier 230e102f36 Only request the app list when the stream is stalled 2025-08-08 20:41:46 +02:00
Guillaume Meunier 963205908f Add spinner when an app is starting 2025-08-08 20:41:46 +02:00
Guillaume Meunier 1b11594c3e Send app list ASAP 2025-08-08 20:41:46 +02:00
Guillaume Meunier 1b78180d73 Send app icons one by one 2025-08-08 20:41:46 +02:00
Patrick Nicolas 669b06e982 typo in translating.md 2025-08-08 20:10:18 +02:00
myghi63 3c82c2db84 Fix welcome translation and file comments 2025-08-08 19:48:32 +02:00
Patrick Nicolas 5d58af95e4 Add note about Lokalize mailing list setting 2025-08-08 18:15:59 +02:00
myghi63 a1bf1de910 Update pt_BR locale (#433) 2025-08-08 17:31:10 +02:00
ჼ 73390c2035 Small fixes in sk translation (#432) 2025-08-08 16:53:42 +02:00
Patrick Nicolas 9c599206d6 Working NVIDIA h264 vulkan video encode!
NVIDIA fails with initalization failed error if no
VkVideoEncodeH264RateControlLayerInfoKHR structure is provided
2025-08-08 16:22:11 +02:00
Patrick Nicolas f91c7222db Fix NVIDIA crash in vulkan video encoder creation 2025-08-08 16:15:49 +02:00
Patrick Nicolas 4f0daa0a63 Don't show wizard on first run if server failed 2025-08-08 14:38:49 +02:00
Patrick Nicolas e0608f0c68 Don't crash if server failed to start 2025-08-08 14:34:42 +02:00
Patrick Nicolas 34036c6b9e Fail if path command does not exist 2025-08-08 14:16:46 +02:00
Patrick Nicolas 19ad856e59 Use VK_KHR_video_maintenance1 2025-08-08 14:06:01 +02:00
Jayden 5097ecef3b added new translation 2025-08-07 17:54:53 +02:00
Patrick Nicolas c6a1f3abc9 Set Lighthouse hand tracking as "conforming" 2025-08-07 09:31:55 +02:00
Patrick Nicolas 46ffc444f0 Default to xrizer 2025-08-06 20:19:59 +02:00
BlackCherryCat f63892119d Update es locale 2025-08-06 20:18:54 +02:00
Patrick Nicolas c485bcb015 Update Monado 2025-08-06 17:27:46 +02:00
Patrick Nicolas 677d303d43 Update Monado 2025-08-06 17:27:46 +02:00
Patrick Nicolas d624f74f83 Update Monado 2025-08-06 17:27:46 +02:00
Patrick Nicolas 89c5921fc8 Update Monado 2025-08-06 17:27:46 +02:00
Patrick Nicolas 443de59d73 Update Monado 2025-08-06 17:27:46 +02:00
Patrick Nicolas 81abdfee3e Update Monado 2025-08-06 17:27:46 +02:00
Patrick Nicolas 2c65b43969 Update Monado 2025-08-06 17:27:46 +02:00
mitsuami-megane 5efc92efee update ja locale 2025-08-06 12:40:08 +02:00
Guillaume Meunier a867c1da45 Fix serialization of vectors of more than 65535 elements 2025-08-04 21:51:39 +02:00
Guillaume Meunier 2327eacbeb Synchronize all uses of the command queue 2025-08-04 15:49:42 +02:00
Patrick Nicolas 55def29a10 Update fr locale 2025-08-04 09:42:23 +02:00
Patrick Nicolas 88f5f2ace4 Show warning if no OpenVR library is detected 2025-08-04 09:40:09 +02:00
Guillaume Meunier 9a53aaa205 Add support for paletted icons, fix misc ico loading bugs 2025-08-04 09:13:51 +02:00
Guillaume Meunier de810d1eea Don't crash the client when the icon cannot be loaded 2025-08-04 09:13:51 +02:00
Guillaume Meunier 06240858fd Avoid loading app icons in the dashboard, add error handling when loading steam icon 2025-08-04 09:13:51 +02:00
Guillaume Meunier fddfb8eb57 Check sizes for overflow before serializing vectors, strings, and spans 2025-08-04 09:13:51 +02:00
Jayden d9a86cb1c8 updated zh_TW translation (#423) 2025-08-03 14:58:10 +02:00
ჼ 79139b38bc Add Slovak translation (#420) 2025-08-03 14:56:49 +02:00
Guillaume Meunier fc3d13ca9d Position the text correctly in the app list 2025-08-03 11:03:33 +02:00
Guillaume Meunier 22757c99ad Don't load too many textures in the same frame 2025-08-03 10:50:22 +02:00
Guillaume Meunier 993adbb651 Drag to scroll, even when hovering a widget 2025-08-03 10:50:22 +02:00
Guillaume Meunier 18f38b575d Cache the loaded icons 2025-08-03 10:50:22 +02:00
Sapphire 5d427f1464 Add librsvg and libpng to nix build inputs 2025-08-03 10:50:22 +02:00
Guillaume Meunier 51b1b3efeb Premultiply alpha when loading images 2025-08-03 10:50:22 +02:00
Guillaume Meunier a144f88f95 Fix horizontal scrolling 2025-08-03 10:50:22 +02:00
Guillaume Meunier fed26b0675 Improve scrolling with the thumbstick 2025-08-03 10:50:22 +02:00
Guillaume Meunier 02c3da3f9f Use a growable descriptor pool in imgui 2025-08-03 10:50:22 +02:00
Guillaume Meunier 1fa4ac0231 Avoid using boost::property_tree for ini parsing 2025-08-03 10:50:22 +02:00
Guillaume Meunier d830d3bdd0 Support older libstdc++ 2025-08-03 10:50:22 +02:00
Guillaume Meunier ce21f578a1 Fix Ubuntu package in CI 2025-08-03 10:50:22 +02:00
Guillaume Meunier 46ad809d56 Add dependency to librsvg2 in CI and docs 2025-08-03 10:50:22 +02:00
Guillaume Meunier 9ded9d37f7 Send packet size on 32 bits instead of 16 bits in TCP 2025-08-03 10:50:22 +02:00
Guillaume Meunier 8aca33e0a4 Set imgui textures to clamp to edge 2025-08-03 10:50:22 +02:00
Guillaume Meunier f3c668a331 Display app icons in lobby 2025-08-03 10:50:22 +02:00
Guillaume Meunier 5e93c87403 Send application icons to the headset 2025-08-03 10:50:22 +02:00
Guillaume Meunier 5435513da2 Allow loading texture from memory buffer for imgui 2025-08-03 10:50:22 +02:00
Patrick Nicolas e67c071be6 Dump velocities with WIVRN_DUMP_TRACKING 2025-08-03 10:48:44 +02:00
Patrick Nicolas 1370942833 Fix controller velocities with xrLocateSpaces 2025-08-03 10:15:28 +02:00
Patrick Nicolas cd47a331de Bump xrizer to v0.3 2025-08-02 09:16:40 +02:00
Patrick Nicolas 315c2f4d82 Change mpc download mirror 2025-08-02 09:11:19 +02:00
Patrick Nicolas c8dc545198 Improve locale check summary 2025-08-02 09:06:23 +02:00
BlackCherryCat 8eaa62c3f8 Update es locale 2025-08-02 08:33:52 +02:00
mitsuami-megane 7884893ccc ja locale line breaks 2025-08-02 08:32:36 +02:00
mitsuami-megane d7d91cd84d update ja locale 2025-07-31 09:18:01 +02:00
Patrick Nicolas 2b9287c042 Reduce log spam for foveation 2025-07-30 23:31:30 +02:00
mitsuami-megane dcc1c82f54 update ja locale 2025-07-30 18:50:17 +02:00
Patrick Nicolas dda5c94051 Update IT locale 2025-07-30 14:53:11 +02:00
Patrick Nicolas 6f47b7669c Update FR locale 2025-07-30 14:53:11 +02:00
Patrick Nicolas ce77a67354 Add explicit language list to update_messages.sh 2025-07-30 09:41:31 +02:00
Patrick Nicolas 3648224f09 Suggest bindings for Pico 4s controller on stream 2025-07-30 09:32:30 +02:00
Patrick Nicolas b72554ea02 Enable split nvenc encoders by default 2025-07-28 17:18:26 +02:00
Patrick Nicolas 4fa33b183f Tweak stream GUI texts, positions 2025-07-27 23:36:13 +02:00
Patrick Nicolas f8f4b8643e Tweak display of foveation config 2025-07-27 23:36:13 +02:00
Kierek e5ba1f7394 Share CUDA context between all nvenc encoder instances 2025-07-27 23:32:41 +02:00
Patrick Nicolas 25ca41cfcf Sort applications alphabetically 2025-07-27 10:06:19 +02:00
Patrick Nicolas 066d195c83 Add "connected" screen with buttons for apps 2025-07-27 08:55:14 +02:00
Patrick Nicolas 45e0fce476 Add packet to start an application 2025-07-26 20:05:35 +02:00
Patrick Nicolas 93a2f1c10b Add packets to list applications 2025-07-26 19:35:26 +02:00
Patrick Nicolas ec63c8a395 Remove unused includes 2025-07-26 15:46:41 +02:00
Guillaume Meunier ac2044dffc Allow enabling the debug menu from gradle.properties 2025-07-26 11:44:01 +02:00
Guillaume Meunier adbbd71557 Fade when dimming the video stream, override session state when the stream GUI is interactable, move the lobby plots to the debug tab 2025-07-26 11:29:06 +02:00
Guillaume Meunier aa4f9ac265 Add first run screen 2025-07-26 11:29:03 +02:00
Guillaume Meunier c3ec979dde Overrideable foveation center 2025-07-26 11:18:58 +02:00
Guillaume Meunier ce437ce2b4 Add compact view in the stream scene 2025-07-26 11:18:58 +02:00
Guillaume Meunier 3a04c52484 Rename stream_stats.cpp -> stream_gui.cpp 2025-07-26 11:18:58 +02:00
Guillaume Meunier a04a0f5d03 Avoid unrealistic frame times when accumulating metrics 2025-07-26 11:18:58 +02:00
Guillaume Meunier 344cb7e572 Don't send controller data when the GUI is interactable 2025-07-26 11:18:58 +02:00
Guillaume Meunier 794f2e3468 Update imgui 1.91.3 -> 1.92.1 2025-07-26 11:18:58 +02:00
Guillaume Meunier 96083cd02e Add interactable GUI in stream scene 2025-07-26 11:18:58 +02:00
Guillaume Meunier 366bc2c793 Fix typo in the dithering Bayer matrix 2025-07-26 11:18:58 +02:00
Guillaume Meunier db3832aadc Sort OpenXR/Vulkan extensions alphabetically 2025-07-26 11:18:58 +02:00
Guillaume Meunier f25aa9d7d2 Use grip instead of A/X to move the GUI 2025-07-26 11:18:58 +02:00
Guillaume Meunier 54f91405a6 Refactor the client GUI 2025-07-26 11:18:58 +02:00
Patrick Nicolas a69bd596d1 Add common-server CMake library 2025-07-25 22:10:47 +02:00
Patrick Nicolas 62894b178d Read host /usr/share/applications in flatpak 2025-07-25 22:10:47 +02:00
Patrick Nicolas e414c82d6c Access real .local/share from flatpak 2025-07-25 22:10:47 +02:00
Patrick Nicolas 6f039a6bac Use common app list for dashboard 2025-07-25 22:10:47 +02:00
Patrick Nicolas f0e625e095 don't build application list binary 2025-07-25 22:10:47 +02:00
Patrick Nicolas 74ea5cfe19 Support flatpak Steam 2025-07-25 22:10:47 +02:00
Patrick Nicolas 8b42be80ee Add flatpak permissions to enumerate applications 2025-07-25 22:10:47 +02:00
Patrick Nicolas b2d49dddb3 WIP application enumeration 2025-07-25 22:10:47 +02:00
Patrick Nicolas fa6e768783 Cache is_flatpak result 2025-07-25 22:10:47 +02:00
Patrick Nicolas 44bbf00bf1 Remove obsolete code 2025-07-25 22:10:47 +02:00
Sapphire e358230a25 Move face/body tracker creation logic into constructors 2025-07-23 19:19:44 +02:00
Patrick Nicolas a1cdbbe0ba Update xrizer (flatpak) 2025-07-23 15:18:48 +02:00
Patrick Nicolas d3e10dc31b Rewrite child application management
Forked applications are managed by a class, which can track more than
one child.
Systemd mode uses transient units, libsystemd is replaced by
gdbus-codegen, the management objects shares the interface with forked
application.
2025-07-22 20:49:32 +02:00
Patrick Nicolas 2f5496c06e Give application to launch instead of reading conf 2025-07-17 15:28:41 +02:00
Patrick Nicolas 286268d2c6 Start application in transient unit in systemd mode 2025-07-16 22:07:03 +02:00
Patrick Nicolas b845f30454 Increase minimum cmake version to 3.28
required for EXCLUDE_FROM_ALL in fetchcontent
2025-07-16 13:12:40 +02:00
Patrick Nicolas 84ef968dc3 Prevent crash on very strong foveation 2025-07-15 17:31:48 +02:00
Patrick Nicolas d8c8020d84 Change isl mirror 2025-07-15 10:31:05 +02:00
galister 5307f2fe62 pass bit_depth to probe_nvenc 2025-07-14 08:47:45 +02:00
galister ec42db83bc change encode_10bit → bit-depth 2025-07-11 23:09:37 +02:00
galister ed32676299 10-bit encoding as a global setting 2025-07-11 23:09:37 +02:00
galister d64d5909ee vaapi: 10-bit hevc/av1 encoding 2025-07-11 23:09:37 +02:00
Patrick Nicolas c5dab27f3c Fix binding to OpenXR 1.1 touch plus interaction profile 2025-07-09 21:09:26 +02:00
Sapphire 717e93846a Unset derived poses for hand interaction 2025-07-09 10:33:32 +02:00
Sapphire c682f8cd9f Make hand interaction a different xdev
* Don't override hands from other drivers on interaction profile change

* Rename *_hand to *_controller

* Fix derived pose and tracking control desync with hand interaction

* Reset pose history on switch from hand interaction, code cleanup
2025-07-09 10:33:32 +02:00
Sapphire 8f0ca7b04c Forward XR_EXT_hand_interaction
* Fix binds

* hand_interaction tids
2025-07-09 10:33:32 +02:00
Sapphire 74befe1f4a Bump flake inputs, add wireshark dissector build to flake 2025-07-09 10:33:32 +02:00
Sapphire 6f22068c42 Bump dissector OpenXR version, fix openxr found check 2025-07-09 10:33:32 +02:00
Patrick Nicolas a6660434e9 Fix disconnect button 2025-07-08 15:30:13 +02:00
Patrick Nicolas ecf6dfd215 Reallocate swapchains if a bigger one is needed 2025-07-08 08:59:17 +02:00
Sapphire 88f03acfbf Resolve symlinks when getting configuration file paths 2025-07-06 20:00:23 +02:00
Guillaume Meunier 8686233b49 Fix depth test in lobby on Quest 3 2025-07-06 10:26:12 +02:00
Patrick Nicolas 11cd9235d9 Allow multiple configuration files
Will merge contents from
@CMAKE_INSTALL_PREFIX@/share/wivrn/config.json
/etc/wivrn/config.json
~/.config/wivrn.config.json (XDG_CONFIG_DIR in fact)

If -f option is provided, just parse that file, don't merge anything
2025-07-06 10:22:25 +02:00
Sapphire fbe5430dc2 Skip Nix CI step for apk repo 2025-07-06 09:59:14 +02:00
Guillaume Meunier be504b5944 Add controller offset for Quest 3 2025-07-06 09:42:51 +02:00
Guillaume Meunier c9e078bd47 Avoid segfault if xrCreatePassthroughFB fails 2025-07-06 09:12:41 +02:00
Guillaume Meunier fafe01b76a Enable passthrough in splash screen 2025-07-05 21:39:41 +02:00
Patrick Nicolas b66ca2e561 Ignore visibility mask errors on connection 2025-07-05 19:53:49 +02:00
Sapphire 5bfc9ed942 Forward session state to server
Closes #395
2025-07-05 15:41:22 +02:00
Patrick Nicolas 8e2719ff30 Update NDK to 28 2025-07-04 23:43:39 +02:00
Sapphire 3ac31fe5cc Forward XR_EXT_user_presence
Closes #258
2025-07-04 23:43:06 +02:00
Sapphire f43ee229f1 update monado 2025-07-04 23:43:06 +02:00
Patrick Nicolas a1c262808d update monado 2025-07-04 23:43:06 +02:00
Patrick Nicolas 1698f4aba6 update monado 2025-07-04 23:43:06 +02:00
Patrick Nicolas 90f49e579b update monado 2025-07-04 23:43:06 +02:00
Patrick Nicolas 56e68825ef typo developper -> developer 2025-07-04 20:30:00 +02:00
Patrick Nicolas af69dc1f4e Fix flatpak CI on pull requests 2025-07-03 11:13:41 +02:00
Sapphire 42c57b61e2 Revert "Fix meta handtracking thumb rotation offset"
Thumb joint rotations are correct when requesting OpenXR 1.1 on Quest,
this is no longer needed.

This reverts commit e0a1598ac5.
2025-07-03 09:26:02 +02:00
Sapphire 88f0f52afe Use grip_surface pose for palms when supported 2025-07-03 09:26:02 +02:00
Sapphire 66878a259d fix add_space locate_spaces check, load xrLocateSpacesKHR on OpenXR 1.0 if supported 2025-07-03 09:26:02 +02:00
Patrick Nicolas 1ad015ff65 Use xrLocateSpaces when runtime has OpenXR 1.1 2025-07-02 22:13:35 +02:00
Patrick Nicolas 3a33adbd86 Remove Quest/simple_controller hack
Just don't suggest bindings for simple controller on Quest
2025-07-02 21:55:27 +02:00
Patrick Nicolas 2ba3d78cd4 Try to request OpenXR 1.1 2025-07-02 21:55:27 +02:00
Guillaume Meunier a2837904cc Fix ray visibility 2025-07-01 21:45:33 +02:00
Patrick Nicolas 29b445e984 Don't build common when only building openxr lib 2025-07-01 21:26:24 +02:00
Sapphire f2760df4b7 bump protocol revision 2025-06-30 11:34:34 +02:00
Sapphire 8dc2b7a5e0 Store face tracker in variant 2025-06-30 11:34:34 +02:00
Sapphire dd4d442f43 Fix set_mic_state typo 2025-06-30 11:34:34 +02:00
Patrick Nicolas eacca07857 25.6.1 release notes 2025-06-29 10:51:08 +02:00
Patrick Nicolas 55b7f0e6c7 Fix foveation with negative offsets
H3VR uses negative y extents so that y axis is flipped, previous code
assumed all extents would be positive.
2025-06-28 15:15:53 +02:00
Sapphire 2250143f00 Don't send poses for khr/simple_controller on Quest when hand tracking data is invalid 2025-06-28 10:29:46 +02:00
Sapphire 795d88d9dc Use method_pointer for function pointer initialisation in eye tracker 2025-06-28 10:29:46 +02:00
Sapphire 6377f21b99 Return appropriate error and use logging helper when unsupported input is requested 2025-06-28 10:29:46 +02:00
Patrick Nicolas 8691be2677 fix release python packages 2025-06-26 21:25:23 +02:00
Patrick Nicolas 857e3af6cc Prepare 25.6 release 2025-06-26 19:19:41 +02:00
Patrick Nicolas 4e53406ec5 Failsafe in foveation for weird application FoV 2025-06-26 18:54:09 +02:00
Patrick Nicolas dbcf4f99f7 Add missing right/squeeze for touch pro controller 2025-06-25 19:20:30 +02:00
Patrick NicolasandBaplar 6ad4e8ae51 Multiple foveation fixes
fix math for center and convergence calculation
add WIVRN_FOVEATION_OFFSET variable to change the vertical center offset
set default vertical center offset to 10° below horizontal
add WIVRN_FOVEATION_DISTANCE variable to set convergence distance
set default convergence distance to 1m
fix cache invalidation condition

Co-authored-by: Baplar <baplar@gmail.com>
2025-06-25 18:27:24 +02:00
ჼ d459c9489e Update hardware.cpp 2025-06-25 12:33:09 +02:00
Patrick Nicolas b75714c936 Unify tracked and non tracked foveation 2025-06-24 15:29:12 +02:00
LuckShiba 9e3951da78 Fix pt_BR locale tooltip width 2025-06-24 14:29:42 +02:00
LuckShiba d6cc209e76 Update pt_BR locale 2025-06-24 14:29:42 +02:00
LuckShiba 4b0d53fa58 Fix pt_BR locale tooltip length 2025-06-24 14:29:42 +02:00
LuckShiba 2ef30ce778 Update pt_BR locale 2025-06-24 14:29:42 +02:00
Patrick Nicolas 6e8af7bb9a Fix absolute manifest build instructions 2025-06-24 10:03:03 +02:00
Patrick Nicolas b9752276b7 read DBUS env variables for --systemd mode 2025-06-23 18:30:27 +02:00
Patrick Nicolas 95ab427517 Fix system bus -> session bus 2025-06-23 12:59:36 +02:00
mitsuami-megane 8ddc6355f2 Rephrase sentence in ja locale 2025-06-23 11:33:23 +02:00
Jayden 081c45e7c6 Updated translation (#377)
* rephrase some sentence that doesnt really make sense in chinese

* updated translation

* added missing translation
2025-06-22 21:08:09 +02:00
Patrick Nicolas 4ee47ab5d4 cleanup unused xr::passthrough 2025-06-22 09:37:46 +02:00
Patrick Nicolas 0fba21addf Fix touch plus/pro controller bindings 2025-06-22 09:37:46 +02:00
Baplar b54d0c5dd5 Use shorter serial for generic trackers 2025-06-21 19:26:37 +02:00
BlackCherryCat 26ef107df4 Simplified es translation 2025-06-20 22:56:41 +02:00
Álvaro f50933c8c6 Updated es locale (#371) 2025-06-20 20:12:17 +02:00
Patrick Nicolas 444a5fed9e Force compositor scale to 100% 2025-06-20 09:17:07 +02:00
mitsuami-megane c8c015b239 update ja locale 2025-06-19 19:05:22 +02:00
Patrick Nicolas 25f9b4b67d Update IT locale 2025-06-18 21:33:12 +02:00
Patrick Nicolas f189356c76 Update FR locale 2025-06-18 21:26:11 +02:00
Patrick Nicolas 19dcec446f Add notice about SteamVR not being compatible with WiVRn 2025-06-18 21:12:52 +02:00
Patrick Nicolas 70ba578f23 Fix cache invalidation for right eye 2025-06-17 23:51:38 +02:00
Patrick Nicolas 5955b2c622 Fix foveation center 2025-06-17 23:35:46 +02:00
Patrick Nicolas ab921c213c minor simplification 2025-06-17 18:10:23 +02:00
Patrick Nicolas 169e8bf206 Check protocol compatibility on handshake 2025-06-17 09:31:30 +02:00
Patrick Nicolas 7e3b6d001e Fail if too many generic trackers are reported 2025-06-16 23:41:11 +02:00
Sapphire cdba101fe8 Remove htc and pico body tracking tooltips 2025-06-16 19:42:36 +02:00
Sapphire eb0aa46b83 Store body trackers in variant 2025-06-16 19:42:36 +02:00
SapphireandAwzri ad136eae43 Vive Ultimate Tracker support
Co-authored-by: Awzri <awzri@awzricat.com>
2025-06-16 19:42:36 +02:00
Patrick Nicolas f2050fbe54 Re-fix build with older vulkan_hpp 2025-06-15 10:00:29 +02:00
Patrick Nicolas 804bfc6291 Fix build with older vulkan_hpp 2025-06-15 09:53:01 +02:00
Patrick Nicolas 2ee0604ccf fix "Steam informations" -> "Steam information" 2025-06-13 11:38:50 +02:00
Patrick Nicolas 40aeaab762 Cap num DPB slots to 16 2025-06-12 21:34:33 +02:00
Patrick Nicolas 711be3754b fix comp_target deletion (again) 2025-06-12 15:46:37 +02:00
Patrick Nicolas f6eb528ea7 Name most vulkan objects 2025-06-12 15:46:37 +02:00
Patrick Nicolas 1ed4d3cfe6 Name vulkan video objects 2025-06-12 15:46:37 +02:00
Patrick Nicolas 5be3a8aef4 Utility to name vulkan objects 2025-06-12 15:46:37 +02:00
Patrick Nicolas a6c20e9520 Send vulkan video idr over tcp 2025-06-12 11:07:10 +02:00
Patrick Nicolas 52b0bb0c42 update monado 2025-06-10 14:44:01 +02:00
Patrick Nicolas e5fd6a69dc Update monado 2025-06-10 14:44:01 +02:00
Patrick Nicolas f2679f21d0 Update monado 2025-06-10 14:44:01 +02:00
Patrick Nicolas d065229cb7 update monado 2025-06-10 14:44:01 +02:00
Patrick Nicolas 629f26acd7 Ignore newline in monado-rev 2025-06-10 14:44:01 +02:00
Patrick Nicolas 80622e16e6 Update monado git url 2025-06-10 14:44:01 +02:00
Patrick Nicolas caa2219a99 Rebuild on monado-rev change 2025-06-10 14:44:01 +02:00
Patrick Nicolas c98b461809 fix vulkan video conformance issues 2025-06-10 11:26:32 +02:00
277 changed files with 34536 additions and 11599 deletions
+23 -5
View File
@@ -36,17 +36,33 @@ body:
validations:
required: true
- type: input
attributes:
label: Installation method
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.
placeholder: Add the content of config.json here...
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
description: Provide the `wivrn-server` output.
placeholder: Add the output of the wivrn-server here...
placeholder: |
Add the output of the wivrn-server here.
If more than a few lines, prefer file attachment.
- type: dropdown
id: gpu
@@ -64,7 +80,8 @@ body:
attributes:
label: Vulkan Info
description: Provide the output of `vulkaninfo --summary` command.
placeholder: Add the output of vulkaninfo command here...
render: text
placeholder: Attach the output as a file here.
- type: dropdown
id: hmd
@@ -90,4 +107,5 @@ body:
attributes:
label: ADB Logs
description: Provide the output of `adb logcat` command.
placeholder: Add the output of adb logcat command here...
render: plain
placeholder: Attach the output of adb logcat as a file.
+6
View File
@@ -0,0 +1,6 @@
version: "1"
rules:
- base: master
upstream: WiVRn:master
mergeMethod: hardreset
+16 -9
View File
@@ -2,7 +2,7 @@ name: Release APK Only
on:
push:
branches: [ "master" ]
branches: [ "apk-build" ]
env:
BUILD_TYPE: RelWithDebInfo
@@ -22,10 +22,17 @@ jobs:
- uses: actions/checkout@v4
with:
# Checkout from upstream instead of WiVRn-APK to ensure the GIT_DESC variable is set correctly
repository: 'WiVRn/WiVRn'
repository: 'Vindicus999/WiVRn'
ref: ${{ github.sha }}
fetch-depth: 0
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944
with:
vulkan-query-version: 1.3.296.0
vulkan-components: Glslang, SPIRV-Tools
vulkan-use-cache: true
- name: set up JDK
uses: actions/setup-java@v4
with:
@@ -102,13 +109,13 @@ 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: 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 APK debug artifacts
uses: actions/download-artifact@v4
+35 -23
View File
@@ -33,12 +33,12 @@ jobs:
- name: Install dependencies
run: >
sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libavahi-glib-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev libboost-all-dev librsvg2-bin libssl-dev libnotify-dev
sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libavahi-glib-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev libboost-all-dev librsvg2-bin libssl-dev libnotify-dev librsvg2-dev libarchive-dev
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944
with:
vulkan-query-version: 1.3.283.0
vulkan-components: Vulkan-Headers
vulkan-query-version: 1.3.296.0
vulkan-components: Vulkan-Headers, Glslang, SPIRV-Tools
vulkan-use-cache: true
- name: Configure CMake
@@ -78,7 +78,7 @@ jobs:
build-dashboard:
name: Linux dashboard
runs-on: ubuntu-24.04
container: ubuntu:oracular
container: ubuntu:plucky
if: ${{ vars.APK_ONLY == '' }}
steps:
- uses: actions/checkout@v4
@@ -87,14 +87,8 @@ jobs:
- name: Install dependencies
run: >
apt-get update && apt-get install --yes libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev qt6-base-dev qt6-tools-dev libcap-dev pkexec libboost-all-dev librsvg2-bin libssl-dev libnotify-dev qt6-declarative-dev extra-cmake-modules libkirigami-dev libkf6i18n-dev libkf6coreaddons-dev libkf6qqc2desktopstyle-dev libkf6iconthemes-dev jq sudo cmake gcc g++ git qcoro-qt6-dev
apt-get update && apt-get install --yes libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev qt6-base-dev qt6-tools-dev libcap-dev pkexec libboost-all-dev librsvg2-bin libssl-dev libnotify-dev qt6-declarative-dev extra-cmake-modules libkirigami-dev libkf6i18n-dev libkf6coreaddons-dev libkf6qqc2desktopstyle-dev libkf6iconthemes-dev jq sudo cmake gcc g++ git qcoro-qt6-dev librsvg2-dev libarchive-dev libglm-dev glslang-tools
# runtime: qml6-module-qtqml-workerscript qml6-module-qtquick-dialogs
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944
with:
vulkan-query-version: 1.3.283.0
vulkan-components: Vulkan-Headers
vulkan-use-cache: true
- name: Configure CMake
run: >
@@ -124,7 +118,7 @@ jobs:
run: |
git config --global --add safe.directory $(pwd)
pip install toml aiohttp
tools/gen_flatpak_manifest.py --git https://github.com/${{github.repository}}.git --out flatpak
tools/gen_flatpak_manifest.py --gitlocal --out flatpak
cat flatpak/io.github.wivrn.wivrn.yml
- uses: flatpak/flatpak-github-actions/flatpak-builder@v6.4
@@ -153,14 +147,16 @@ jobs:
nix-test:
name: Test Nix package and devshell
runs-on: ubuntu-24.04
if: ${{ vars.APK_ONLY == '' }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: cachix/install-nix-action@v31
- run: nix flake check
- run: nix build
- run: nix build --print-build-logs
build-test-client:
name: Linux client
@@ -180,8 +176,8 @@ jobs:
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944
with:
vulkan-query-version: 1.3.283.0
vulkan-components: Vulkan-Headers
vulkan-query-version: 1.3.296.0
vulkan-components: Vulkan-Headers, Glslang, SPIRV-Tools
vulkan-use-cache: true
- name: Install dependencies
@@ -190,13 +186,14 @@ jobs:
- name: install server dependencies
run: >
sudo apt-get update && sudo apt-get install libavahi-glib-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev qt6-base-dev qt6-tools-dev libcap-dev pkexec libnotify-dev
sudo apt-get update && sudo apt-get install libavahi-glib-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev qt6-base-dev qt6-tools-dev libcap-dev pkexec libnotify-dev librsvg2-dev libarchive-dev
- name: Configure CMake
run: >
cmake -B ${{github.workspace}}/build
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
-DCMAKE_INSTALL_PREFIX=/usr
-DWIVRN_USE_SYSTEM_OPENXR=OFF
--preset everything
-DWIVRN_BUILD_DASHBOARD=OFF
-DWIVRN_BUILD_DISSECTOR=OFF
@@ -242,7 +239,7 @@ jobs:
WIVRN_SERVER_PID=$!
mkdir -p ~/.config/wivrn
echo '{"servers": [{"autoconnect": false, "manual": true, "pretty_name": "Deep Thought", "hostname": "localhost", "port": 9757, "tcp_only": false, "cookie": ""}]}' > ~/.config/wivrn/client.json.in
echo '{"servers": [{"autoconnect": false, "manual": true, "pretty_name": "Deep Thought", "hostname": "localhost", "port": 9757, "tcp_only": false, "cookie": ""}], "first_run": false}' > ~/.config/wivrn/client.json.in
for LANG in en $(basename -a ${{github.workspace}}/locale/*)
do
@@ -291,8 +288,8 @@ jobs:
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944
with:
vulkan-query-version: 1.3.268.0
vulkan-components: Vulkan-Headers
vulkan-query-version: 1.3.296.0
vulkan-components: Vulkan-Headers, Glslang, SPIRV-Tools
vulkan-use-cache: true
- name: Install dependencies
@@ -305,6 +302,7 @@ jobs:
-DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
-DCMAKE_INSTALL_PREFIX=/usr
--preset ${{ matrix.cmake_preset }}
-DWIVRN_USE_SYSTEM_OPENXR=OFF
- name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
@@ -324,6 +322,13 @@ jobs:
with:
fetch-depth: 0
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944
with:
vulkan-query-version: 1.3.296.0
vulkan-components: Glslang, SPIRV-Tools
vulkan-use-cache: true
- name: set up JDK
uses: actions/setup-java@v4
with:
@@ -457,7 +462,7 @@ jobs:
strategy:
fail-fast: false
matrix:
distro: ['oracular', 'plucky']
distro: ['plucky']
runs-on: ubuntu-24.04
container: ubuntu:${{ matrix.distro }}
steps:
@@ -465,7 +470,7 @@ jobs:
- name: Install dependencies
run: |
apt update
apt install --yes libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libavahi-glib-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev qt6-base-dev qt6-tools-dev libcap-dev pkexec libboost-all-dev librsvg2-bin dpkg-dev pkg-config debhelper-compat build-essential lintian cmake libnotify-dev qt6-declarative-dev extra-cmake-modules libkirigami-dev libkf6i18n-dev libkf6coreaddons-dev libkf6qqc2desktopstyle-dev libkf6iconthemes-dev jq sudo cmake gcc g++ git wget libssl-dev qcoro-qt6-dev
apt install --yes libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libavahi-glib-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev qt6-base-dev qt6-tools-dev libcap-dev pkexec libboost-all-dev librsvg2-bin dpkg-dev pkg-config debhelper-compat build-essential lintian cmake libnotify-dev qt6-declarative-dev extra-cmake-modules libkirigami-dev libkf6i18n-dev libkf6coreaddons-dev libkf6qqc2desktopstyle-dev libkf6iconthemes-dev jq sudo cmake gcc g++ git wget libssl-dev qcoro-qt6-dev librsvg2-dev libarchive-dev
- uses: actions/checkout@v4
with:
@@ -487,6 +492,13 @@ jobs:
patch -p1 --fuzz=0 --forward < "$p"
done
- name: Download stb
run: |
wget https://github.com/nothings/stb/archive/013ac3beddff3dbffafd5177e7972067cd2b5083.tar.gz -O stb.tar.gz
mkdir wivrn/stb-src
tar xzf stb.tar.gz --strip-components=1 -C wivrn/stb-src
- name: Edit changelog
working-directory: wivrn
run: >
@@ -574,7 +586,7 @@ jobs:
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
sudo apt-get install python-toml python-aiohttp
sudo apt-get install python3-toml python3-aiohttp
cd flathub
git remote add upstream https://github.com/flathub/io.github.wivrn.wivrn.git
+8 -4
View File
@@ -9,10 +9,14 @@ jobs:
- uses: actions/checkout@v4
- name: Install dependencies
run: sudo apt-get update && sudo apt-get install gettext qt6-base-dev qt6-tools-dev qt6-l10n-tools qtchooser python3-polib
run: |
sudo apt-get update && sudo apt-get install gettext
pip install polib PyGithub
- name: Check that .po files are up to date
run: |
qtchooser -install qt6 $(which qmake6)
export QT_SELECT=qt6
tools/check_messages.sh
if [[ "${{github.ref}}" == 'refs/heads/master' ]] ; then
tools/check_po.py --manage-issues --github-repository "${{ github.repository }}" --github-token "${{ github.token }}"
else
tools/check_po.py
fi
+42
View File
@@ -0,0 +1,42 @@
name: Sync Upstream
env:
UPSTREAM_URL: "https://github.com/wivrn/wivrn.git"
WORKFLOW_TOKEN: ${{ secrets.DOWNSTREAM_GITHUB_TOKEN }}
UPSTREAM_BRANCH: "master"
on:
schedule:
- cron: '0 5/6 * * *'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: GitHub Sync to Upstream Repository
uses: dabreadman/sync-upstream-repo@v1.3.0
with:
upstream_repo: ${{ env.UPSTREAM_URL }}
upstream_branch: ${{ env.UPSTREAM_BRANCH }}
token: ${{ env.WORKFLOW_TOKEN }}
- name: Checkout stuff
uses: actions/checkout@master
- name: Merge master -> apk-build
uses: devmasx/merge-branch@master
with:
type: now
from_branch: master
target_branch: apk-build
github_token: ${{ env.WORKFLOW_TOKEN }}
- name: Merge sneed -> apk-build
uses: devmasx/merge-branch@master
with:
type: now
from_branch: sneed
target_branch: apk-build
github_token: ${{ env.WORKFLOW_TOKEN }}
+3
View File
@@ -60,6 +60,7 @@
<uses-feature android:name="wave.feature.handtracking" android:required="false" />
<uses-feature android:name="wave.feature.eyetracking" android:required="false" />
<uses-feature android:name="wave.feature.lipexpression" android:required="false" />
<uses-feature android:name="wave.feature.tracker" android:required="false" />
<application
android:allowBackup="false"
@@ -87,6 +88,8 @@
<!-- https://developer.oculus.com/documentation/native/android/mobile-splash/ -->
<meta-data android:name="com.oculus.ossplash" android:value="true"/>
<!-- https://developers.meta.com/horizon/documentation/native/android/mobile-passthrough-loading-screens -->
<meta-data android:name="com.oculus.ossplash.background" android:value="passthrough-contextual"/>
<!-- The activity is the built-in NativeActivity framework class. -->
<!-- launchMode is set to singleTask because there should never be multiple copies of the app running. -->
+54 -98
View File
@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.25)
cmake_minimum_required(VERSION 3.28)
project(WiVRn VERSION 0.0.0 LANGUAGES C CXX)
# Set default for FetchContent projects
@@ -6,6 +6,7 @@ set(CMAKE_POLICY_DEFAULT_CMP0069 NEW)
set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
@@ -17,13 +18,12 @@ set(CMAKE_POSITION_INDEPENDENT_CODE ON)
include(FetchContent)
include(ExternalProject)
include(GNUInstallDirs)
include("cmake/AutoOption.cmake")
option(WIVRN_USE_SYSTEM_FREETYPE "Use system FreeType" ON)
auto_option(WIVRN_USE_SYSTEM_BOOST "Use system Boost headers" AUTO)
auto_option(WIVRN_USE_SYSTEM_OPENXR "Use system OpenXR headers" AUTO)
auto_option(WIVRN_USE_SYSTEMD "Use libsystemd" AUTO)
auto_option(WIVRN_USE_LIBKTX "Use libktx" AUTO)
option(WIVRN_USE_SYSTEM_BOOST "Use system Boost headers" ON)
option(WIVRN_USE_SYSTEM_OPENXR "Use system OpenXR headers" ON)
option(WIVRN_USE_SYSTEMD "Use libsystemd" ON)
option(WIVRN_USE_LIBKTX "Use libktx" ${ANDROID})
option(WIVRN_USE_ANDROID_VALIDATION_LAYER "Download the android version of the Vulkan validation layer" OFF)
option(WIVRN_BUILD_CLIENT "Build WiVRn client" OFF)
option(WIVRN_BUILD_SERVER "Build WiVRn server" ON)
@@ -31,17 +31,19 @@ option(WIVRN_BUILD_SERVER_LIBRARY "Build OpenXR library for WiVRn server" ${WIVR
option(WIVRN_BUILD_DASHBOARD "Build WiVRn dashboard" OFF)
option(WIVRN_BUILD_WIVRNCTL "Build wivrnctl" ON)
option(WIVRN_BUILD_DISSECTOR "Build Wireshark dissector" OFF)
option(WIVRN_BUILD_TEST "Build test binaries" OFF)
option(WIVRN_WERROR "Treat warnings as errors" OFF)
option(WIVRN_OPTIMIZE_SHADERS "Run siprv-opt on compiled shaders" ON)
option(WIVRN_USE_NVENC "Enable nvenc (Nvidia) hardware encoder" ON)
auto_option(WIVRN_USE_VAAPI "Enable vaapi (AMD/Intel) hardware encoder" AUTO)
auto_option(WIVRN_USE_VULKAN_ENCODE "Enable vulkan video encoder" AUTO)
auto_option(WIVRN_USE_X264 "Enable x264 software encoder" AUTO)
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)
auto_option(WIVRN_USE_PIPEWIRE "Enable pipewire backend" AUTO)
auto_option(WIVRN_USE_PULSEAUDIO "Enable pulseaudio backend" AUTO)
option(WIVRN_USE_PIPEWIRE "Enable pipewire backend" ON)
option(WIVRN_USE_PULSEAUDIO "Enable pulseaudio backend" OFF)
set(OVR_COMPAT_SEARCH_PATH "/usr/local/lib/OpenComposite:/usr/lib/OpenComposite:/opt/OpenComposite:/opt/opencomposite:/opt/xrizer"
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)
@@ -63,6 +65,12 @@ endif()
option(ENABLE_COLOURED_OUTPUT "Always produce ANSI-coloured output (GNU/Clang only)." ON)
if (WIVRN_BUILD_CLIENT OR WIVRN_BUILD_SERVER OR WIVRN_BUILD_DASHBOARD OR WIVRN_BUILD_DISSECTOR)
set(NEED_COMMON TRUE)
else()
set(NEED_COMMON FALSE)
endif()
if(ENABLE_COLOURED_OUTPUT)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
add_compile_options(-fdiagnostics-color=always)
@@ -74,19 +82,13 @@ endif()
find_package(PkgConfig REQUIRED)
find_package(Vulkan REQUIRED)
find_package(Git)
if (NOT ANDROID)
if (NEED_COMMON AND NOT ANDROID)
find_package(OpenSSL REQUIRED)
endif()
include(VulkanVersion)
if (WIVRN_USE_SYSTEM_BOOST STREQUAL "AUTO")
if(WIVRN_BUILD_DISSECTOR)
find_package(Boost 1.84.0 COMPONENTS locale url)
else()
find_package(Boost 1.75.0 COMPONENTS locale url)
endif()
elseif(WIVRN_USE_SYSTEM_BOOST STREQUAL "ON")
if(WIVRN_BUILD_DISSECTOR)
if (WIVRN_USE_SYSTEM_BOOST AND NEED_COMMON)
if (WIVRN_BUILD_DISSECTOR)
find_package(Boost 1.84.0 REQUIRED COMPONENTS locale url)
else()
find_package(Boost 1.75.0 REQUIRED COMPONENTS locale url)
@@ -103,72 +105,30 @@ if (WIVRN_BUILD_SERVER)
message(FATAL_ERROR "No encoder selected, use at least one of WIVRN_USE_NVENC, WIVRN_USE_VAAPI, WIVRN_USE_VULKAN_ENCODE or WIVRN_USE_X264")
endif()
if (WIVRN_USE_VAAPI STREQUAL "AUTO")
pkg_check_modules(LIBAV IMPORTED_TARGET libavcodec libavutil libswscale libavfilter)
pkg_check_modules(LIBDRM IMPORTED_TARGET libdrm)
if (LIBAV_FOUND AND LIBDRM_FOUND)
set(WIVRN_USE_VAAPI ON)
else()
set(WIVRN_USE_VAAPI OFF)
endif()
elseif (WIVRN_USE_VAAPI)
if (WIVRN_USE_VAAPI)
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET libavcodec libavutil libswscale libavfilter)
pkg_check_modules(LIBDRM REQUIRED IMPORTED_TARGET libdrm)
endif()
if (WIVRN_USE_VULKAN_ENCODE STREQUAL "AUTO")
if (Vulkan_VERSION VERSION_GREATER_EQUAL 1.3.283)
set(WIVRN_USE_VULKAN_ENCODE ON)
else()
set(WIVRN_USE_VULKAN_ENCODE OFF)
endif()
elseif(WIVRN_USE_VULKAN_ENCODE)
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 STREQUAL "AUTO")
pkg_check_modules(X264 IMPORTED_TARGET x264)
if (X264_FOUND)
set(WIVRN_USE_X264 ON)
else()
set(WIVRN_USE_X264 OFF)
endif()
elseif (WIVRN_USE_X264)
if (WIVRN_USE_X264)
pkg_check_modules(X264 REQUIRED IMPORTED_TARGET x264)
endif()
if (WIVRN_USE_SYSTEMD STREQUAL "AUTO")
pkg_check_modules(SYSTEMD IMPORTED_TARGET libsystemd)
if (SYSTEMD_FOUND)
set(WIVRN_USE_SYSTEMD ON)
else()
set(WIVRN_USE_SYSTEMD OFF)
endif()
elseif (WIVRN_USE_SYSTEMD)
if (WIVRN_USE_SYSTEMD)
pkg_check_modules(SYSTEMD REQUIRED IMPORTED_TARGET libsystemd)
endif()
if (WIVRN_USE_PIPEWIRE STREQUAL "AUTO")
pkg_check_modules(libpipewire IMPORTED_TARGET libpipewire-0.3)
if (libpipewire_FOUND)
set(WIVRN_USE_PIPEWIRE ON)
else()
set(WIVRN_USE_PIPEWIRE OFF)
endif()
elseif (WIVRN_USE_PIPEWIRE)
if (WIVRN_USE_PIPEWIRE)
pkg_check_modules(libpipewire REQUIRED IMPORTED_TARGET libpipewire-0.3)
endif()
if (WIVRN_USE_PULSEAUDIO STREQUAL "AUTO")
pkg_check_modules(libpulse IMPORTED_TARGET libpulse)
if (libpulse_FOUND)
set(WIVRN_USE_PULSEAUDIO ON)
else()
set(WIVRN_USE_PULSEAUDIO OFF)
endif()
elseif (WIVRN_USE_PULSEAUDIO)
if (WIVRN_USE_PULSEAUDIO)
pkg_check_modules(libpulse REQUIRED IMPORTED_TARGET libpulse)
endif()
@@ -182,6 +142,12 @@ if (WIVRN_BUILD_SERVER)
pkg_check_modules(libnotify REQUIRED IMPORTED_TARGET libnotify)
endif()
if (WIVRN_BUILD_DASHBOARD OR WIVRN_BUILD_SERVER)
pkg_check_modules(librsvg-2.0 REQUIRED IMPORTED_TARGET librsvg-2.0)
find_package(LibArchive REQUIRED)
find_package(PNG REQUIRED)
endif()
if (WIVRN_BUILD_DASHBOARD)
find_package(Qt6 REQUIRED COMPONENTS Core Quick Test Gui QuickControls2 Widgets Network)
@@ -208,23 +174,11 @@ if (WIVRN_BUILD_CLIENT OR WIVRN_BUILD_DASHBOARD)
find_package(Gettext REQUIRED)
endif()
if (WIVRN_BUILD_CLIENT)
if (WIVRN_USE_LIBKTX STREQUAL "AUTO")
if (ANDROID)
set(WIVRN_USE_LIBKTX ON)
else()
set(WIVRN_USE_LIBKTX OFF)
endif()
endif()
endif()
if (WIVRN_BUILD_CLIENT AND NOT ANDROID)
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET libavcodec libavutil libswscale libavfilter)
find_package(Fontconfig REQUIRED)
if (WIVRN_USE_SYSTEM_OPENXR STREQUAL "AUTO")
find_package(OpenXR 1.1.48)
elseif(WIVRN_USE_SYSTEM_OPENXR STREQUAL "ON")
if (WIVRN_USE_SYSTEM_OPENXR)
find_package(OpenXR 1.1.48 REQUIRED)
endif()
@@ -238,10 +192,8 @@ if(ANDROID)
endif()
if (WIVRN_BUILD_DISSECTOR)
if (WIVRN_USE_SYSTEM_OPENXR STREQUAL "AUTO")
find_package(OpenXR 1.0.34)
elseif(WIVRN_USE_SYSTEM_OPENXR STREQUAL "ON")
find_package(OpenXR 1.0.34 REQUIRED)
if (WIVRN_USE_SYSTEM_OPENXR)
find_package(OpenXR 1.1.48 REQUIRED)
endif()
find_package(Wireshark REQUIRED)
endif()
@@ -266,28 +218,30 @@ FetchContent_Declare(glm EXCLUDE_FROM_ALL SYSTEM URL https://github.co
URL_HASH SHA256=9f3174561fd26904b23f0db5e560971cbf9b3cbda0b280f04d5c379d03bf234c)
FetchContent_Declare(openxr_loader EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/OpenXR-SDK/archive/refs/tags/release-1.1.48.tar.gz
URL_HASH SHA256=c9372992dcdfac643e28796e41d4dbd36c4cdf0388d01fa89245628edae9d411)
FetchContent_Declare(spdlog EXCLUDE_FROM_ALL SYSTEM URL https://github.com/gabime/spdlog/archive/refs/tags/v1.14.1.tar.gz
URL_HASH SHA256=1586508029a7d0670dfcb2d97575dcdc242d3868a259742b69f100801ab4e16b)
FetchContent_Declare(spdlog EXCLUDE_FROM_ALL SYSTEM URL https://github.com/gabime/spdlog/archive/refs/tags/v1.15.3.tar.gz
URL_HASH SHA256=15a04e69c222eb6c01094b5c7ff8a249b36bb22788d72519646fb85feb267e67)
FetchContent_Declare(stb EXCLUDE_FROM_ALL SYSTEM URL https://github.com/nothings/stb/archive/013ac3beddff3dbffafd5177e7972067cd2b5083.zip
URL_HASH SHA256=b7f476902bbef1b30f8ecc2d9d95c459c32302c8b559d09b589b5955463b7af8)
FetchContent_Declare(libktx EXCLUDE_FROM_ALL SYSTEM
GIT_REPOSITORY https://github.com/KhronosGroup/KTX-Software
GIT_TAG 91ace88675ac59a97e55d0378a6602a9ae6b98bd)
FetchContent_Declare(implot EXCLUDE_FROM_ALL SYSTEM URL https://github.com/epezent/implot/archive/refs/tags/v0.16.tar.gz
URL_HASH SHA256=961df327d8a756304d1b0a67316eebdb1111d13d559f0d3415114ec0eb30abd1)
FetchContent_Declare(libktx EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/KTX-Software/archive/refs/tags/v4.4.0.tar.gz
URL_HASH SHA256=3585d76edcdcbe3a671479686f8c81c1c10339f419e4b02a9a6f19cc6e4e0612)
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.91.3.tar.gz
URL_HASH SHA256=29949d7b300c30565fbcd66398100235b63aa373acfee0b76853a7aeacd1be28
FetchContent_Declare(imgui EXCLUDE_FROM_ALL SYSTEM URL https://github.com/ocornut/imgui/archive/refs/tags/v1.92.1.tar.gz
URL_HASH SHA256=32c237c2abf67a2ffccaac17192f711d4a787554b4133187a153d49057d6109c
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/v3.15.0.tar.gz
URL_HASH SHA256=01466fcbf77618a79b62891510c0bbf25ac2804af5751c84982b413852234d66)
file(GLOB MONADO_PATCHES CONFIGURE_DEPENDS patches/monado/*)
file(READ monado-rev MONADO_REV)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS monado-rev)
file(STRINGS monado-rev MONADO_REV)
# Server dependencies
FetchContent_Declare(monado
GIT_REPOSITORY https://gitlab.freedesktop.org/monado/monado
GIT_REPOSITORY https://gitlab.freedesktop.org/monado/monado.git
# The flatpak manifest is updated automatically
GIT_TAG ${MONADO_REV}
PATCH_COMMAND ${CMAKE_CURRENT_LIST_DIR}/patches/apply.sh ${MONADO_PATCHES}
@@ -295,7 +249,9 @@ FetchContent_Declare(monado
)
add_subdirectory(external)
add_subdirectory(common)
if (NEED_COMMON)
add_subdirectory(common)
endif()
if (WIVRN_BUILD_CLIENT)
add_subdirectory(client)
+20 -8
View File
@@ -6,7 +6,7 @@
WiVRn wirelessly connects a standalone VR headset to a Linux computer. You can then play PCVR games on the headset while processing is done on the computer.
It supports a wide range of headsets such as Quest 1 / 2 / Pro / 3 / 3S, Pico Neo 4, HTC Vive Focus 3, HTC Vive XR elite and most other Android based headsets.
It supports a wide range of headsets such as Quest 1 / 2 / Pro / 3 / 3S, Pico Neo 3, Pico 4, HTC Vive Focus 3, HTC Vive XR elite and most other Android based headsets.
# Getting started
@@ -41,8 +41,8 @@ Avahi must be running:
systemctl enable --now avahi-daemon
```
If a firewall is installed, open port 5353/UDP for avahi.
Open ports 9757/UDP+TCP for WiVRn itself.
- If a firewall is installed, open port 5353/UDP for avahi and ports 9757/UDP+TCP for WiVRn itself.
- In the case of ufw, use `ufw allow 5353/udp` and `ufw allow 9757`.
### Running
- On your computer, run "WiVRn server" application, or `wivrn-dashboard` from the command line, it will show the connection wizard the first time you launch it.
@@ -109,7 +109,7 @@ If the server list is empty in the headset app:
## My headset does not connect to my computer
- If you have a firewall, check that port 9757 (UDP and TCP) is open
- The server and client must be compatible:
- The server and client must be compatible.
## How do I use a wired connection?
@@ -129,9 +129,20 @@ If the server list is empty in the headset app:
## How do I see server logs when using the dashboard?
```
journalctl -f --no-hostname -u io.github.wivrn.wivrn.desktop
```
- 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`.
## I have high motion latency, black borders following my view, hear corrupted audio or see a corrupted, pixelated image
- When connecting through USB, make sure the headset isn't connected through WiFi (switch off WiFi)
- Reset the settings using the button at the bottom of the settings tab
- Try switching to software encoding
- Decrease the bitrate
- Decrease the resolution in the WiVRn app
- Connect through USB or use a better WiFi router.
Note: WiVRn isn't properly optimized for NVIDIA GPUs due to the lack of developers with NVIDIA hardware. Motion latency may be significantly worse at rendering resolutions higher than default.
# Contributing
@@ -153,8 +164,9 @@ WiVRn uses the following software:
- [FreeType](https://freetype.org/)
- [glm](http://glm.g-truc.net/)
- [HarfBuzz](https://harfbuzz.github.io/)
- [librsvg](https://wiki.gnome.org/Projects/LibRsvg)
- [Monado](https://monado.freedesktop.org/)
- [nvenc](https://developer.nvidia.com/nvidia-video-codec-sdk) optional, for hardware encoding on Nvidia
- [nvenc](https://developer.nvidia.com/nvidia-video-codec-sdk) optional, for hardware encoding on NVIDIA
- [qCoro](https://qcoro.dev/)
- [Qt 6](https://www.qt.io/) optional, for the dashboard
- [spdlog](https://github.com/gabime/spdlog)
Binary file not shown.

After

Width:  |  Height:  |  Size: 930 B

-32
View File
@@ -1,32 +0,0 @@
Snapdragon(TM) Game Super Resolution
Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved.
https://github.com/SnapdragonStudios/snapdragon-gsr
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
SPDX-License-Identifier: BSD-3-Clause
+90 -32
View File
@@ -4,7 +4,7 @@ buildscript {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.7.3'
classpath 'com.android.tools.build:gradle:8.12.1'
}
}
@@ -17,45 +17,86 @@ allprojects {
apply plugin: 'com.android.application'
task "generatePngs"() {
group = 'Custom'
mkdir layout.buildDirectory.dir('generated_resources')
["mipmap-mdpi", "mipmap-hdpi", "mipmap-xhdpi", "mipmap-xxhdpi", "mipmap-xxxhdpi", ].each {
mkdir layout.buildDirectory.dir("generated_resources/${it}")
}
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.*
import org.gradle.api.file.DirectoryProperty
import org.gradle.process.ExecOperations
def css = project.hasProperty('wivrn_css') ? project.wivrn_css: "images/wivrn-local.css"
abstract class GeneratePngsTask extends DefaultTask {
@Inject
abstract ExecOperations getExecOps()
exec {
executable = 'rsvg-convert'
args = [ "images/wivrn.svg", "-w", "48", "-h", "48", "-o", layout.buildDirectory.file('generated_resources/mipmap-mdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ]
}
@InputFile
abstract RegularFileProperty getSvg()
exec {
executable = 'rsvg-convert'
args = [ "images/wivrn.svg", "-w", "72", "-h", "72", "-o", layout.buildDirectory.file('generated_resources/mipmap-hdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ]
}
@InputFile
@Optional
abstract RegularFileProperty getCss()
exec {
executable = 'rsvg-convert'
args = [ "images/wivrn.svg", "-w", "96", "-h", "96", "-o", layout.buildDirectory.file('generated_resources/mipmap-xhdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ]
}
@OutputDirectory
abstract DirectoryProperty getOutputDir()
exec {
executable = 'rsvg-convert'
args = [ "images/wivrn.svg", "-w", "144", "-h", "144", "-o", layout.buildDirectory.file('generated_resources/mipmap-xxhdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ]
}
@TaskAction
void generate() {
def outDir = getOutputDir().get().asFile
outDir.mkdirs()
exec {
executable = 'rsvg-convert'
args = [ "images/wivrn.svg", "-w", "192", "-h", "192", "-o", layout.buildDirectory.file('generated_resources/mipmap-xxxhdpi/ic_wivrn_launcher.png').get().asFile, '--stylesheet=' + css ]
// Map of density → size
def dpiConfigs = [
"mipmap-mdpi" : 48,
"mipmap-hdpi" : 72,
"mipmap-xhdpi" : 96,
"mipmap-xxhdpi" : 144,
"mipmap-xxxhdpi": 192
]
def cssFile = getCss().isPresent() ? getCss().get().asFile : null
dpiConfigs.each { dpi, size ->
def dpiDir = new File(outDir, dpi)
dpiDir.mkdirs()
def outputFile = new File(dpiDir, "ic_wivrn_launcher.png")
def argsList = [
getSvg().get().asFile.absolutePath,
"-w", size.toString(),
"-h", size.toString(),
"-o", outputFile.absolutePath
]
if (cssFile != null) {
argsList.add("--stylesheet=${cssFile.absolutePath}")
}
execOps.exec {
executable = "rsvg-convert"
args = argsList
}
}
}
}
tasks.register("generatePngs", GeneratePngsTask) {
group = "Custom"
// configure defaults
svg.set(layout.projectDirectory.file("images/wivrn.svg"))
outputDir.set(layout.buildDirectory.dir("generated_resources"))
if (project.hasProperty("wivrn_css")) {
css.set(layout.projectDirectory.file(project.wivrn_css))
} else {
css.set(layout.projectDirectory.file("images/wivrn-local.css"))
}
}
android {
namespace "org.meumeu.wivrn"
ndkVersion "27.1.12297006"
namespace = "org.meumeu.wivrn"
ndkVersion = "28.1.13356709"
lint {
disable += "ExpiredTargetSdkVersion"
@@ -72,6 +113,7 @@ android {
versionName = project.hasProperty('wivrn_version') ? wivrn_version : "1.0"
versionCode = project.hasProperty('wivrn_versionCode') ? wivrn_versionCode.toInteger() : 1
def showImguiDemo = project.hasProperty('wivrn_show_imgui_demo') ? wivrn_show_imgui_demo : 'OFF'
def showDebugMenu = project.hasProperty('wivrn_show_debug_menu') ? wivrn_show_debug_menu : 'OFF'
externalNativeBuild {
def css = project.hasProperty('wivrn_css') ? project.wivrn_css: "images/wivrn-local.css"
@@ -82,6 +124,7 @@ android {
'-DCMAKE_ANDROID_NDK_VERSION=' + ndkVersion,
'-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON',
'-DCMAKE_EXPORT_COMPILE_COMMANDS=ON',
'-DWIVRN_USE_SYSTEM_BOOST=OFF',
'-DWIVRN_USE_SYSTEM_FREETYPE=OFF',
'-DWIVRN_BUILD_CLIENT=ON',
'-DWIVRN_BUILD_SERVER=OFF',
@@ -90,6 +133,7 @@ android {
'-DWIVRN_BUILD_DASHBOARD=OFF',
'-DWIVRN_WERROR=ON',
'-DWIVRN_SHOW_IMGUI_DEMO_WINDOW=' + showImguiDemo,
'-DWIVRN_CLIENT_DEBUG_MENU=' + showDebugMenu,
'-DWIVRN_CSS=' + css
resValue "string", "app_name", project.hasProperty('wivrn_app_name') ? project.wivrn_app_name : "WiVRn Local"
}
@@ -103,7 +147,7 @@ android {
keyAlias "default_key"
storePassword signingKeyPassword // Set in gradle.properties
keyPassword signingKeyPassword
enableV2Signing true
enableV2Signing = true
}
}
}
@@ -111,7 +155,7 @@ android {
buildTypes {
if (project.hasProperty("signingKeyPassword")) {
release {
signingConfig signingConfigs.release
signingConfig = signingConfigs.release
}
}
@@ -180,7 +224,7 @@ android {
externalNativeBuild {
cmake {
version '3.30.3'
version = '3.30.3'
path 'CMakeLists.txt'
}
}
@@ -205,4 +249,18 @@ android {
}
}
}
buildTypes.all { variant ->
sourceSets {
"${variant.name}" {
jniLibs.srcDirs layout.buildDirectory.dir("libs${variant.name.capitalize()}")
}
}
externalNativeBuild{
cmake {
arguments '-DCMAKE_ANDROID_LIB_DIRECTORIES=' + layout.buildDirectory.dir("libs${variant.name.capitalize()}").get().asFile
}
}
}
}
+33 -18
View File
@@ -7,13 +7,13 @@ set(KTX_FEATURE_LOADTEST_APPS OFF)
set(FASTGLTF_COMPILE_AS_CPP20 ON)
FetchContent_MakeAvailable(simdjson spdlog glm fastgltf imgui stb implot uni-algo)
FetchContent_MakeAvailable(simdjson spdlog glm fastgltf imgui stb implot uni-algo entt)
if (WIVRN_USE_LIBKTX)
FetchContent_MakeAvailable(libktx)
endif()
if (NOT BOOST_FOUND)
if (NOT WIVRN_USE_SYSTEM_BOOST)
FetchContent_MakeAvailable(boost)
endif()
@@ -51,7 +51,7 @@ if(ANDROID)
else()
add_executable(wivrn)
if (OpenXR_FOUND)
if (WIVRN_USE_SYSTEM_OPENXR)
target_link_libraries(wivrn OpenXR::openxr_loader OpenXR::headers)
else()
FetchContent_MakeAvailable(openxr_loader)
@@ -89,9 +89,24 @@ file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS
file(GLOB_RECURSE VULKAN_SHADERS CONFIGURE_DEPENDS "*.glsl")
target_sources(wivrn PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS})
wivrn_compile_glsl(wivrn ${VULKAN_SHADERS})
wivrn_compile_glsl(wivrn SHADERS ${VULKAN_SHADERS})
target_link_libraries(wivrn Vulkan::Vulkan spdlog::spdlog glm::glm fastgltf FreetypeHarfbuzz stb Boost::url Boost::locale)
target_link_libraries(wivrn
Boost::locale
Boost::url
EnTT::EnTT
fastgltf
FreetypeHarfbuzz
glm::glm
imspinner
simdjson
spdlog::spdlog
stb
uni-algo
Vulkan::Vulkan
wivrn-common
wivrn-external
)
if (WIVRN_USE_LIBKTX)
target_link_libraries(wivrn ktx_read)
@@ -107,10 +122,6 @@ if(NOT ANDROID)
install(TARGETS wivrn)
endif()
target_link_libraries(wivrn simdjson uni-algo wivrn-common wivrn-external)
##############################################################################
# Dear ImGui
#
@@ -155,14 +166,14 @@ khronos_validation.enables = VK_VALIDATION_FEATURE_ENABLE_THREAD_SAFETY_EXT
endif()
if(USE_ANDROID_VALIDATION_LAYER)
set(VVL_VERSION "1.3.231.1")
set(VVL_VERSION "1.4.321.0")
if(NOT EXISTS ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip)
if (EXISTS ${CMAKE_SOURCE_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip)
file(CREATE_LINK ${CMAKE_SOURCE_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip SYMBOLIC)
else()
file(DOWNLOAD https://github.com/KhronosGroup/Vulkan-ValidationLayers/releases/download/sdk-${VVL_VERSION}/android-binaries-${VVL_VERSION}.zip ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip
EXPECTED_HASH SHA256=eec3a54222d6d33d4f787a13a45c60ac5b9e8d7bf795fc41e4242354a02e34ba)
file(DOWNLOAD https://github.com/KhronosGroup/Vulkan-ValidationLayers/releases/download/vulkan-sdk-${VVL_VERSION}/android-binaries-${VVL_VERSION}.zip ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip
EXPECTED_HASH SHA256=75f2881ba7af0507c8cec13b4bf6c95556c6333485cdb8be41f608fccf762128)
endif()
endif()
@@ -170,12 +181,12 @@ if(USE_ANDROID_VALIDATION_LAYER)
file(ARCHIVE_EXTRACT INPUT ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayers-${VVL_VERSION}.zip DESTINATION ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayer)
add_library(vvl1 SHARED IMPORTED)
set_property(TARGET vvl1 PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayer/${CMAKE_ANDROID_ARCH_ABI}/libVkLayer_khronos_validation.so)
add_library(vvl2 SHARED IMPORTED)
set_property(TARGET vvl2 PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/Vulkan-ValidationLayer/${CMAKE_ANDROID_ARCH_ABI}/libc++_shared.so)
target_link_libraries(wivrn vvl1 vvl2) # Hack to get gradle to package the validation layer in the APK
file(COPY
${CMAKE_BINARY_DIR}/Vulkan-ValidationLayer/android-binaries-${VVL_VERSION}/${CMAKE_ANDROID_ARCH_ABI}
DESTINATION ${CMAKE_ANDROID_LIB_DIRECTORIES})
else()
# silence "Manually-specified variables were not used by the project" warning
set(_unused ${CMAKE_ANDROID_LIB_DIRECTORIES})
endif()
@@ -245,6 +256,10 @@ if(ANDROID)
COMMAND ${TOKTX} --encode astc --astc_blk_d 4x4 --astc_quality 100 --genmipmap ${ASSETS_DIR}/wivrn-pride.ktx2 ${ASSETS_DIR}/wivrn-pride.png
DEPENDS ${ASSETS_DIR}/wivrn-pride.png)
add_custom_command(OUTPUT ${ASSETS_DIR}/default_icon.ktx2
COMMAND ${TOKTX} --encode astc --astc_blk_d 4x4 --astc_quality 100 --genmipmap ${ASSETS_DIR}/wivrn-pride.ktx2 ${ASSETS_DIR}/default_icon.png
DEPENDS ${ASSETS_DIR}/default_icon.png)
add_custom_command(OUTPUT ${ASSETS_DIR}/WoodFloor051_1K-JPG_Color.ktx2
COMMAND ${TOKTX} --encode astc --astc_blk_d 12x12 --astc_quality 100 --genmipmap ${ASSETS_DIR}/WoodFloor051_1K-JPG_Color.ktx2 ${AST_SRC_DIR}/WoodFloor051_1K-JPG_Color.jpg
DEPENDS ${AST_SRC_DIR}/WoodFloor051_1K-JPG_Color.jpg)
+317 -238
View File
@@ -18,7 +18,7 @@
*/
#include "application.h"
#include "asset.h"
#include "hardware.h"
#include "openxr/openxr.h"
#include "scene.h"
@@ -26,19 +26,22 @@
#include "spdlog/spdlog.h"
#include "utils/contains.h"
#include "utils/files.h"
#include "utils/named_thread.h"
#include "utils/i18n.h"
#include "vk/check.h"
#include "wifi_lock.h"
#include "xr/actionset.h"
#include "xr/check.h"
#include "xr/htc_exts.h"
#include "xr/htc_face_tracker.h"
#include "xr/meta_body_tracking_fidelity.h"
#include "xr/xr.h"
#include "xr/to_string.h"
#include <algorithm>
#include <boost/locale.hpp>
#include <boost/url/parse.hpp>
#include <chrono>
#include <ctype.h>
#include <exception>
#include <magic_enum.hpp>
#include <string>
#include <thread>
#include <vector>
@@ -51,6 +54,7 @@
#endif
#ifdef __ANDROID__
#include "utils/named_thread.h"
#include <android/native_activity.h>
#include <sys/system_properties.h>
@@ -66,15 +70,15 @@ struct interaction_profile
{
std::string profile_name;
std::vector<std::string> required_extensions;
XrVersion min_version = XR_MAKE_VERSION(1, 0, 0);
std::vector<std::string> input_sources;
bool available;
};
static std::vector<interaction_profile> interaction_profiles{
interaction_profile{
"/interaction_profiles/khr/simple_controller",
{},
{
.profile_name = "/interaction_profiles/khr/simple_controller",
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -90,11 +94,11 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/menu/click",
"/user/hand/right/input/select/click",
}},
},
},
interaction_profile{
"/interaction_profiles/oculus/touch_controller",
{},
{
.profile_name = "/interaction_profiles/oculus/touch_controller",
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -129,11 +133,12 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/thumbstick/click",
"/user/hand/right/input/thumbstick/touch",
"/user/hand/right/input/thumbrest/touch",
}},
},
},
interaction_profile{
" /interaction_profiles/facebook/touch_controller_pro",
{"XR_FB_touch_controller_pro"},
{
.profile_name = "/interaction_profiles/facebook/touch_controller_pro",
.required_extensions = {XR_FB_TOUCH_CONTROLLER_PRO_EXTENSION_NAME},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/left/output/haptic_trigger_fb",
"/user/hand/left/output/haptic_thumb_fb",
@@ -171,6 +176,7 @@ static std::vector<interaction_profile> interaction_profiles{
"/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/trigger/value",
"/user/hand/right/input/trigger/touch",
"/user/hand/right/input/thumbstick",
@@ -183,11 +189,12 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/trigger/slide_fb",
"/user/hand/right/input/trigger/proximity_fb",
"/user/hand/right/input/thumb_fb/proximity_fb",
}},
},
},
interaction_profile{
" /interaction_profiles/meta/touch_pro_controller",
{"XR_VERSION_1_1"},
{
.profile_name = "/interaction_profiles/meta/touch_pro_controller",
.min_version = XR_MAKE_VERSION(1, 1, 0),
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/left/output/haptic_trigger",
"/user/hand/left/output/haptic_thumb",
@@ -238,12 +245,12 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/thumbrest/touch",
"/user/hand/right/input/thumbrest/force",
"/user/hand/right/input/stylus/force",
}},
},
},
interaction_profile{
" /interaction_profiles/meta/touch_controller_plus",
{"XR_META_touch_controller_plus"},
{
.profile_name = "/interaction_profiles/meta/touch_controller_plus",
.required_extensions = {XR_META_TOUCH_CONTROLLER_PLUS_EXTENSION_NAME},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -287,11 +294,12 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/trigger/slide_meta",
"/user/hand/right/input/trigger/force",
}},
},
},
interaction_profile{
" /interaction_profiles/meta/touch_plus_controller",
{"XR_VERSION_1_1"},
{
.profile_name = "/interaction_profiles/meta/touch_plus_controller",
.min_version = XR_MAKE_VERSION(1, 1, 0),
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -337,11 +345,12 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/thumbstick/touch",
"/user/hand/right/input/thumbrest/touch",
}},
},
},
interaction_profile{
"/interaction_profiles/bytedance/pico_neo3_controller",
{"XR_BD_controller_interaction"},
{
.profile_name = "/interaction_profiles/bytedance/pico_neo3_controller",
.required_extensions = {XR_BD_CONTROLLER_INTERACTION_EXTENSION_NAME},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -379,11 +388,12 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/thumbstick/click",
"/user/hand/right/input/thumbstick/touch",
}},
},
},
interaction_profile{
"/interaction_profiles/bytedance/pico4_controller",
{"XR_BD_controller_interaction"},
{
.profile_name = "/interaction_profiles/bytedance/pico4_controller",
.required_extensions = {XR_BD_CONTROLLER_INTERACTION_EXTENSION_NAME},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -421,11 +431,12 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/thumbstick/touch",
"/user/hand/right/input/squeeze/click",
"/user/hand/right/input/squeeze/value",
}},
},
},
interaction_profile{
"/interaction_profiles/bytedance/pico4s_controller",
{"XR_BD_controller_interaction"},
{
.profile_name = "/interaction_profiles/bytedance/pico4s_controller",
.required_extensions = {XR_BD_CONTROLLER_INTERACTION_EXTENSION_NAME},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -463,11 +474,12 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/thumbstick/touch",
"/user/hand/right/input/squeeze/click",
"/user/hand/right/input/squeeze/value",
}},
},
},
interaction_profile{
"/interaction_profiles/htc/vive_focus3_controller",
{"XR_HTC_vive_focus3_controller_interaction"},
{
.profile_name = "/interaction_profiles/htc/vive_focus3_controller",
.required_extensions = {XR_HTC_VIVE_FOCUS3_CONTROLLER_INTERACTION_EXTENSION_NAME},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -504,13 +516,51 @@ static std::vector<interaction_profile> interaction_profiles{
"/user/hand/right/input/thumbstick/click",
"/user/hand/right/input/thumbstick/touch",
"/user/hand/right/input/thumbrest/touch",
}},
},
},
interaction_profile{
"/interaction_profiles/ext/eye_gaze_interaction",
{"XR_EXT_eye_gaze_interaction"},
{
.profile_name = "/interaction_profiles/ext/hand_interaction_ext",
.required_extensions = {XR_EXT_HAND_INTERACTION_EXTENSION_NAME},
.input_sources = {
"/user/hand/left/input/aim/pose",
"/user/hand/left/input/grip/pose",
"/user/hand/left/input/pinch_ext/pose",
"/user/hand/left/input/pinch_ext/value",
"/user/hand/left/input/pinch_ext/ready_ext",
"/user/hand/left/input/poke_ext/pose",
"/user/hand/left/input/aim_activate_ext/value",
"/user/hand/left/input/aim_activate_ext/ready_ext",
"/user/hand/left/input/grasp_ext/value",
"/user/hand/left/input/grasp_ext/ready_ext",
"/user/hand/right/input/aim/pose",
"/user/hand/right/input/grip/pose",
"/user/hand/right/input/pinch_ext/pose",
"/user/hand/right/input/pinch_ext/value",
"/user/hand/right/input/pinch_ext/ready_ext",
"/user/hand/right/input/poke_ext/pose",
"/user/hand/right/input/aim_activate_ext/value",
"/user/hand/right/input/aim_activate_ext/ready_ext",
"/user/hand/right/input/grasp_ext/value",
"/user/hand/right/input/grasp_ext/ready_ext",
},
},
interaction_profile{
.profile_name = "/interaction_profiles/htc/vive_xr_tracker",
.required_extensions = {
XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME,
XR_HTC_PATH_ENUMERATION_EXTENSION_NAME,
},
},
interaction_profile{
.profile_name = "/interaction_profiles/ext/eye_gaze_interaction",
.required_extensions = {XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME},
.input_sources = {
"/user/eyes_ext/input/gaze_ext/pose",
}},
},
},
};
static const std::pair<std::string_view, XrActionType> action_suffixes[] =
@@ -539,6 +589,9 @@ static const std::pair<std::string_view, XrActionType> action_suffixes[] =
{"/joystick", XR_ACTION_TYPE_VECTOR2F_INPUT},
{"/trackball", XR_ACTION_TYPE_VECTOR2F_INPUT},
// XR_EXT_hand_interaction
{"/ready_ext", XR_ACTION_TYPE_BOOLEAN_INPUT},
// Output paths
{"/haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"/haptic_trigger", XR_ACTION_TYPE_VIBRATION_OUTPUT},
@@ -600,6 +653,7 @@ VkBool32 application::vulkan_debug_report_callback(
}
#ifndef NDEBUG
bool my_error = true;
if (level >= spdlog::level::warn)
{
bool validation_layer_found = false;
@@ -610,10 +664,13 @@ VkBool32 application::vulkan_debug_report_callback(
if (validation_layer_found && i.library != "libVkLayer_khronos_validation.so")
spdlog::log(level, "{:#016x}: {} + {:#x}", i.pc, i.library, i.pc - i.library_base);
if (i.library == "libopenxr_loader.so")
my_error = false;
}
}
if (level >= spdlog::level::err)
if (level >= spdlog::level::err and my_error)
abort();
#endif
@@ -668,45 +725,45 @@ void application::initialize_vulkan()
spdlog::info("Using Vulkan validation layer");
layers.push_back("VK_LAYER_KHRONOS_validation");
}
bool debug_report_found = false;
bool debug_utils_found = false;
#endif
std::vector<const char *> instance_extensions{};
std::unordered_set<std::string_view> optional_device_extensions{};
#ifndef NDEBUG
bool debug_report_found = false;
bool debug_utils_found = false;
#endif
spdlog::info("Available Vulkan instance extensions:");
std::vector<std::pair<std::string, int>> extensions;
for (vk::ExtensionProperties & i: vk_context.enumerateInstanceExtensionProperties(nullptr))
{
spdlog::info(" {} (version {})", i.extensionName.data(), i.specVersion);
extensions.emplace_back(i.extensionName.data(), i.specVersion);
#ifndef NDEBUG
if (!strcmp(i.extensionName, VK_EXT_DEBUG_REPORT_EXTENSION_NAME))
{
debug_report_found = true;
instance_extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
}
if (!strcmp(i.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME))
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
}
#ifndef NDEBUG
if (debug_utils_found && debug_report_found)
{
// debug_extensions_found = true;
// spdlog::info("Using debug extensions");
instance_extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
// 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);
optional_device_extensions.emplace(VK_IMG_FILTER_CUBIC_EXTENSION_NAME);
optional_device_extensions.emplace(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
#ifdef __ANDROID__
vk_device_extensions.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
vk_device_extensions.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
vk_device_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
vk_device_extensions.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
vk_device_extensions.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);
@@ -768,11 +825,16 @@ void application::initialize_vulkan()
vk_physical_device = xr_system_id.physical_device(vk_instance);
physical_device_properties = vk_physical_device.getProperties();
spdlog::info("Available Vulkan device extensions:");
extensions.clear();
for (vk::ExtensionProperties & i: vk_physical_device.enumerateDeviceExtensionProperties())
extensions.emplace_back(i.extensionName.data(), i.specVersion);
std::ranges::sort(extensions);
spdlog::info("Available Vulkan device extensions:");
for (const auto & [extension_name, spec_version]: extensions)
{
spdlog::info(" {}", i.extensionName.data());
if (auto it = optional_device_extensions.find(i.extensionName); it != optional_device_extensions.end())
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());
}
@@ -816,16 +878,27 @@ void application::initialize_vulkan()
.ppEnabledExtensionNames = vk_device_extensions.data(),
.pEnabledFeatures = &device_features,
},
#ifdef __ANDROID__
vk::PhysicalDeviceSamplerYcbcrConversionFeaturesKHR{
.samplerYcbcrConversion = VK_TRUE,
.samplerYcbcrConversion = true,
},
vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR{
.timelineSemaphore = true,
},
#endif
};
vk_device = xr_system_id.create_device(vk_physical_device, device_create_info.get());
if (utils::contains(vk_device_extensions, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME))
{
auto [_, feat] = vk_physical_device.getFeatures2<vk::PhysicalDeviceFeatures2, vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR>();
auto & create_feat = device_create_info.get<vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR>();
create_feat.timelineSemaphore = feat.timelineSemaphore;
}
else
{
device_create_info.unlink<vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR>();
}
vk_queue = vk_device.getQueue(vk_queue_family_index, 0);
vk_device = xr_system_id.create_device(vk_physical_device, device_create_info.get());
*vk_queue.lock() = vk_device.getQueue(vk_queue_family_index, 0);
vk::PipelineCacheCreateInfo pipeline_cache_info;
std::vector<std::byte> pipeline_cache_bytes;
@@ -845,10 +918,16 @@ void application::initialize_vulkan()
pipeline_cache = vk::raii::PipelineCache(vk_device, pipeline_cache_info);
allocator.emplace(VmaAllocatorCreateInfo{
.physicalDevice = *vk_physical_device,
.device = *vk_device,
.instance = *vk_instance,
});
.physicalDevice = *vk_physical_device,
.device = *vk_device,
.instance = *vk_instance,
},
#ifndef NDEBUG
debug_utils_found
#else
false
#endif
);
}
void application::log_views()
@@ -902,23 +981,83 @@ void application::initialize_actions()
std::unordered_map<std::string, std::vector<XrActionSuggestedBinding>> suggested_bindings;
XrVersion api_version = xr_instance.get_api_version();
// Build the list of all possible input sources, without duplicates,
// checking which profiles are supported by the runtime
std::vector<std::string> sources;
for (auto & profile: interaction_profiles)
{
profile.available = utils::contains_all(xr_extensions, profile.required_extensions);
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"))
{
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;
// Patch profile to add palm_ext
if (utils::contains(xr_extensions, XR_EXT_PALM_POSE_EXTENSION_NAME) //
and utils::contains(profile.input_sources, "/user/hand/left/input/grip/pose") //
and not utils::contains(profile.input_sources, "/user/hand/left/input/palm_ext/pose"))
// Patch profile to add grip_surface or palm_ext
bool add_palms = true;
if (profile.profile_name.ends_with("ext/hand_interaction_ext"))
{
profile.input_sources.push_back("/user/hand/left/input/palm_ext/pose");
profile.input_sources.push_back("/user/hand/right/input/palm_ext/pose");
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)) //
and utils::contains(profile.input_sources, "/user/hand/left/input/grip/pose") //
and not utils::contains(profile.input_sources, "/user/hand/left/input/grip_surface/pose"))
{
spdlog::info("Adding grip_surface/pose for interaction profile {}", profile.profile_name);
profile.input_sources.push_back("/user/hand/left/input/grip_surface/pose");
profile.input_sources.push_back("/user/hand/right/input/grip_surface/pose");
}
else if (xr_instance.has_extension(XR_EXT_PALM_POSE_EXTENSION_NAME) //
and utils::contains(profile.input_sources, "/user/hand/left/input/grip/pose") //
and not utils::contains(profile.input_sources, "/user/hand/left/input/palm_ext/pose"))
{
spdlog::info("Adding palm_ext/pose for interaction profile {}", profile.profile_name);
profile.input_sources.push_back("/user/hand/left/input/palm_ext/pose");
profile.input_sources.push_back("/user/hand/right/input/palm_ext/pose");
}
}
// Dynamically add VIVE XR Trackers to the profile if available
if (utils::contains(profile.required_extensions, XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME) and
xr_instance.has_extension(XR_HTC_PATH_ENUMERATION_EXTENSION_NAME))
{
XrPath tracker_profile = xr_instance.string_to_path("/interaction_profiles/htc/vive_xr_tracker");
for (const auto & user_path: xr_instance.enumerate_paths_for_interaction_profile(tracker_profile))
{
generic_trackers.emplace_back(user_path, nullptr);
for (const auto & input_path: xr_instance.enumerate_paths_for_interaction_profile(tracker_profile, user_path))
profile.input_sources.push_back(xr_instance.path_to_string(user_path) + xr_instance.path_to_string(input_path));
}
}
suggested_bindings.emplace(profile.profile_name, std::vector<XrActionSuggestedBinding>{});
@@ -947,16 +1086,32 @@ void application::initialize_actions()
spaces[size_t(xr::spaces::grip_left)] = xr_session.create_action_space(a);
else if (name == "/user/hand/left/input/aim/pose")
spaces[size_t(xr::spaces::aim_left)] = xr_session.create_action_space(a);
else if (name == "/user/hand/left/input/palm_ext/pose" or name == "/user/hand/left/input/grip_surface/pose")
spaces[size_t(xr::spaces::palm_left)] = xr_session.create_action_space(a);
else if (name == "/user/hand/left/input/pinch_ext/pose")
spaces[size_t(xr::spaces::pinch_left)] = xr_session.create_action_space(a);
else if (name == "/user/hand/left/input/poke_ext/pose")
spaces[size_t(xr::spaces::poke_left)] = xr_session.create_action_space(a);
else if (name == "/user/hand/right/input/grip/pose")
spaces[size_t(xr::spaces::grip_right)] = xr_session.create_action_space(a);
else if (name == "/user/hand/right/input/aim/pose")
spaces[size_t(xr::spaces::aim_right)] = xr_session.create_action_space(a);
else if (name == "/user/hand/right/input/palm_ext/pose" or name == "/user/hand/right/input/grip_surface/pose")
spaces[size_t(xr::spaces::palm_right)] = xr_session.create_action_space(a);
else if (name == "/user/hand/right/input/pinch_ext/pose")
spaces[size_t(xr::spaces::pinch_right)] = xr_session.create_action_space(a);
else if (name == "/user/hand/right/input/poke_ext/pose")
spaces[size_t(xr::spaces::poke_right)] = xr_session.create_action_space(a);
else if (name == "/user/eyes_ext/input/gaze_ext/pose")
spaces[size_t(xr::spaces::eye_gaze)] = xr_session.create_action_space(a);
else if (name == "/user/hand/right/input/palm_ext/pose")
spaces[size_t(xr::spaces::palm_right)] = xr_session.create_action_space(a);
else if (name == "/user/hand/left/input/palm_ext/pose")
spaces[size_t(xr::spaces::palm_left)] = xr_session.create_action_space(a);
else if (name.contains("/input/entity_htc/pose"))
{
for (auto & [path, action]: generic_trackers)
{
if (name.starts_with(xr_instance.path_to_string(path)))
action = xr_session.create_action_space(a);
}
}
}
// Build an action set for each scene
@@ -978,20 +1133,23 @@ void application::initialize_actions()
for (const scene::suggested_binding & j: i->bindings)
{
// Skip unsupported profiles
if (!suggested_bindings.contains(j.profile_name))
continue;
std::vector<XrActionSuggestedBinding> & xr_bindings = suggested_bindings[j.profile_name];
for (const scene::action_binding & k: j.paths)
for (const auto & profile: j.profile_names)
{
XrAction a = i->actions_by_name[k.action_name].first;
assert(a != XR_NULL_HANDLE);
// Skip unsupported profiles
if (!suggested_bindings.contains(profile))
continue;
xr_bindings.push_back(XrActionSuggestedBinding{
.action = a,
.binding = string_to_path(k.input_source)});
std::vector<XrActionSuggestedBinding> & xr_bindings = suggested_bindings[profile];
for (const scene::action_binding & k: j.paths)
{
XrAction a = i->actions_by_name[k.action_name].first;
assert(a != XR_NULL_HANDLE);
xr_bindings.push_back(XrActionSuggestedBinding{
.action = a,
.binding = xr_instance.string_to_path(k.input_source)});
}
}
}
}
@@ -1007,7 +1165,7 @@ void application::initialize_actions()
for (const auto & name: profile.input_sources)
{
xr_bindings.push_back({actions_by_name[name], string_to_path(name)});
xr_bindings.push_back({actions_by_name[name], xr_instance.string_to_path(name)});
}
try
@@ -1027,19 +1185,24 @@ void application::initialize()
{
// LogLayersAndExtensions
assert(!xr_instance);
xr_extensions.clear();
std::vector<std::string> xr_extensions;
// Required extensions
xr_extensions.push_back(XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME);
// Optional extensions
std::vector<std::string> opt_extensions;
opt_extensions.push_back(XR_KHR_LOCATE_SPACES_EXTENSION_NAME);
opt_extensions.push_back(XR_KHR_MAINTENANCE1_EXTENSION_NAME);
opt_extensions.push_back(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME);
opt_extensions.push_back(XR_EXT_HAND_TRACKING_EXTENSION_NAME);
opt_extensions.push_back(XR_EXT_HAND_INTERACTION_EXTENSION_NAME);
opt_extensions.push_back(XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME);
opt_extensions.push_back(XR_FB_PASSTHROUGH_EXTENSION_NAME);
opt_extensions.push_back(XR_HTC_PASSTHROUGH_EXTENSION_NAME);
opt_extensions.push_back(XR_HTC_FACIAL_TRACKING_EXTENSION_NAME);
opt_extensions.push_back(XR_HTC_PATH_ENUMERATION_EXTENSION_NAME);
opt_extensions.push_back(XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME);
opt_extensions.push_back(XR_FB_FACE_TRACKING2_EXTENSION_NAME);
opt_extensions.push_back(XR_FB_BODY_TRACKING_EXTENSION_NAME);
opt_extensions.push_back(XR_META_BODY_TRACKING_FULL_BODY_EXTENSION_NAME);
@@ -1049,17 +1212,12 @@ void application::initialize()
opt_extensions.push_back(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME);
opt_extensions.push_back(XR_FB_COMPOSITION_LAYER_DEPTH_TEST_EXTENSION_NAME);
opt_extensions.push_back(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME);
opt_extensions.push_back(XR_EXT_USER_PRESENCE_EXTENSION_NAME);
opt_extensions.push_back(XR_KHR_VISIBILITY_MASK_EXTENSION_NAME);
opt_extensions.push_back(XR_FB_COMPOSITION_LAYER_SETTINGS_EXTENSION_NAME);
for (const auto & i: interaction_profiles)
{
for (const auto & j: i.required_extensions)
{
if (not j.starts_with("XR_VERSION"))
opt_extensions.push_back(j);
}
}
opt_extensions.insert(opt_extensions.end(), i.required_extensions.begin(), i.required_extensions.end());
for (const auto & i: xr::instance::extensions())
{
@@ -1080,7 +1238,10 @@ void application::initialize()
xr_instance = xr::instance(app_info.name, extensions);
#endif
spdlog::info("Created OpenXR instance, runtime {}, version {}", xr_instance.get_runtime_name(), xr_instance.get_runtime_version());
spdlog::info("Created OpenXR instance, runtime {}, version {}, API version {}",
xr_instance.get_runtime_name(),
xr_instance.get_runtime_version(),
xr::to_string(xr_instance.get_api_version()));
xr_system_id = xr::system(xr_instance, app_info.formfactor);
spdlog::info("Created OpenXR system for form factor {}", xr::to_string(app_info.formfactor));
@@ -1097,69 +1258,16 @@ void application::initialize()
spdlog::info(" Orientation tracking: {}", (bool)properties.trackingProperties.orientationTracking);
spdlog::info(" Position tracking: {}", (bool)properties.trackingProperties.positionTracking);
if (utils::contains(xr_extensions, XR_EXT_HAND_TRACKING_EXTENSION_NAME))
{
XrSystemHandTrackingPropertiesEXT hand_tracking_properties = xr_system_id.hand_tracking_properties();
spdlog::info(" Hand tracking support: {}", (bool)hand_tracking_properties.supportsHandTracking);
hand_tracking_supported = hand_tracking_properties.supportsHandTracking;
}
spdlog::info(" Hand tracking support: {}", xr_system_id.hand_tracking_supported());
if (utils::contains(xr_extensions, XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME))
if (xr_instance.has_extension(XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME))
{
XrSystemEyeGazeInteractionPropertiesEXT eye_gaze_properties = xr_system_id.eye_gaze_interaction_properties();
spdlog::info(" Eye gaze support: {}", (bool)eye_gaze_properties.supportsEyeGazeInteraction);
eye_gaze_supported = eye_gaze_properties.supportsEyeGazeInteraction;
if (eye_gaze_supported)
{
switch (guess_model())
{
case model::pico_4_pro:
case model::pico_4_enterprise:
pico_face_tracking_supported = true;
break;
default:
pico_face_tracking_supported = false;
break;
}
}
else
pico_face_tracking_supported = false;
spdlog::info(" PICO face tracking support: {}", (bool)pico_face_tracking_supported);
}
if (utils::contains(xr_extensions, XR_FB_FACE_TRACKING2_EXTENSION_NAME))
{
XrSystemFaceTrackingProperties2FB fb_face2_properties = xr_system_id.fb_face_tracking2_properties();
spdlog::info(" FB face tracking support: {}", (bool)fb_face2_properties.supportsVisualFaceTracking);
fb_face_tracking2_supported = fb_face2_properties.supportsVisualFaceTracking;
}
if (utils::contains(xr_extensions, XR_HTC_FACIAL_TRACKING_EXTENSION_NAME))
{
XrSystemFacialTrackingPropertiesHTC htc_face_properties = xr_system_id.htc_face_tracking_properties();
spdlog::info(" HTC eye tracking support: {}", (bool)htc_face_properties.supportEyeFacialTracking);
spdlog::info(" HTC lip tracking support: {}", (bool)htc_face_properties.supportLipFacialTracking);
htc_face_tracking_eye_supported = htc_face_properties.supportEyeFacialTracking;
htc_face_tracking_lip_supported = htc_face_properties.supportLipFacialTracking;
}
if (utils::contains_all(xr_extensions, std::array{XR_FB_BODY_TRACKING_EXTENSION_NAME, XR_META_BODY_TRACKING_FULL_BODY_EXTENSION_NAME, XR_META_BODY_TRACKING_FIDELITY_EXTENSION_NAME}))
{
XrSystemBodyTrackingPropertiesFB fb_body_properties = xr_system_id.fb_body_tracking_properties();
spdlog::info(" FB body tracking support: {}", (bool)fb_body_properties.supportsBodyTracking);
fb_body_tracking_supported = fb_body_properties.supportsBodyTracking;
}
if (utils::contains(xr_extensions, XR_BD_BODY_TRACKING_EXTENSION_NAME))
{
XrSystemBodyTrackingPropertiesBD bd_body_properties = xr_system_id.bd_body_tracking_properties();
spdlog::info(" PICO body tracking support: {}", (bool)bd_body_properties.supportsBodyTracking);
pico_body_tracking_supported = bd_body_properties.supportsBodyTracking;
}
if (utils::contains(xr_extensions, XR_FB_COMPOSITION_LAYER_SETTINGS_EXTENSION_NAME))
if (xr_instance.has_extension(XR_FB_COMPOSITION_LAYER_SETTINGS_EXTENSION_NAME))
{
spdlog::info(" OpenXR post-processing extension support: true");
openxr_post_processing_supported = true;
@@ -1167,70 +1275,45 @@ void application::initialize()
switch (xr_system_id.passthrough_supported())
{
case xr::system::passthrough_type::no_passthrough:
case xr::passthrough_type::none:
spdlog::info(" Passthrough: not supported");
break;
case xr::system::passthrough_type::bw:
case xr::passthrough_type::bw:
spdlog::info(" Passthrough: black and white");
break;
case xr::system::passthrough_type::color:
case xr::passthrough_type::color:
spdlog::info(" Passthrough: color");
break;
}
spdlog::info(" Face tracker: {}", magic_enum::enum_name(xr_system_id.face_tracker_supported()));
spdlog::info(" Body tracker: {}", magic_enum::enum_name(xr_system_id.body_tracker_supported()));
// Log view configurations and blend modes
log_views();
initialize_vulkan();
xr_session = xr::session(xr_instance, xr_system_id, vk_instance, vk_physical_device, vk_device, vk_queue_family_index);
{
auto spaces = xr_session.get_reference_spaces();
spdlog::info("{} reference spaces", spaces.size());
for (XrReferenceSpaceType i: spaces)
spdlog::info(" {}", xr::to_string(i));
}
xr_session = xr::session(xr_instance, xr_system_id, vk_instance, vk_physical_device, vk_device, vk_queue, vk_queue_family_index);
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);
if (hand_tracking_supported)
// HTC face tracker fails if created later
// we can destroy it right away, it actually stores static handles
if (xr_system_id.face_tracker_supported() == xr::face_tracker_type::htc)
{
left_hand = xr_session.create_hand_tracker(XR_HAND_LEFT_EXT);
right_hand = xr_session.create_hand_tracker(XR_HAND_RIGHT_EXT);
auto props = xr_system_id.htc_face_tracking_properties();
xr::htc_face_tracker(xr_instance, xr_session, props.supportEyeFacialTracking, props.supportLipFacialTracking);
}
if (fb_face_tracking2_supported)
{
fb_face_tracker2 = xr_session.create_fb_face_tracker2();
}
if (htc_face_tracking_eye_supported)
{
htc_face_tracker_eye = xr_session.create_htc_face_tracker(XR_FACIAL_TRACKING_TYPE_EYE_DEFAULT_HTC);
}
if (htc_face_tracking_lip_supported)
{
htc_face_tracker_lip = xr_session.create_htc_face_tracker(XR_FACIAL_TRACKING_TYPE_LIP_DEFAULT_HTC);
}
if (pico_face_tracking_supported)
{
pico_face_tracker = xr_session.create_pico_face_tracker();
}
if (fb_body_tracking_supported)
{
fb_body_tracker = xr_session.create_fb_body_tracker();
}
if (pico_body_tracking_supported)
{
pico_body_tracker = xr_session.create_pico_body_tracker();
auto spaces = xr_session.get_reference_spaces();
spdlog::info("{} reference spaces", spaces.size());
for (XrReferenceSpaceType i: spaces)
spdlog::info(" {}", xr::to_string(i));
}
vk::CommandPoolCreateInfo cmdpool_create_info;
@@ -1240,50 +1323,47 @@ void application::initialize()
vk_cmdpool = vk::raii::CommandPool{vk_device, cmdpool_create_info};
initialize_actions();
load_locale();
}
void application::load_locale()
{
gen.add_messages_domain("wivrn");
std::locale loc = gen("");
messages_info.encoding = "UTF-8";
if (config->locale.empty())
{
#ifdef __ANDROID__
jni::klass java_util_Locale("java/util/Locale");
auto default_locale = java_util_Locale.call<jni::object<"java/util/Locale">>("getDefault");
jni::klass java_util_Locale("java/util/Locale");
auto default_locale = java_util_Locale.call<jni::object<"java/util/Locale">>("getDefault");
// if (auto language = default_locale.call<jni::string>("toString"))
if (auto language = default_locale.call<jni::string>("getLanguage"))
messages_info.language = language;
if (auto country = default_locale.call<jni::string>("getCountry"))
messages_info.country = country;
messages_info.encoding = "UTF-8";
// if (auto language = default_locale.call<jni::string>("toString"))
if (auto language = default_locale.call<jni::string>("getLanguage"))
messages_info.language = language;
if (auto country = default_locale.call<jni::string>("getCountry"))
messages_info.country = country;
#else
auto & facet = std::use_facet<boost::locale::info>(loc);
messages_info.language = facet.language();
messages_info.country = facet.country();
messages_info.encoding = "UTF-8";
auto & facet = std::use_facet<boost::locale::info>(loc);
messages_info.language = facet.language();
messages_info.country = facet.country();
#endif
}
else
{
auto pos = config->locale.find("_");
messages_info.language = config->locale.substr(0, pos);
if (pos != std::string::npos)
messages_info.country = config->locale.substr(pos + 1);
}
spdlog::info("Current locale: language {}, country {}, encoding {}", messages_info.language, messages_info.country, messages_info.encoding);
messages_info.paths.push_back("locale");
messages_info.domains.push_back(boost::locale::gnu_gettext::messages_info::domain("wivrn"));
messages_info.callback = [](const std::string & file_name, const std::string & encoding) {
std::vector<char> buffer;
try
{
asset file(file_name);
buffer.resize(file.size());
memcpy(buffer.data(), file.data(), file.size());
}
catch (...)
{
}
return buffer;
};
messages_info.callback = open_locale_file;
loc = std::locale(loc, boost::locale::gnu_gettext::create_messages_facet<char>(messages_info));
std::locale::global(loc);
@@ -1767,7 +1847,6 @@ void application::poll_events()
exit_requested = true;
}
break;
case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED:
case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING:
break;
case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
+25 -137
View File
@@ -19,20 +19,20 @@
#pragma once
#include "configuration.h"
#include "wifi_lock.h"
#include "xr/fb_body_tracker.h"
#include "xr/fb_face_tracker2.h"
#include "xr/hand_tracker.h"
#include "xr/htc_face_tracker.h"
#include "xr/pico_face_tracker.h"
#ifdef __ANDROID__
#include <android_native_app_glue.h>
#endif
#include "configuration.h"
#include "utils/singleton.h"
#include "utils/thread_safe.h"
#include "vk/vk_allocator.h"
#include "xr/xr.h"
#include "wifi_lock.h"
#include "xr/actionset.h"
#include "xr/instance.h"
#include "xr/session.h"
#include "xr/swapchain.h"
#include "xr/system.h"
#include <atomic>
#include <boost/locale/generator.hpp>
#include <boost/locale/gnu_gettext.hpp>
@@ -103,7 +103,7 @@ class application : public singleton<application>
vk::raii::PhysicalDevice vk_physical_device = nullptr;
vk::raii::Device vk_device = nullptr;
uint32_t vk_queue_family_index;
vk::raii::Queue vk_queue = nullptr;
thread_safe<vk::raii::Queue> vk_queue = nullptr;
vk::raii::CommandPool vk_cmdpool = nullptr;
vk::raii::PipelineCache pipeline_cache = nullptr;
vk::PhysicalDeviceProperties physical_device_properties;
@@ -123,25 +123,7 @@ class application : public singleton<application>
xr::actionset xr_actionset;
std::vector<std::tuple<XrAction, XrActionType, std::string>> actions;
bool hand_tracking_supported = false;
xr::hand_tracker left_hand;
xr::hand_tracker right_hand;
bool fb_face_tracking2_supported = false;
xr::fb_face_tracker2 fb_face_tracker2;
bool htc_face_tracking_eye_supported = false;
xr::htc_face_tracker htc_face_tracker_eye;
bool htc_face_tracking_lip_supported = false;
xr::htc_face_tracker htc_face_tracker_lip;
bool pico_face_tracking_supported = false;
xr::pico_face_tracker pico_face_tracker;
bool fb_body_tracking_supported = false;
xr::fb_body_tracker fb_body_tracker;
bool pico_body_tracking_supported = false;
xr::pico_body_tracker pico_body_tracker;
std::vector<std::pair<XrPath, xr::space>> generic_trackers;
bool eye_gaze_supported = false;
@@ -151,7 +133,6 @@ class application : public singleton<application>
bool session_focused = false;
bool session_visible = false;
bool debug_extensions_found = false;
std::vector<std::string> xr_extensions;
std::vector<const char *> vk_device_extensions;
std::atomic<bool> exit_requested = false;
std::filesystem::path config_path;
@@ -281,16 +262,6 @@ public:
return std::make_pair(position, orientation);
}
static XrPath string_to_path(const std::string & s)
{
return instance().xr_instance.string_to_path(s);
}
static std::string path_to_string(XrPath p)
{
return instance().xr_instance.path_to_string(p);
}
void run();
static void push_scene(std::shared_ptr<scene>);
@@ -361,17 +332,7 @@ public:
// #endif
}
static XrTime now()
{
return instance().xr_instance.now();
}
static uint32_t queue_family_index()
{
return instance().vk_queue_family_index;
}
static vk::raii::Queue & get_queue()
static thread_safe<vk::raii::Queue> & get_queue()
{
return instance().vk_queue;
}
@@ -386,26 +347,21 @@ public:
return intent;
}
static vk::raii::PhysicalDevice & get_physical_device()
{
return instance().vk_physical_device;
}
static const vk::PhysicalDeviceProperties & get_physical_device_properties()
{
return instance().physical_device_properties;
}
static vk::raii::Device & get_device()
{
return instance().vk_device;
}
static vk::raii::Instance & get_vulkan_instance()
{
return instance().vk_instance;
}
static xr::system & get_system()
{
return instance().xr_system_id;
}
static vk::raii::PipelineCache & get_pipeline_cache()
{
return instance().pipeline_cache;
@@ -426,41 +382,6 @@ public:
return instance().last_scene_cpu_time;
}
static bool get_hand_tracking_supported()
{
return instance().hand_tracking_supported;
}
static bool get_fb_face_tracking2_supported()
{
return instance().fb_face_tracking2_supported;
}
static bool get_htc_face_tracking_eye_supported()
{
return instance().htc_face_tracking_eye_supported;
}
static bool get_htc_face_tracking_lip_supported()
{
return instance().htc_face_tracking_lip_supported;
}
static bool get_pico_face_tracking_supported()
{
return instance().pico_face_tracking_supported;
}
static bool get_fb_body_tracking_supported()
{
return instance().fb_body_tracking_supported;
}
static bool get_pico_body_tracking_supported()
{
return instance().pico_body_tracking_supported;
}
static bool get_eye_gaze_supported()
{
return instance().eye_gaze_supported;
@@ -471,49 +392,9 @@ public:
return instance().openxr_post_processing_supported;
}
static xr::hand_tracker & get_left_hand()
static auto & get_generic_trackers()
{
return instance().left_hand;
}
static xr::hand_tracker & get_right_hand()
{
return instance().right_hand;
}
static xr::fb_face_tracker2 & get_fb_face_tracker2()
{
return instance().fb_face_tracker2;
}
static xr::htc_face_tracker & get_htc_face_tracker_eye()
{
return instance().htc_face_tracker_eye;
}
static xr::htc_face_tracker & get_htc_face_tracker_lip()
{
return instance().htc_face_tracker_lip;
}
static xr::pico_face_tracker & get_pico_face_tracker()
{
return instance().pico_face_tracker;
}
static xr::fb_body_tracker & get_fb_body_tracker()
{
return instance().fb_body_tracker;
}
static xr::pico_body_tracker & get_pico_body_tracker()
{
return instance().pico_body_tracker;
}
static const std::vector<std::string> & get_xr_extensions()
{
return instance().xr_extensions;
return instance().generic_trackers;
}
static const std::vector<const char *> & get_vk_device_extensions()
@@ -527,8 +408,15 @@ public:
return *instance().config;
}
static XrSessionState get_session_state()
{
return instance().session_state;
}
static boost::locale::gnu_gettext::messages_info & get_messages_info()
{
return instance().messages_info;
}
void load_locale();
};
+1 -1
View File
@@ -291,7 +291,7 @@ void wivrn::android::audio::operator()(wivrn::audio_data && data)
buffer_size_bytes.fetch_add(size);
}
void wivrn::android::audio::set_mic_sate(bool running)
void wivrn::android::audio::set_mic_state(bool running)
{
if (not microphone)
return;
+1 -1
View File
@@ -78,7 +78,7 @@ public:
void operator()(wivrn::audio_data &&);
void set_mic_sate(bool running);
void set_mic_state(bool running);
static void get_audio_description(wivrn::from_headset::headset_info_packet & info);
};
+1 -1
View File
@@ -42,7 +42,7 @@ public:
~audio() = default;
void operator()(wivrn::audio_data &&) {}
void set_mic_sate(bool running) {}
void set_mic_state(bool running) {}
static void get_audio_description(wivrn::from_headset::headset_info_packet & info) {}
};
+35 -83
View File
@@ -82,6 +82,8 @@ bool configuration::check_feature(feature f) const
{
std::lock_guard lock(mutex);
auto & system = application::get_system();
auto it = features.find(f);
if (it == features.end())
return false;
@@ -94,7 +96,7 @@ bool configuration::check_feature(feature f) const
case feature::microphone:
break;
case feature::hand_tracking:
if (not application::get_hand_tracking_supported())
if (not system.hand_tracking_supported())
return false;
break;
case feature::eye_gaze:
@@ -102,45 +104,12 @@ bool configuration::check_feature(feature f) const
return false;
break;
case feature::face_tracking:
switch (guess_model())
{
case model::htc_vive_focus_3:
case model::htc_vive_focus_vision:
[[fallthrough]];
case model::htc_vive_xr_elite:
if (not(application::get_htc_face_tracking_eye_supported() or application::get_htc_face_tracking_lip_supported()))
return false;
break;
case model::pico_4_pro:
case model::pico_4_enterprise:
if (not application::get_pico_face_tracking_supported())
return false;
break;
default:
if (not application::get_fb_face_tracking2_supported())
return false;
break;
}
if (system.face_tracker_supported() == xr::face_tracker_type::none)
return false;
break;
case feature::body_tracking:
switch (guess_model())
{
case model::meta_quest_3:
case model::meta_quest_3s:
if (not application::get_fb_body_tracking_supported())
return 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:
if (not application::get_pico_body_tracking_supported())
return false;
break;
default:
break;
}
if (system.body_tracker_supported() == xr::body_tracker_type::none)
return false;
break;
}
}
@@ -176,8 +145,8 @@ void configuration::set_feature(feature f, bool state)
configuration::configuration(xr::system & system)
{
passthrough_enabled = system.passthrough_supported() == xr::system::passthrough_type::color;
features[feature::hand_tracking] = application::get_hand_tracking_supported();
passthrough_enabled = system.passthrough_supported() == xr::passthrough_type::color;
features[feature::hand_tracking] = system.hand_tracking_supported();
try
{
simdjson::dom::parser parser;
@@ -200,9 +169,6 @@ configuration::configuration(xr::system & system)
servers.emplace(data.service.txt["cookie"], data);
}
if (auto val = root["show_performance_metrics"]; val.is_bool())
show_performance_metrics = val.get_bool();
if (auto val = root["preferred_refresh_rate"]; val.is_double())
preferred_refresh_rate = val.get_double();
@@ -212,8 +178,8 @@ configuration::configuration(xr::system & system)
if (auto val = root["resolution_scale"]; val.is_double())
resolution_scale = val.get_double();
if (auto val = root["sgsr"]; val.is_object())
parse_sgsr_options(val.get_object());
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());
@@ -238,8 +204,23 @@ configuration::configuration(xr::system & system)
features[i] = val.get_bool();
}
if (system.passthrough_supported() == xr::system::passthrough_type::no_passthrough)
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();
}
catch (std::exception & e)
{
@@ -250,32 +231,11 @@ configuration::configuration(xr::system & system)
preferred_refresh_rate.reset();
minimum_refresh_rate.reset();
resolution_scale = 1.4;
sgsr = {};
openxr_post_processing = {};
show_performance_metrics = false;
passthrough_enabled = system.passthrough_supported() == xr::system::passthrough_type::color;
passthrough_enabled = system.passthrough_supported() == xr::passthrough_type::color;
}
}
void configuration::parse_sgsr_options(simdjson::simdjson_result<simdjson::dom::object> sgsr_root)
{
sgsr = {};
if (auto val = sgsr_root["enabled"]; val.is_bool())
sgsr.enabled = val.get_bool();
if (auto val = sgsr_root["upscaling_factor"]; val.is_double())
sgsr.upscaling_factor = val.get_double();
if (auto val = sgsr_root["use_edge_direction"]; val.is_bool())
sgsr.use_edge_direction = val.get_bool();
if (auto val = sgsr_root["edge_threshold"]; val.is_double())
sgsr.edge_threshold = val.get_double();
if (auto val = sgsr_root["edge_sharpness"]; val.is_double())
sgsr.edge_sharpness = val.get_double();
}
void configuration::parse_openxr_post_processing_options(simdjson::simdjson_result<simdjson::dom::object> openxr_post_processing_root)
{
openxr_post_processing = {};
@@ -291,17 +251,6 @@ static std::ostream & operator<<(std::ostream & stream, feature f)
return stream << "\"" << magic_enum::enum_name(f) << "\"";
}
static std::ostream & write_sgsr(std::ofstream & stream, const configuration::sgsr_settings & sgsr)
{
stream << "{\"enabled\":" << std::boolalpha << sgsr.enabled;
stream << ",\"upscaling_factor\":" << sgsr.upscaling_factor;
stream << ",\"use_edge_direction\":" << std::boolalpha << sgsr.use_edge_direction;
stream << ",\"edge_threshold\":" << sgsr.edge_threshold;
stream << ",\"edge_sharpness\":" << sgsr.edge_sharpness;
stream << "}";
return stream;
}
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;
@@ -338,23 +287,26 @@ void configuration::save()
std::ofstream json(application::get_config_path() / "client.json");
json << "{\"servers\":[" << servers_str << "],"
<< "\"show_performance_metrics\":" << std::boolalpha << show_performance_metrics;
json << "{\"servers\":[" << servers_str << "]";
if (preferred_refresh_rate)
json << ",\"preferred_refresh_rate\":" << *preferred_refresh_rate;
if (minimum_refresh_rate)
json << ",\"minimum_refresh_rate\":" << *minimum_refresh_rate;
json << ",\"resolution_scale\":" << resolution_scale;
json << ",\"sgsr\":";
write_sgsr(json, sgsr);
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 << "}";
}
+10 -12
View File
@@ -50,23 +50,13 @@ public:
std::optional<float> preferred_refresh_rate;
std::optional<float> minimum_refresh_rate;
float resolution_scale = 1.4;
bool show_performance_metrics = false;
bool passthrough_enabled = false;
bool mic_unprocessed_audio = false;
bool fb_lower_body = false;
bool fb_hip = true;
// Snapdragon Game Super Resolution
struct sgsr_settings
{
bool enabled = false;
float upscaling_factor = 1.5;
bool use_edge_direction = true;
float edge_threshold = 4.0;
float edge_sharpness = 2.0;
};
sgsr_settings sgsr{};
bool enable_stream_gui = true;
// XR_FB_composition_layer_settings extension flags
struct openxr_post_processing_settings
@@ -78,6 +68,14 @@ public:
std::string virtual_keyboard_layout = "QWERTY";
bool override_foveation_enable = false;
float override_foveation_pitch = 10 * M_PI / 180;
float override_foveation_distance = 3;
bool first_run = true;
std::string locale;
bool check_feature(feature f) const;
void set_feature(feature f, bool state);
@@ -85,11 +83,11 @@ private:
mutable std::mutex mutex;
std::map<feature, bool> features;
void parse_sgsr_options(simdjson::simdjson_result<simdjson::dom::object> root);
void parse_openxr_post_processing_options(simdjson::simdjson_result<simdjson::dom::object> root);
public:
configuration(xr::system &);
configuration() = default;
void save();
};
+12 -6
View File
@@ -18,7 +18,6 @@
#pragma once
#include <array>
#include <cstdint>
#include <glm/glm.hpp>
#include <imgui.h>
@@ -29,9 +28,6 @@ namespace constants::gui
// Minimum distance between a GUI layer and a fingertip/controller to register a click
constexpr float min_pointer_distance = -0.1;
// Number of combined image samplers in ImGui descriptor pool
constexpr unsigned int nb_combined_image_samplers = 100;
// Font to use (desktop only)
constexpr const char font_name[] = "Noto Sans";
@@ -40,7 +36,7 @@ constexpr int font_size_small = 30;
constexpr int font_size_large = 75;
// Ratio between joystick position and scroll distance/s
constexpr float scroll_ratio = 3;
constexpr float scroll_ratio = 10;
// Threshold on the trigger value to register a click
constexpr float trigger_click_thd = 0.8;
@@ -91,7 +87,7 @@ constexpr float recenter_action_distance = 0.3;
constexpr float initial_gui_distance = 0.5;
// Skybox color
constexpr std::array<float, 4> sky_color = {0, 0.25, 0.5, 1};
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};
@@ -105,6 +101,16 @@ constexpr int zindex_controllers = 1;
constexpr int zindex_recenter_tip = 2;
} // namespace constants::lobby
namespace constants::stream
{
constexpr float fade_delay = 3;
constexpr float fade_duration = 0.25;
// Dimming for the streamed video when the GUI is interactable
constexpr float dimming_scale = 0.7;
constexpr float dimming_bias = 0.15;
} // namespace constants::stream
namespace constants::style
{
constexpr ImVec2 window_padding = {20, 20};
+34 -18
View File
@@ -59,8 +59,11 @@ const char * mime(wivrn::video_codec codec)
return "video/hevc";
case c::av1:
return "video/av01";
case c::raw:
break;
}
assert(false);
__builtin_unreachable();
}
void check(media_status_t status, const char * msg)
@@ -72,6 +75,26 @@ void check(media_status_t status, const char * msg)
}
}
struct android_blit_handle : public decoder::blit_handle
{
std::shared_ptr<wivrn::android::decoder::mapped_hardware_buffer> vk_data;
std::shared_ptr<AImageReader> image_reader;
AImage_ptr aimage;
android_blit_handle(
const wivrn::from_headset::feedback & feedback,
const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info,
vk::ImageView image_view,
vk::Image image,
vk::ImageLayout & current_layout,
decltype(vk_data) vk_data,
decltype(image_reader) image_reader,
decltype(aimage) aimage) :
decoder::blit_handle(feedback, view_info, image_view, image, current_layout),
vk_data(vk_data),
image_reader(image_reader),
aimage(std::move(aimage)) {}
};
} // namespace
namespace wivrn::android
@@ -85,7 +108,7 @@ decoder::decoder(
uint8_t stream_index,
std::weak_ptr<scenes::stream> weak_scene,
shard_accumulator * accumulator) :
description(description), stream_index(stream_index), fps(fps), device(device), weak_scene(weak_scene), accumulator(accumulator)
wivrn::decoder(description), stream_index(stream_index), fps(fps), device(device), weak_scene(weak_scene), accumulator(accumulator)
{
spdlog::info("hbm_mutex.native_handle() = {}", (void *)hbm_mutex.native_handle());
@@ -222,7 +245,7 @@ void decoder::push_data(std::span<std::span<const uint8_t>> data, uint64_t frame
current_input_buffer = input_buffer{};
}
void decoder::frame_completed(wivrn::from_headset::feedback & feedback, const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info)
void decoder::frame_completed(const wivrn::from_headset::feedback & feedback, const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info)
{
if (not media_codec)
{
@@ -255,7 +278,7 @@ void decoder::on_image_available(AImageReader * reader)
assert(reader == image_reader.get());
// Executed on image reader thread
decltype(blit_handle::aimage) image;
decltype(android_blit_handle::aimage) image;
try
{
AImage * tmp;
@@ -280,13 +303,13 @@ void decoder::on_image_available(AImageReader * reader)
auto vk_data = map_hardware_buffer(image.get());
auto handle = std::make_shared<decoder::blit_handle>(
auto handle = std::make_shared<android_blit_handle>(
info->feedback,
info->view_info,
vk_data->image_view,
*vk_data->image_view,
*vk_data->vimage,
&vk_data->layout,
vk_data,
vk_data->layout,
std::move(vk_data),
image_reader,
std::move(image));
@@ -388,7 +411,8 @@ std::shared_ptr<decoder::mapped_hardware_buffer> decoder::map_hardware_buffer(AI
if (!*ycbcr_sampler || memcmp(&ahb_format, &format_properties, sizeof(format_properties)))
{
memcpy(&ahb_format, &format_properties, sizeof(format_properties));
extent = {buffer_desc.width, buffer_desc.height};
extent_ = {buffer_desc.width, buffer_desc.height};
spdlog::info("decoded image size: {}x{}", buffer_desc.width, buffer_desc.height);
create_sampler(buffer_desc, ahb_format);
hardware_buffer_map.clear();
// TODO tell the reprojector to recreate the pipeline
@@ -514,11 +538,6 @@ void decoder::on_media_output_available(AMediaCodec * media_codec, void * userda
});
}
void decoder::blit_handle::deleter::operator()(AImage * aimage)
{
AImage_delete(aimage);
}
static bool hardware_accelerated(AMediaCodec * media_codec)
{
// MediaCodecInfo has isHardwareAccelerated, but this does not exist in NDK.
@@ -542,11 +561,10 @@ static bool hardware_accelerated(AMediaCodec * media_codec)
return true;
}
std::vector<wivrn::video_codec> decoder::supported_codecs()
void decoder::supported_codecs(std::vector<wivrn::video_codec> & result)
{
std::vector<wivrn::video_codec> result;
// Make sure we update this code when codecs are changed
static_assert(magic_enum::enum_count<wivrn::video_codec>() == 3);
static_assert(magic_enum::enum_count<wivrn::video_codec>() == 4);
// In order or preference, from preferred to least preferred
for (auto codec: {
@@ -563,8 +581,6 @@ std::vector<wivrn::video_codec> decoder::supported_codecs()
spdlog::info("video codec {}: {}supported", magic_enum::enum_name(codec), supported ? "" : "NOT ");
}
return result;
}
} // namespace wivrn::android
+7 -39
View File
@@ -19,6 +19,7 @@
#pragma once
#include "decoder/decoder.h"
#include "utils/sync_queue.h"
#include "wivrn_packets.h"
#include <functional>
@@ -59,31 +60,12 @@ class stream;
namespace wivrn::android
{
class decoder
class decoder : public wivrn::decoder
{
public:
struct mapped_hardware_buffer;
struct blit_handle
{
struct deleter
{
void operator()(AImage *);
};
wivrn::from_headset::feedback feedback;
wivrn::to_headset::video_stream_data_shard::view_info_t view_info;
vk::raii::ImageView & image_view;
vk::Image image = nullptr;
vk::ImageLayout * current_layout = nullptr;
std::shared_ptr<mapped_hardware_buffer> vk_data;
std::shared_ptr<AImageReader> image_reader;
AImage_ptr aimage;
};
private:
wivrn::to_headset::video_stream_description::item description;
uint8_t stream_index;
float fps;
@@ -92,7 +74,6 @@ private:
vk::AndroidHardwareBufferFormatPropertiesANDROID ahb_format;
vk::raii::SamplerYcbcrConversion ycbcr_conversion = nullptr;
vk::raii::Sampler ycbcr_sampler = nullptr;
vk::Extent2D extent{};
std::mutex hbm_mutex;
std::shared_ptr<AImageReader> image_reader;
@@ -146,33 +127,20 @@ public:
uint8_t stream_index,
std::weak_ptr<scenes::stream> scene,
shard_accumulator * accumulator);
decoder(const decoder &) = delete;
decoder(decoder &&) = delete;
~decoder();
void push_data(std::span<std::span<const uint8_t>> data, uint64_t frame_index, bool partial);
void push_data(std::span<std::span<const uint8_t>> data, uint64_t frame_index, bool partial) override;
void frame_completed(
wivrn::from_headset::feedback & feedback,
const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info);
const wivrn::from_headset::feedback & feedback,
const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info) override;
const auto & desc() const
{
return description;
}
vk::Sampler sampler()
vk::Sampler sampler() override
{
return *ycbcr_sampler;
}
vk::Extent2D image_size()
{
return extent;
}
static std::vector<wivrn::video_codec> supported_codecs();
static void supported_codecs(std::vector<wivrn::video_codec> &);
};
} // namespace wivrn::android
+86
View File
@@ -0,0 +1,86 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "decoder.h"
#ifdef __ANDROID__
#include "decoder/android/android_decoder.h"
#else
#include "decoder/ffmpeg/ffmpeg_decoder.h"
#endif
#include "decoder/raw_decoder.h"
wivrn::decoder::~decoder() = default;
std::shared_ptr<wivrn::decoder> wivrn::decoder::make(
vk::raii::Device & device,
vk::raii::PhysicalDevice & phys_dev,
uint32_t vk_queue_family_index,
const wivrn::to_headset::video_stream_description::item & description,
float fps,
uint8_t stream_index,
std::weak_ptr<scenes::stream> scene,
shard_accumulator * acc)
{
switch (description.codec)
{
case h264:
case h265:
case av1:
#ifdef __ANDROID__
return std::make_shared<wivrn::android::decoder>(
device,
phys_dev,
description,
fps,
stream_index,
scene,
acc);
#else
return std::make_shared<wivrn::ffmpeg::decoder>(
device,
phys_dev,
description,
stream_index,
scene,
acc);
#endif
case raw:
return std::make_shared<wivrn::raw_decoder>(
device,
phys_dev,
vk_queue_family_index,
description,
stream_index,
scene,
acc);
}
__builtin_unreachable();
}
std::vector<wivrn::video_codec> wivrn::decoder::supported_codecs()
{
std::vector<wivrn::video_codec> res;
#ifdef __ANDROID__
android::decoder::supported_codecs(res);
#else
ffmpeg::decoder::supported_codecs(res);
#endif
res.push_back(video_codec::raw);
return res;
}
+82
View File
@@ -0,0 +1,82 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "wivrn_packets.h"
#include <cstdint>
#include <memory>
#include <span>
#include <vulkan/vulkan_raii.hpp>
namespace scenes
{
class stream;
}
namespace wivrn
{
class shard_accumulator;
class decoder
{
public:
struct blit_handle
{
wivrn::from_headset::feedback feedback;
wivrn::to_headset::video_stream_data_shard::view_info_t view_info;
vk::ImageView image_view = nullptr;
vk::Image image = nullptr;
vk::ImageLayout & current_layout;
vk::Semaphore semaphore = nullptr;
uint64_t * semaphore_val = nullptr;
};
const wivrn::to_headset::video_stream_description::item description;
protected:
decoder(const wivrn::to_headset::video_stream_description::item & description) :
description(description) {}
vk::Extent2D extent_; // Must be populated when sampler is set
public:
static std::shared_ptr<decoder> make(
vk::raii::Device &,
vk::raii::PhysicalDevice &,
uint32_t vk_queue_family_index,
const wivrn::to_headset::video_stream_description::item & description,
float fps,
uint8_t stream_index,
std::weak_ptr<scenes::stream>,
shard_accumulator *);
virtual ~decoder();
virtual void push_data(std::span<std::span<const uint8_t>> data, uint64_t frame_index, bool partial) = 0;
virtual void frame_completed(
const from_headset::feedback & feedback,
const to_headset::video_stream_data_shard::view_info_t & view_info) = 0;
virtual vk::Sampler sampler() = 0;
const vk::Extent2D extent()
{
return extent_;
}
static std::vector<wivrn::video_codec> supported_codecs();
};
} // namespace wivrn
+48 -19
View File
@@ -56,29 +56,60 @@ static AVCodecID codec_id(wivrn::video_codec codec)
return AV_CODEC_ID_HEVC;
case c::av1:
return AV_CODEC_ID_AV1;
case c::raw:
break;
}
assert(false);
__builtin_unreachable();
}
decoder::blit_handle::~blit_handle()
struct decoder::ffmpeg_blit_handle : public wivrn::decoder::blit_handle
{
std::unique_lock lock(self->mutex);
if (image_index < 0)
return;
int image_index;
wivrn::ffmpeg::decoder * self;
self->free_images.push_back(image_index);
}
ffmpeg_blit_handle(
const wivrn::from_headset::feedback & feedback,
const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info,
vk::ImageView image_view,
vk::Image image,
vk::ImageLayout & current_layout,
int image_index,
wivrn::ffmpeg::decoder * self) :
wivrn::decoder::blit_handle{
feedback,
view_info,
image_view,
image,
current_layout,
},
image_index(image_index),
self(self)
{}
~ffmpeg_blit_handle()
{
std::unique_lock lock(self->mutex);
if (image_index < 0)
return;
self->free_images.push_back(image_index);
}
};
decoder::decoder(
vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
const wivrn::to_headset::video_stream_description::item & description,
float fps,
uint8_t stream_index,
std::weak_ptr<scenes::stream> scene,
shard_accumulator * accumulator) :
device(device), description(description), codec(nullptr, free_codec_context), sws(nullptr, sws_freeContext), weak_scene(scene), accumulator(accumulator)
wivrn::decoder(description),
device(device),
codec(nullptr, free_codec_context),
sws(nullptr, sws_freeContext),
weak_scene(scene),
accumulator(accumulator)
{
free_images.resize(image_count);
@@ -108,7 +139,7 @@ decoder::decoder(
decoded_images[i].image = image_allocation(device, image_info, alloc_info);
decoded_images[i].image.map();
extent = vk::Extent2D{description.width, description.height};
extent_ = vk::Extent2D{description.width, description.height};
vk::ImageSubresource resource;
resource.aspectMask = vk::ImageAspectFlagBits::eColor;
@@ -221,12 +252,12 @@ void decoder::frame_completed(const wivrn::from_headset::feedback & feedback, co
if (res == 0)
throw std::runtime_error{"sws_scale failed"};
auto handle = std::make_shared<decoder::blit_handle>(
auto handle = std::make_shared<ffmpeg_blit_handle>(
feedback,
view_info,
decoded_images[index].image_view,
(vk::Image)decoded_images[index].image,
&decoded_images[index].current_layout,
*decoded_images[index].image_view,
decoded_images[index].image,
decoded_images[index].current_layout,
index,
this);
@@ -234,13 +265,11 @@ void decoder::frame_completed(const wivrn::from_headset::feedback & feedback, co
scene->push_blit_handle(accumulator, std::move(handle));
}
std::vector<wivrn::video_codec> decoder::supported_codecs()
void decoder::supported_codecs(std::vector<wivrn::video_codec> & res)
{
return {
wivrn::video_codec::h264,
wivrn::video_codec::h265,
wivrn::video_codec::av1,
};
res.push_back(wivrn::video_codec::h264);
res.push_back(wivrn::video_codec::h265);
res.push_back(wivrn::video_codec::av1);
}
} // namespace wivrn::ffmpeg
+7 -37
View File
@@ -19,6 +19,7 @@
#pragma once
#include "decoder/decoder.h"
#include "vk/allocation.h"
#include "wivrn_packets.h"
#include <memory>
@@ -46,24 +47,10 @@ class stream;
namespace wivrn::ffmpeg
{
class decoder
class decoder : public wivrn::decoder
{
public:
struct blit_handle
{
wivrn::from_headset::feedback feedback;
wivrn::to_headset::video_stream_data_shard::view_info_t view_info;
vk::raii::ImageView & image_view;
vk::Image image = nullptr;
vk::ImageLayout * current_layout = nullptr;
int image_index;
decoder * self;
~blit_handle();
};
private:
struct ffmpeg_blit_handle;
static const int image_count = 12;
struct image
{
@@ -78,11 +65,8 @@ private:
vk::raii::Sampler rgb_sampler = nullptr;
std::array<image, image_count> decoded_images;
vk::Extent2D extent{};
std::vector<int> free_images;
wivrn::to_headset::video_stream_description::item description;
std::unique_ptr<AVCodecContext, void (*)(AVCodecContext *)> codec;
std::unique_ptr<SwsContext, void (*)(SwsContext *)> sws;
std::vector<uint8_t> packet;
@@ -96,35 +80,21 @@ public:
decoder(vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
const wivrn::to_headset::video_stream_description::item & description,
float fps,
uint8_t stream_index,
std::weak_ptr<scenes::stream> scene,
shard_accumulator * accumulator);
decoder(const decoder &) = delete;
decoder(decoder &&) = delete;
void push_data(std::span<std::span<const uint8_t>> data, uint64_t frame_index, bool partial);
void push_data(std::span<std::span<const uint8_t>> data, uint64_t frame_index, bool partial) override;
void frame_completed(
const wivrn::from_headset::feedback & feedback,
const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info);
const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info) override;
const auto & desc() const
{
return description;
}
vk::Sampler sampler()
vk::Sampler sampler() override
{
return *rgb_sampler;
}
vk::Extent2D image_size()
{
return extent;
}
static std::vector<wivrn::video_codec> supported_codecs();
static void supported_codecs(std::vector<wivrn::video_codec> &);
};
} // namespace wivrn::ffmpeg
+353
View File
@@ -0,0 +1,353 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "raw_decoder.h"
#include "application.h"
#include "scenes/stream.h"
namespace
{
struct raw_blit_handle : public wivrn::decoder::blit_handle
{
std::atomic_bool & free;
raw_blit_handle(
const wivrn::from_headset::feedback & feedback,
const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info,
vk::ImageView image_view,
vk::Image image,
vk::ImageLayout & current_layout,
vk::Semaphore semaphore,
uint64_t & semaphore_val,
std::atomic_bool & free) :
wivrn::decoder::blit_handle{feedback, view_info, image_view, image, current_layout, semaphore, &semaphore_val},
free(free) {}
~raw_blit_handle()
{
free = true;
};
};
vk::raii::Sampler make_sampler(
vk::raii::Device & device,
vk::raii::SamplerYcbcrConversion & ycbcr_conversion,
to_headset::video_stream_description::channels_t channels)
{
vk::StructureChain info{
vk::SamplerCreateInfo{
.magFilter = vk::Filter::eNearest,
.minFilter = vk::Filter::eNearest,
.mipmapMode = vk::SamplerMipmapMode::eNearest,
.addressModeU = vk::SamplerAddressMode::eClampToEdge,
.addressModeV = vk::SamplerAddressMode::eClampToEdge,
.addressModeW = vk::SamplerAddressMode::eClampToEdge,
.maxAnisotropy = 1,
},
vk::SamplerYcbcrConversionInfo{
.conversion = *ycbcr_conversion,
},
};
switch (channels)
{
case wivrn::to_headset::video_stream_description::channels_t::colour:
break;
case wivrn::to_headset::video_stream_description::channels_t::alpha:
info.unlink<vk::SamplerYcbcrConversionInfo>();
break;
}
return vk::raii::Sampler(device, info.get());
}
} // namespace
namespace wivrn
{
raw_decoder::raw_decoder(
vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
uint32_t vk_queue_family_index,
const wivrn::to_headset::video_stream_description::item & description,
uint8_t stream_index,
std::weak_ptr<scenes::stream> scene,
shard_accumulator * accumulator) :
decoder(description),
device(device),
ycbcr_conversion(device,
{
.format = vk::Format::eG8B8R82Plane420Unorm,
.ycbcrModel = vk::SamplerYcbcrModelConversion(description.color_model.value_or(VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709)),
.ycbcrRange = vk::SamplerYcbcrRange(description.range.value_or(VK_SAMPLER_YCBCR_RANGE_ITU_FULL)),
.chromaFilter = vk::Filter::eNearest,
}),
sampler_(make_sampler(device, ycbcr_conversion, description.channels)),
command_pool(device, vk::CommandPoolCreateInfo{
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = vk_queue_family_index,
}),
cmd(device.allocateCommandBuffers(vk::CommandBufferAllocateInfo{
.commandPool = *command_pool,
.commandBufferCount = 1,
})[0]
.release()),
fence(device, vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled}),
weak_scene(scene),
accumulator(accumulator)
{
extent_ = vk::Extent2D{
.width = description.width,
.height = description.height,
};
vk::DeviceSize buffer_size = description.width * description.height;
vk::Format format{};
switch (description.channels)
{
case to_headset::video_stream_description::channels_t::colour:
buffer_size += (description.width * description.height) / 2;
format = vk::Format::eG8B8R82Plane420Unorm;
break;
case to_headset::video_stream_description::channels_t::alpha:
format = vk::Format::eR8Unorm;
break;
}
for (auto & i: input)
{
i = buffer_allocation(
device,
{
.size = buffer_size,
.usage = vk::BufferUsageFlagBits::eTransferSrc,
},
{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
},
"raw stream buffer");
}
input_pos = (uint8_t *)input[0].map();
for (auto & item: image_pool)
{
item.image = image_allocation(
device,
vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = format,
.extent = {
.width = description.width,
.height = description.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst,
},
{
.usage = VMA_MEMORY_USAGE_AUTO,
},
"raw image");
vk::SamplerYcbcrConversionInfo conv{
.conversion = *ycbcr_conversion,
};
vk::ImageViewCreateInfo view_info{
.pNext = format == vk::Format::eG8B8R82Plane420Unorm ? &conv : nullptr,
.image = item.image,
.viewType = vk::ImageViewType::e2D,
.format = format,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.levelCount = 1,
.layerCount = 1,
},
};
item.view_full = vk::raii::ImageView(device, view_info);
item.semaphore = vk::raii::Semaphore(
device,
vk::StructureChain{
vk::SemaphoreCreateInfo{},
vk::SemaphoreTypeCreateInfo{
.semaphoreType = vk::SemaphoreType::eTimeline,
},
}
.get());
}
}
void raw_decoder::push_data(std::span<std::span<const uint8_t>> data, uint64_t frame_index, bool partial)
{
if (frame_index != current_frame)
{
input_pos = (uint8_t *)input[0].map();
current_frame = frame_index;
}
for (const auto & item: data)
{
memcpy(input_pos, item.data(), item.size_bytes());
input_pos += item.size();
}
}
void raw_decoder::frame_completed(
const from_headset::feedback & feedback,
const to_headset::video_stream_data_shard::view_info_t & view_info)
{
auto item = get_free();
if (not item)
{
spdlog::warn("No image available in pool, discard frame");
return;
}
auto handle = std::make_shared<raw_blit_handle>(
feedback,
view_info,
*item->view_full,
item->image,
item->current_layout,
*item->semaphore,
item->semaphore_val,
item->free);
auto res = device.waitForFences(*fence, true, UINT64_MAX);
if (res != vk::Result::eSuccess)
spdlog::warn("waitForFences failed");
cmd.reset();
cmd.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
if (item->current_layout != vk::ImageLayout::eTransferDstOptimal)
{
item->current_layout = vk::ImageLayout::eTransferDstOptimal;
vk::ImageMemoryBarrier barrier{
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eMemoryWrite,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = item->current_layout,
.image = item->image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.levelCount = 1,
.layerCount = 1,
},
};
cmd.pipelineBarrier(
vk::PipelineStageFlagBits::eAllCommands,
vk::PipelineStageFlagBits::eTransfer,
{},
{},
{},
barrier);
}
std::array regions{
vk::BufferImageCopy{
.imageSubresource = {
.aspectMask = vk::ImageAspectFlagBits::ePlane0,
.layerCount = 1,
},
.imageExtent = {
.width = description.width,
.height = description.height,
.depth = 1,
},
},
vk::BufferImageCopy{
.bufferOffset = vk::DeviceSize(description.width * description.height),
.imageSubresource = {
.aspectMask = vk::ImageAspectFlagBits::ePlane1,
.layerCount = 1,
},
.imageExtent = {
.width = description.width / 2u,
.height = description.height / 2u,
.depth = 1,
},
},
};
cmd.copyBufferToImage(
input[0],
item->image,
item->current_layout,
description.channels == to_headset::video_stream_description::channels_t::colour ? 2 : 1,
regions.data());
vk::ImageMemoryBarrier barrier{
.srcAccessMask = vk::AccessFlagBits::eMemoryWrite,
.dstAccessMask = vk::AccessFlagBits::eMemoryRead,
.oldLayout = item->current_layout,
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.image = item->image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.levelCount = 1,
.layerCount = 1,
},
};
item->current_layout = barrier.newLayout;
cmd.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eFragmentShader,
{},
{},
{},
barrier);
cmd.end();
device.resetFences(*fence);
application::get_queue().lock()->submit(
vk::StructureChain{
vk::SubmitInfo{
.commandBufferCount = 1,
.pCommandBuffers = &cmd,
.signalSemaphoreCount = 1,
.pSignalSemaphores = &*item->semaphore,
},
vk::TimelineSemaphoreSubmitInfo{
.signalSemaphoreValueCount = 1,
.pSignalSemaphoreValues = &++item->semaphore_val,
},
}
.get(),
*fence);
if (auto scene = weak_scene.lock())
scene->push_blit_handle(accumulator, std::move(handle));
std::swap(input[0], input[1]);
input_pos = (uint8_t *)input[0].map();
}
raw_decoder::image * raw_decoder::get_free()
{
for (auto & item: image_pool)
{
if (item.free.exchange(false))
return &item;
}
return nullptr;
}
std::vector<wivrn::video_codec> raw_decoder::supported_codecs()
{
return {video_codec::raw};
}
} // namespace wivrn
+96
View File
@@ -0,0 +1,96 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "decoder.h"
#include "vk/allocation.h"
#include <atomic>
namespace wivrn
{
class raw_decoder : public decoder
{
private:
static const int image_count = 5;
struct image
{
image_allocation image;
vk::raii::ImageView view_full = nullptr;
vk::ImageLayout current_layout = vk::ImageLayout::eUndefined;
std::atomic_bool free = true;
vk::raii::Semaphore semaphore = nullptr;
uint64_t semaphore_val = 0;
};
vk::raii::Device & device;
vk::raii::SamplerYcbcrConversion ycbcr_conversion;
vk::raii::Sampler sampler_;
vk::raii::CommandPool command_pool;
vk::CommandBuffer cmd;
vk::raii::Fence fence;
std::array<image, image_count> image_pool;
std::weak_ptr<scenes::stream> weak_scene;
shard_accumulator * accumulator;
uint64_t current_frame = 0;
std::array<buffer_allocation, 2> input;
uint8_t * input_pos;
from_headset::feedback feedback;
to_headset::video_stream_data_shard::view_info_t view_info;
public:
raw_decoder(vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
uint32_t vk_queue_family_index,
const wivrn::to_headset::video_stream_description::item & description,
uint8_t stream_index,
std::weak_ptr<scenes::stream> scene,
shard_accumulator * accumulator);
void push_data(std::span<std::span<const uint8_t>> data, uint64_t frame_index, bool partial) override;
void frame_completed(
const wivrn::from_headset::feedback & feedback,
const wivrn::to_headset::video_stream_data_shard::view_info_t & view_info) override;
vk::Sampler sampler() override
{
return *sampler_;
}
vk::Extent2D image_size()
{
return {
description.width,
description.height,
};
}
static std::vector<wivrn::video_codec> supported_codecs();
private:
image * get_free();
};
} // namespace wivrn
+10 -10
View File
@@ -18,9 +18,9 @@
*/
#include "shard_accumulator.h"
#include "application.h"
#include "scenes/stream.h"
#include "scenes/stream.h" // IWYU pragma: keep
#include "spdlog/spdlog.h"
#include "xr/instance.h"
namespace wivrn
{
@@ -63,10 +63,10 @@ static bool is_complete(const shard_set & shards)
return true;
}
std::optional<uint16_t> shard_set::insert(data_shard && shard)
std::optional<uint16_t> shard_set::insert(data_shard && shard, xr::instance & instance)
{
if (empty())
feedback.received_first_packet = application::now();
feedback.received_first_packet = instance.now();
auto idx = shard.shard_idx;
if (idx >= data.size())
@@ -121,12 +121,12 @@ void shard_accumulator::push_shard(video_stream_data_shard && shard)
}
else if (frame_diff == 0)
{
auto shard_idx = current.insert(std::move(shard));
auto shard_idx = current.insert(std::move(shard), instance);
try_submit_frame(shard_idx);
}
else if (frame_diff == 1)
{
next.insert(std::move(shard));
next.insert(std::move(shard), instance);
if (is_complete(next))
{
debug_why_not_sent(current);
@@ -186,12 +186,12 @@ void shard_accumulator::try_submit_frame(uint16_t shard_idx)
payload.emplace_back(data_shards[idx]->payload);
bool frame_complete = last_idx == data_shards.size() and data_shards.back()->flags & video_stream_data_shard::end_of_frame;
decoder->push_data(payload, data_shards[shard_idx]->frame_idx, not frame_complete);
decoder_->push_data(payload, data_shards[shard_idx]->frame_idx, not frame_complete);
if (not frame_complete)
return;
current.feedback.received_last_packet = application::now();
current.feedback.received_last_packet = instance.now();
current.feedback.sent_to_decoder = current.feedback.received_last_packet;
data_shard::timing_info_t timing_info = data_shards.back()->timing_info.value_or(data_shard::timing_info_t{});
current.feedback.encode_begin = timing_info.encode_begin;
@@ -206,7 +206,7 @@ void shard_accumulator::try_submit_frame(uint16_t shard_idx)
}
// Try to extract a frame
decoder->frame_completed(current.feedback, *data_shards.front()->view_info);
decoder_->frame_completed(current.feedback, *data_shards.front()->view_info);
send_feedback(current.feedback);
@@ -216,7 +216,7 @@ void shard_accumulator::try_submit_frame(uint16_t shard_idx)
void shard_accumulator::send_feedback(wivrn::from_headset::feedback & feedback)
{
if (not feedback.received_last_packet)
feedback.received_first_packet = application::now();
feedback.received_first_packet = instance.now();
auto scene = weak_scene.lock();
if (scene)
scene->send_feedback(feedback);
+27 -20
View File
@@ -19,27 +19,30 @@
#pragma once
#include <memory>
#include <vulkan/vulkan.hpp>
#ifdef __ANDROID__
#include "decoder/android/android_decoder.h"
using decoder_impl = ::wivrn::android::decoder;
#else
#include "decoder/ffmpeg/ffmpeg_decoder.h"
using decoder_impl = ::wivrn::ffmpeg::decoder;
#endif
#include "decoder.h"
#include "wivrn_packets.h"
#include <memory>
#include <optional>
#include <vector>
#include <vulkan/vulkan_raii.hpp>
namespace xr
{
class instance;
}
namespace scenes
{
class stream;
}
namespace wivrn
{
class shard_accumulator
{
std::shared_ptr<decoder_impl> decoder;
std::shared_ptr<decoder> decoder_;
public:
using data_shard = wivrn::to_headset::video_stream_data_shard;
@@ -50,7 +53,7 @@ public:
void reset(uint64_t frame_index);
bool empty() const;
std::optional<uint16_t> insert(data_shard &&);
std::optional<uint16_t> insert(data_shard &&, xr::instance & instance);
wivrn::from_headset::feedback feedback{};
@@ -70,19 +73,23 @@ private:
shard_set current;
shard_set next;
std::weak_ptr<scenes::stream> weak_scene;
xr::instance & instance;
public:
explicit shard_accumulator(
vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
xr::instance & instance,
uint32_t vk_queue_family_index,
const wivrn::to_headset::video_stream_description::item & description,
float fps,
std::weak_ptr<scenes::stream> scene,
uint8_t stream_index) :
decoder(std::make_shared<decoder_impl>(device, physical_device, description, fps, stream_index, scene, this)),
decoder_(decoder::make(device, physical_device, vk_queue_family_index, description, fps, stream_index, scene, this)),
current(stream_index),
next(stream_index),
weak_scene(scene)
weak_scene(scene),
instance(instance)
{
next.reset(1);
}
@@ -91,20 +98,20 @@ public:
auto & desc() const
{
return decoder->desc();
return decoder_->description;
}
vk::Sampler sampler()
{
return decoder->sampler();
return decoder_->sampler();
}
vk::Extent2D image_size()
const vk::Extent2D extent()
{
return decoder->image_size();
return decoder_->extent();
}
using blit_handle = decoder_impl::blit_handle;
using blit_handle = decoder::blit_handle;
private:
void try_submit_frame(std::optional<uint16_t> shard_idx);
+19 -1
View File
@@ -348,6 +348,24 @@ std::pair<glm::vec3, glm::quat> controller_offset(std::string_view profile, xr::
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:
return {{0, 0, 0.03}, {1, 0, 0, 0}};
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)
{
@@ -367,7 +385,7 @@ std::pair<glm::vec3, glm::quat> controller_offset(std::string_view profile, xr::
{
case xr::spaces::grip_left:
case xr::spaces::grip_right:
return {{0, -0.030, -0.040}, glm::angleAxis(glm::radians(-35.f), glm::vec3{1, 0, 0})};
return {{0, -0.014, -0.048}, glm::angleAxis(glm::radians(-35.060f), glm::vec3{1, 0, 0})};
default:
break;
+2 -3
View File
@@ -18,7 +18,6 @@
#pragma once
#include "application.h"
#include "utils/alignment.h"
#include "vk/allocation.h"
#include <fastgltf/tools.hpp>
@@ -115,10 +114,10 @@ public:
}
}
buffer_allocation copy_to_gpu()
buffer_allocation copy_to_gpu(vk::raii::Device & device)
{
buffer_allocation gpu_buffer{
application::get_device(),
device,
vk::BufferCreateInfo{
.size = bytes.size(),
.usage = usage},
+33 -5
View File
@@ -23,13 +23,41 @@
struct descriptor_set
{
growable_descriptor_pool & growable_pool;
growable_descriptor_pool * growable_pool;
vk::DescriptorPool pool;
vk::raii::DescriptorSet ds;
descriptor_set(const descriptor_set &) = delete;
descriptor_set & operator=(const descriptor_set &) = delete;
descriptor_set(growable_descriptor_pool * growable_pool,
vk::DescriptorPool pool,
vk::raii::DescriptorSet ds) :
growable_pool(growable_pool),
pool(pool),
ds(std::move(ds))
{
}
descriptor_set(descriptor_set && other) :
growable_pool(std::exchange(other.growable_pool, nullptr)),
pool(other.pool),
ds(std::move(other.ds))
{
}
descriptor_set & operator=(descriptor_set && other)
{
std::swap(*this, other);
return *this;
}
~descriptor_set()
{
for (auto & i: growable_pool.pools)
if (not growable_pool)
return;
for (auto & i: growable_pool->pools)
{
if (*i.descriptor_pool == pool)
{
@@ -43,7 +71,7 @@ struct descriptor_set
growable_descriptor_pool::growable_descriptor_pool(
vk::raii::Device & device,
vk::raii::DescriptorSetLayout & layout,
std::span<vk::DescriptorSetLayoutBinding> bindings,
std::span<const vk::DescriptorSetLayoutBinding> bindings,
int descriptorsets_per_pool) :
device(device),
layout_(nullptr),
@@ -84,7 +112,7 @@ std::shared_ptr<vk::raii::DescriptorSet> growable_descriptor_pool::allocate()
i.free_count--;
alloc_info.descriptorPool = *i.descriptor_pool;
auto ds = std::make_shared<descriptor_set>(*this, *i.descriptor_pool, std::move(device.allocateDescriptorSets(alloc_info)[0]));
auto ds = std::make_shared<descriptor_set>(this, *i.descriptor_pool, std::move(device.allocateDescriptorSets(alloc_info)[0]));
return std::shared_ptr<vk::raii::DescriptorSet>(ds, &ds->ds);
}
@@ -103,7 +131,7 @@ std::shared_ptr<vk::raii::DescriptorSet> growable_descriptor_pool::allocate()
alloc_info.descriptorPool = *pools.back().descriptor_pool;
auto ds = std::make_shared<descriptor_set>(*this, *pools.back().descriptor_pool, std::move(device.allocateDescriptorSets(alloc_info)[0]));
auto ds = std::make_shared<descriptor_set>(this, *pools.back().descriptor_pool, std::move(device.allocateDescriptorSets(alloc_info)[0]));
return std::shared_ptr<vk::raii::DescriptorSet>(ds, &ds->ds);
}
+1 -1
View File
@@ -40,7 +40,7 @@ class growable_descriptor_pool
std::vector<pool> pools;
public:
growable_descriptor_pool(vk::raii::Device & device, vk::raii::DescriptorSetLayout & layout, std::span<vk::DescriptorSetLayoutBinding> bindings, int descriptorsets_per_pool = 100);
growable_descriptor_pool(vk::raii::Device & device, vk::raii::DescriptorSetLayout & layout, std::span<const vk::DescriptorSetLayoutBinding> bindings, int descriptorsets_per_pool = 100);
std::shared_ptr<vk::raii::DescriptorSet> allocate();
};
+54 -9
View File
@@ -20,12 +20,14 @@
#include "image_loader.h"
#include "wivrn_config.h"
#include <cstdint>
#if WIVRN_USE_LIBKTX
#include <ktxvulkan.h>
#endif
#include <chrono>
#include <cstdint>
#include <memory>
#include <span>
#include <spdlog/fmt/chrono.h>
#include <spdlog/spdlog.h>
#include <stdexcept>
#include <vulkan/vulkan_raii.hpp>
@@ -160,21 +162,20 @@ int bytes_per_pixel(vk::Format format)
}
} // namespace
image_loader::image_loader(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool) :
image_loader::image_loader(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, thread_safe<vk::raii::Queue> & queue, vk::raii::CommandPool & cb_pool) :
device(device),
queue(queue),
cb_pool(cb_pool)
{
#if WIVRN_USE_LIBKTX
vdi = ktxVulkanDeviceInfo_Create(*physical_device, *device, *queue, *cb_pool, nullptr);
ktxVulkanDeviceInfo_Construct(&vdi, *physical_device, *device, *queue.get_unsafe(), *cb_pool, nullptr);
#endif
}
image_loader::~image_loader()
{
#if WIVRN_USE_LIBKTX
if (vdi)
ktxVulkanDeviceInfo_Destroy(vdi);
ktxVulkanDeviceInfo_Destruct(&vdi);
#endif
}
@@ -381,7 +382,7 @@ void image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::For
vk::SubmitInfo info;
info.setCommandBuffers(*cb);
auto fence = device.createFence(vk::FenceCreateInfo{});
queue.submit(info, *fence);
queue.lock()->submit(info, *fence);
if (auto result = device.waitForFences(*fence, true, 1'000'000'000); result != vk::Result::eSuccess)
throw std::runtime_error("vkWaitForfences: " + vk::to_string(result));
@@ -414,21 +415,28 @@ void image_loader::do_load_ktx(std::span<const std::byte> bytes)
if (err != KTX_SUCCESS)
{
spdlog::info("ktxTexture_CreateFromMemory: error {}", (int)err);
spdlog::warn("ktxTexture_CreateFromMemory: error {}", (int)err);
throw std::runtime_error("ktxTexture_CreateFromMemory");
}
if (ktxTexture_NeedsTranscoding(texture))
{
// TODO
spdlog::warn("ktxTexture_NeedsTranscoding");
throw std::runtime_error("ktxTexture_NeedsTranscoding");
}
{
auto _ = queue.lock(); // ktxTexture_VkUploadEx uses the queue internally (in ktxTexture_VkUploadEx_WithSuballocator)
// TODO: patch vkloader.c to accept a mutex
err = ktxTexture_VkUploadEx(texture, &vdi, &vk_texture, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
}
err = ktxTexture_VkUploadEx(texture, vdi, &vk_texture, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
if (err != KTX_SUCCESS)
{
// TODO try uncompressing the texture
ktxTexture_Destroy(texture);
spdlog::info("ktxTexture_CreateFromMemory: error {}", (int)err);
spdlog::warn("ktxTexture_CreateFromMemory: error {}", (int)err);
throw std::runtime_error("ktxTexture_VkUploadEx");
}
@@ -471,6 +479,41 @@ static constexpr bool starts_with(std::span<const std::byte> data, std::span<con
return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size());
}
template <typename T>
void premultiply_alpha_aux(T * pixels, float alpha_scale, int width, int height)
{
for (int i = 0, n = width * height; i < n; i++)
{
float alpha = pixels[4 * i + 3] * alpha_scale;
pixels[4 * i + 0] = pixels[4 * i + 0] * alpha;
pixels[4 * i + 1] = pixels[4 * i + 1] * alpha;
pixels[4 * i + 2] = pixels[4 * i + 2] * alpha;
}
}
static void premultiply_alpha(void * pixels, vk::Extent3D extent, vk::Format format)
{
switch (format)
{
case vk::Format::eR8G8B8A8Srgb: // TODO: sRGB
case vk::Format::eR8G8B8A8Unorm:
premultiply_alpha_aux<uint8_t>((uint8_t *)pixels, 1. / 255., extent.width, extent.height);
break;
case vk::Format::eR16G16B16A16Unorm:
premultiply_alpha_aux<uint16_t>((uint16_t *)pixels, 1. / 65535., extent.width, extent.height);
break;
case vk::Format::eR32G32B32A32Sfloat:
premultiply_alpha_aux<float>((float *)pixels, 1, extent.width, extent.height);
break;
default:
break;
}
}
// Load a PNG/JPEG/KTX2 file
void image_loader::load(std::span<const std::byte> bytes, bool srgb)
{
@@ -517,6 +560,8 @@ void image_loader::load(std::span<const std::byte> bytes, bool srgb)
extent.height = h;
extent.depth = 1;
premultiply_alpha(pixels.get(), extent, format);
do_load_raw(pixels.get(), extent, format);
}
}
+8 -6
View File
@@ -19,6 +19,7 @@
#pragma once
#include "utils/thread_safe.h"
#include "vk/allocation.h"
#include "vk/fwd.h"
#include "wivrn_config.h"
@@ -31,7 +32,7 @@
#include <vulkan/vulkan.hpp>
#if WIVRN_USE_LIBKTX
struct ktxVulkanDeviceInfo;
#include <ktxvulkan.h>
#endif
struct image_loader
@@ -45,7 +46,10 @@ struct image_loader
uint32_t num_mipmaps;
image_loader(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool);
image_loader(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, thread_safe<vk::raii::Queue> & queue, vk::raii::CommandPool & cb_pool);
image_loader(const image_loader &) = delete;
image_loader & operator=(const image_loader &) = delete;
~image_loader();
// Load a PNG/JPEG/KTX2 file
void load(std::span<const std::byte> bytes, bool srgb);
@@ -71,15 +75,13 @@ struct image_loader
load(pixels.data(), pixels.size() * sizeof(T), extent, format);
}
~image_loader();
private:
#if WIVRN_USE_LIBKTX
ktxVulkanDeviceInfo * vdi = nullptr;
ktxVulkanDeviceInfo vdi;
#endif
vk::raii::Device & device;
vk::raii::Queue & queue;
thread_safe<vk::raii::Queue> & queue;
vk::raii::CommandPool & cb_pool;
buffer_allocation staging_buffer;
+285 -197
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"
@@ -25,6 +26,7 @@
#include "image_loader.h"
#include "openxr/openxr.h"
#include "utils/ranges.h"
#include "utils/strings.h"
#include "vulkan/vulkan_enums.hpp"
#include "vulkan/vulkan_handles.hpp"
#include "vulkan/vulkan_to_string.hpp"
@@ -43,8 +45,6 @@
#include <spdlog/spdlog.h>
#include <string_view>
#include "IconsFontAwesome6.h"
#ifdef __ANDROID__
#include <android/font.h>
#include <android/font_matcher.h>
@@ -178,6 +178,31 @@ static float distance_to_window(ImGuiWindow * window, ImVec2 position)
return std::hypot(dx, dy);
}
static const std::array layout_bindings = {
vk::DescriptorSetLayoutBinding{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
}};
imgui_textures::imgui_textures(
vk::raii::PhysicalDevice physical_device,
vk::raii::Device & device,
uint32_t queue_family_index,
thread_safe<vk::raii::Queue> & queue) :
physical_device(physical_device),
device(device),
queue(queue),
ds_layout(device, vk::DescriptorSetLayoutCreateInfo{.bindingCount = layout_bindings.size(), .pBindings = layout_bindings.data()}),
command_pool(device,
vk::CommandPoolCreateInfo{
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient,
.queueFamilyIndex = queue_family_index,
}),
descriptor_pool(device, ds_layout, layout_bindings)
{}
std::vector<std::pair<ImVec2, float>> imgui_context::ray_plane_intersection(const imgui_context::controller_state & in) const
{
if (!in.active)
@@ -289,38 +314,21 @@ imgui_context::imgui_frame & imgui_context::get_frame(vk::Image destination)
return frame;
}
static const std::array pool_sizes =
{
vk::DescriptorPoolSize{
.type = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = constants::gui::nb_combined_image_samplers,
}};
static const vk::DescriptorSetLayoutBinding layout_bindings{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment};
imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, uint32_t queue_family_index, vk::raii::Queue & queue, std::span<controller> controllers_, xr::swapchain & swapchain, std::vector<viewport> layers) :
physical_device(physical_device),
device(device),
imgui_context::imgui_context(
vk::raii::PhysicalDevice physical_device,
vk::raii::Device & device,
uint32_t queue_family_index,
thread_safe<vk::raii::Queue> & queue,
std::span<controller> controllers_,
xr::swapchain & swapchain,
std::vector<viewport> layers) :
imgui_textures(
physical_device,
device,
queue_family_index,
queue),
queue_family_index(queue_family_index),
queue(queue),
descriptor_pool(device,
vk::DescriptorPoolCreateInfo{
.flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet,
.maxSets = pool_sizes[0].descriptorCount,
.poolSizeCount = pool_sizes.size(),
.pPoolSizes = pool_sizes.data(),
}),
ds_layout(device, vk::DescriptorSetLayoutCreateInfo{.bindingCount = 1, .pBindings = &layout_bindings}),
renderpass(create_renderpass(device, swapchain.format(), true)),
command_pool(device,
vk::CommandPoolCreateInfo{
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient,
.queueFamilyIndex = queue_family_index,
}),
command_buffers(swapchain.images().size()),
size(swapchain.extent().width, swapchain.extent().height),
format(swapchain.format()),
@@ -349,17 +357,17 @@ imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii:
ImGui_ImplVulkan_InitInfo init_info = {
.Instance = *application::get_vulkan_instance(),
.PhysicalDevice = *application::get_physical_device(),
.Device = *application::get_device(),
.QueueFamily = application::queue_family_index(),
.Queue = *application::get_queue(),
.DescriptorPool = *descriptor_pool,
.PhysicalDevice = *physical_device,
.Device = *device,
.QueueFamily = queue_family_index,
.Queue = *queue.get_unsafe(),
.RenderPass = *renderpass,
.MinImageCount = 2,
.ImageCount = (uint32_t)swapchain.images().size(), // used to cycle between VkBuffers in ImGui_ImplVulkan_RenderDrawData
.MSAASamples = VK_SAMPLE_COUNT_1_BIT,
.PipelineCache = *application::get_pipeline_cache(),
.Subpass = 0,
.DescriptorPoolSize = 100,
.Allocator = nullptr,
.CheckVkResultFn = check_vk_result,
};
@@ -382,46 +390,9 @@ imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii:
style.Colors[ImGuiCol_ModalWindowDimBg] = {0, 0, 0, 0};
}
void imgui_context::add_chars(std::string_view sv)
{
for (auto it = sv.begin(); it != sv.end();)
{
ImWchar c = (ImWchar)*it;
if (c < 0x80)
++it;
else
it += ImTextCharFromUtf8(&c, it, sv.end());
if (!glyph_range_builder.GetBit(c))
{
glyph_range_builder.AddChar(c);
glyph_range_dirty = true;
}
}
}
#ifdef __ANDROID__
static std::vector<std::string> find_font(const ImFontGlyphRangesBuilder & glyph_range_builder, const std::string & locale)
static std::vector<std::string> find_font(std::u16string_view sample_text, const std::string & locale)
{
std::u16string wtext;
std::u16string_view wtextview;
for (int i = 0; i < glyph_range_builder.UsedChars.Size; ++i)
{
std::uint32_t used_chars = glyph_range_builder.UsedChars[i];
if (used_chars == 0)
continue;
for (int j = 0; j < 32; ++j)
{
ImWchar c = i * 32 + j;
if (used_chars & (1 << j))
{
wtext += c;
}
}
}
wtextview = wtext;
AFontMatcher * font_matcher = AFontMatcher_create();
if (!font_matcher)
throw std::runtime_error("AFontMatcher_create");
@@ -432,18 +403,18 @@ static std::vector<std::string> find_font(const ImFontGlyphRangesBuilder & glyph
std::vector<std::string> fonts;
while (!wtextview.empty())
while (!sample_text.empty())
{
uint32_t runlength = 0;
AFont * font = AFontMatcher_match(font_matcher, "sans-serif", (uint16_t *)wtextview.data(), wtextview.size(), &runlength);
AFont * font = AFontMatcher_match(font_matcher, "sans-serif", (uint16_t *)sample_text.data(), sample_text.size(), &runlength);
fonts.emplace_back(AFont_getFontFilePath(font));
AFont_close(font);
if (runlength == 0)
break;
wtextview = wtextview.substr(runlength);
sample_text = sample_text.substr(runlength);
}
AFontMatcher_destroy(font_matcher);
@@ -451,7 +422,7 @@ static std::vector<std::string> find_font(const ImFontGlyphRangesBuilder & glyph
return fonts;
}
#else
static std::vector<std::string> find_font(ImFontGlyphRangesBuilder glyph_range_builder, const std::string & locale)
static std::vector<std::string> find_font(std::u16string sample_text, const std::string & locale)
{
// See https://www.camconn.cc/post/how-to-fontconfig-lib-c/
@@ -470,21 +441,8 @@ static std::vector<std::string> find_font(ImFontGlyphRangesBuilder glyph_range_b
// Add the text to the pattern (to determine appropriate characters)
FcCharSet * charset = FcCharSetCreate();
for (int i = 8; i < glyph_range_builder.UsedChars.Size; ++i)
{
std::uint32_t used_chars = glyph_range_builder.UsedChars[i];
if (used_chars == 0)
continue;
for (int j = 0; j < 32; ++j)
{
ImWchar c = i * 32 + j;
if (used_chars & (1 << j))
{
FcCharSetAddChar(charset, c);
}
}
}
for (char16_t c: sample_text)
FcCharSetAddChar(charset, c);
FcPatternAddCharSet(pattern, FC_CHARSET, charset);
FcCharSetDestroy(charset);
@@ -513,28 +471,26 @@ static std::vector<std::string> find_font(ImFontGlyphRangesBuilder glyph_range_b
continue;
bool keep_this_font = false;
for (int i = 0; i < glyph_range_builder.UsedChars.Size; ++i)
{
std::uint32_t & used_chars = glyph_range_builder.UsedChars[i];
if (used_chars == 0)
continue;
for (int j = 0; j < 32; ++j)
std::u16string tmp = sample_text;
for (int i = 0; i < tmp.size();)
{
char16_t c = tmp[i];
if (FcCharSetHasChar(font_charset, c))
{
ImWchar c = i * 32 + j;
if (used_chars & (1 << j))
{
if (FcCharSetHasChar(font_charset, c))
{
keep_this_font = true;
used_chars &= ~(1 << j);
}
}
keep_this_font = true;
tmp[i] = tmp[tmp.size() - 1];
tmp.resize(tmp.size() - 1);
}
else
++i;
}
if (keep_this_font)
fonts.emplace_back((const char *)font_file);
break;
}
FcFontSetDestroy(fs);
@@ -546,71 +502,41 @@ static std::vector<std::string> find_font(ImFontGlyphRangesBuilder glyph_range_b
void imgui_context::initialize_fonts()
{
glyph_ranges.clear();
// Always include Basic Latin and Latin-1 Supplement without control characters
ImWchar default_ranges[] = {0x20, 0x7f, 0xa0, 0xff, 0};
glyph_range_builder.AddRanges(default_ranges);
std::vector<std::string> fonts;
for (auto & [code, glyphs]: glyph_set_per_language)
{
const auto & locale = application::get_messages_info();
auto it = glyph_set_per_language.find(locale.language + "_" + locale.country);
if (it == glyph_set_per_language.end())
it = glyph_set_per_language.find(locale.language);
std::u16string sample_text = u"Hello world";
if (it != glyph_set_per_language.end())
for (char16_t c: glyphs)
sample_text += c;
auto language = code.substr(0, code.find("_"));
// Load Fonts
for (auto && i: find_font(sample_text, language))
{
for (ImWchar c: it->second)
glyph_range_builder.AddChar(c);
spdlog::info("Font for {} {}", code, i);
if (not std::ranges::contains(fonts, i))
fonts.push_back(std::move(i));
}
}
glyph_range_builder.BuildRanges(&glyph_ranges);
// Load Fonts
auto fonts = find_font(glyph_range_builder, application::get_messages_info().language);
for (auto & i: fonts)
{
spdlog::info("Font {}", i);
}
asset font_awesome_regular("Font Awesome 6 Free-Regular-400.otf");
asset font_awesome_solid("Font Awesome 6 Free-Solid-900.otf");
IM_DELETE(io.Fonts);
io.Fonts = IM_NEW(ImFontAtlas);
ImFontConfig config;
config.FontDataOwnedByAtlas = false;
for (auto & font: fonts)
{
ImFontConfig config;
config.FontDataOwnedByAtlas = false;
for (auto & font: fonts)
{
spdlog::info("Using font {}", font, application::get_messages_info().language);
io.Fonts->AddFontFromFileTTF(font.c_str(), constants::gui::font_size_small, &config, glyph_ranges.Data);
config.MergeMode = true;
}
spdlog::info("Using font {}", font, application::get_messages_info().language);
io.Fonts->AddFontFromFileTTF(font.c_str(), constants::gui::font_size_small, &config);
config.MergeMode = true;
config.GlyphMinAdvanceX = 40; // Use if you want to make the icon monospaced
static const ImWchar icon_ranges[] = {ICON_MIN_FA, ICON_MAX_FA, 0};
io.Fonts->AddFontFromMemoryTTF(const_cast<std::byte *>(font_awesome_regular.data()), font_awesome_regular.size(), constants::gui::font_size_small, &config, icon_ranges);
io.Fonts->AddFontFromMemoryTTF(const_cast<std::byte *>(font_awesome_solid.data()), font_awesome_solid.size(), constants::gui::font_size_small, &config, icon_ranges);
}
{
ImFontConfig config;
config.FontDataOwnedByAtlas = false;
for (auto & font: fonts)
{
large_font = io.Fonts->AddFontFromFileTTF(font.c_str(), constants::gui::font_size_large, &config, glyph_ranges.Data);
config.MergeMode = true;
}
}
glyph_range_dirty = false;
ImGui_ImplVulkan_CreateFontsTexture();
config.MergeMode = true;
config.GlyphMinAdvanceX = 40; // Use if you want to make the icon monospaced
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)
@@ -627,6 +553,9 @@ std::vector<imgui_context::controller_state> imgui_context::read_controllers_sta
controller_state & new_state = new_states.emplace_back();
if (not controllers_enabled)
continue;
if (ctrl.hand)
{
if (auto joints = ctrl.hand->locate(world, display_time))
@@ -801,7 +730,7 @@ void imgui_context::new_frame(XrTime display_time)
ImPlot::SetCurrentContext(plot_context);
if (last_display_time)
io.DeltaTime = std::min((display_time - last_display_time) * 1e-9f, 0.1f);
io.DeltaTime = std::clamp((display_time - last_display_time) * 1e-9f, 0.001f, 0.0166f);
last_display_time = display_time;
// Uses the window list from last frame
@@ -831,7 +760,10 @@ void imgui_context::new_frame(XrTime display_time)
io.AddMousePosEvent(position->x, position->y);
if (glm::length(scroll) > constants::gui::scroll_value_thd)
io.AddMouseWheelEvent(scroll.x, scroll.y);
{
io.MouseWheel = scroll.y;
io.MouseWheelH = scroll.x;
}
}
}
@@ -841,24 +773,6 @@ void imgui_context::new_frame(XrTime display_time)
controller.second = next_state;
}
// Force recreation of the font atlas
if (glyph_range_dirty)
{
// Wait for fences before ImGui_ImplVulkan_DestroyFontsTexture is called
std::vector<vk::Fence> fences;
for (auto & f: command_buffers)
{
fences.push_back(*f.fence);
}
if (auto result = device.waitForFences(fences, true, 1'000'000'000); result != vk::Result::eSuccess)
spdlog::error("vkWaitForfences: {}", vk::to_string(result));
ImGui_ImplVulkan_DestroyFontsTexture();
initialize_fonts();
ImGui_ImplVulkan_CreateFontsTexture();
}
// Start the Dear ImGui frame
ImGui_ImplVulkan_NewFrame();
@@ -876,10 +790,20 @@ void imgui_context::new_frame(XrTime display_time)
image_index = swapchain.acquire();
swapchain.wait();
hovered_item_prev = hovered_item;
hovered_item = 0;
}
std::vector<std::pair<int, XrCompositionLayerQuad>> imgui_context::end_frame()
{
if (hovered_item != hovered_item_prev && hovered_item != 0)
{
size_t controller = get_focused_controller();
if (auto haptic_output = controllers[controller].first.haptic_output; haptic_output != XR_NULL_HANDLE)
application::haptic_start(haptic_output, XR_NULL_PATH, 10'000'000, 1000, 1);
}
vk::Image destination = swapchain.images()[image_index].image;
ImGui::SetCurrentContext(context);
@@ -996,17 +920,21 @@ std::vector<std::pair<int, XrCompositionLayerQuad>> imgui_context::end_frame()
.pClearValues = &clear},
vk::SubpassContents::eInline);
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), *cb);
{
auto _ = queue.lock(); // ImGui_ImplVulkan_RenderDrawData uses the queue internally (in ImGui_ImplVulkan_UpdateTexture)
// TODO: patch imgui_impl_vulkan to accept a mutex
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), *cb);
}
cb.endRenderPass();
cb.end();
queue.submit(vk::SubmitInfo{
.commandBufferCount = 1,
.pCommandBuffers = &*cb,
},
*fence);
queue.lock()->submit(vk::SubmitInfo{
.commandBufferCount = 1,
.pCommandBuffers = &*cb,
},
*fence);
swapchain.release();
@@ -1070,6 +998,17 @@ std::vector<std::pair<int, XrCompositionLayerQuad>> imgui_context::end_frame()
return quads;
}
void imgui_context::vibrate_on_hover()
{
if (ImGui::IsItemHovered())
hovered_item = ImGui::GetItemID();
}
void imgui_context::set_hovered_item()
{
hovered_item = ImGui::GetItemID();
}
imgui_context::~imgui_context()
{
ImGui::SetCurrentContext(context);
@@ -1093,17 +1032,18 @@ imgui_context::~imgui_context()
ImGui::DestroyContext(context);
}
ImTextureID imgui_context::load_texture(const std::string & filename, vk::raii::Sampler && sampler)
ImTextureID imgui_textures::load_texture(const std::string & filename, vk::raii::Sampler && sampler)
{
return load_texture(std::span<const std::byte>{asset{filename}}, std::move(sampler));
}
ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & bytes, vk::raii::Sampler && sampler)
{
bool srgb = true;
image_loader loader(physical_device, device, queue, command_pool);
loader.load(asset{filename}, srgb);
loader.load(bytes, srgb);
vk::raii::DescriptorSet ds = std::move(device.allocateDescriptorSets({
.descriptorPool = *descriptor_pool,
.descriptorSetCount = 1,
.pSetLayouts = &*ds_layout,
})[0]);
std::shared_ptr<vk::raii::DescriptorSet> ds = descriptor_pool.allocate();
vk::DescriptorImageInfo image_info{
.sampler = *sampler,
@@ -1112,14 +1052,14 @@ ImTextureID imgui_context::load_texture(const std::string & filename, vk::raii::
};
vk::WriteDescriptorSet ds_write{
.dstSet = *ds,
.dstSet = **ds,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info};
device.updateDescriptorSets(ds_write, nullptr);
ImTextureID id = *ds;
ImTextureID id = reinterpret_cast<ImTextureID>(VkDescriptorSet(**ds));
textures.emplace(
id,
@@ -1133,7 +1073,25 @@ ImTextureID imgui_context::load_texture(const std::string & filename, vk::raii::
return id;
}
ImTextureID imgui_context::load_texture(const std::string & filename)
ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & bytes)
{
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,
},
});
}
ImTextureID imgui_textures::load_texture(const std::string & filename)
{
return load_texture(
filename,
@@ -1143,12 +1101,15 @@ ImTextureID imgui_context::load_texture(const std::string & filename)
.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_context::free_texture(ImTextureID texture)
void imgui_textures::free_texture(ImTextureID texture)
{
textures.erase(texture);
}
@@ -1159,6 +1120,11 @@ void imgui_context::set_current()
ImPlot::SetCurrentContext(plot_context);
}
void imgui_context::set_controllers_enabled(bool value)
{
controllers_enabled = value;
}
bool imgui_context::is_modal_popup_shown() const
{
return ImGui::GetTopMostAndVisiblePopupModal() != nullptr;
@@ -1174,3 +1140,125 @@ imgui_context::viewport & imgui_context::layer(ImVec2 position)
return layers_.front();
}
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(ImGui::GetMousePos());
auto pos_backup = viewport->Pos;
auto size_backup = viewport->Size;
viewport->Pos = ImVec2(current_layer.vp_origin.x, current_layer.vp_origin.y);
viewport->Size = ImVec2(current_layer.vp_size.x, current_layer.vp_size.y);
ImVec2 pos{
(ImGui::GetItemRectMin().x + ImGui::GetItemRectMax().x) / 2,
ImGui::GetItemRectMin().y - constants::style::tooltip_distance,
};
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::tooltip_padding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::tooltip_rounding);
// Clamp position to avoid overflowing on the left or the right
auto & style = ImGui::GetStyle();
const ImVec2 text_size = ImGui::CalcTextSize(text.data(), text.data() + text.size(), true);
const ImVec2 size = {text_size.x + style.WindowPadding.x * 2.0f, text_size.y + style.WindowPadding.y * 2.0f};
pos.x = std::clamp<float>(pos.x, viewport->Pos.x + size.x / 2, viewport->Pos.x + viewport->Size.x - size.x / 2);
ImVec2 pivot = {0.5, 1};
// Move tooltip below the item if it overflows on the top
if (pos.y - size.y <= viewport->Pos.y)
{
pos.y = ImGui::GetItemRectMax().y + constants::style::tooltip_distance;
pivot.y = 0;
}
ImGui::SetNextWindowPos(pos, ImGuiCond_Always, pivot);
if (ImGui::BeginTooltip())
{
ImGui::PushStyleColor(ImGuiCol_Text, 0xffffffff);
ImGui::TextUnformatted(text.data(), text.data() + text.size());
ImGui::PopStyleColor();
ImGui::EndTooltip();
}
ImGui::PopStyleVar(2);
viewport->Pos = pos_backup;
viewport->Size = size_backup;
}
// https://github.com/ocornut/imgui/issues/3379#issuecomment-2943903877
void ScrollWhenDragging()
{
ImVec2 delta{0.0f, -ImGui::GetIO().MouseDelta.y};
const ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
ImGuiContext & g = *ImGui::GetCurrentContext();
ImGuiWindow * window = g.CurrentWindow;
ImGuiID id = window->GetID("##scrolldraggingoverlay");
ImGui::KeepAliveID(id);
static int active_id;
static ImVec2 cumulated_delta;
bool HoveredIdAllowOverlap_backup = std::exchange(g.HoveredIdAllowOverlap, true);
bool ActiveIdAllowOverlap_backup = std::exchange(g.ActiveIdAllowOverlap, true);
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;
// Don't scroll on the first step, in case the active controller just changed
delta = {};
cumulated_delta = {};
}
if (not g.IO.MouseDown[mouse_button])
active_id = 0;
if (active_id == id)
{
if (delta.x != 0.0f)
ImGui::SetScrollX(window, window->Scroll.x + delta.x);
if (delta.y != 0.0f)
ImGui::SetScrollY(window, window->Scroll.y + delta.y);
cumulated_delta += delta;
if (std::max(std::abs(cumulated_delta.x), std::abs(cumulated_delta.y)) > 50)
ImGui::ClearActiveID();
}
g.HoveredIdAllowOverlap = HoveredIdAllowOverlap_backup;
g.ActiveIdAllowOverlap = ActiveIdAllowOverlap_backup;
}
void CenterTextH(const std::string & text)
{
float win_width = ImGui::GetWindowSize().x;
float text_width = ImGui::CalcTextSize(text.c_str()).x;
ImGui::SetCursorPosX((win_width - text_width) / 2);
ImGui::Text("%s", text.c_str());
}
void CenterTextHV(const std::string & text)
{
ImVec2 size = ImGui::GetWindowSize();
std::vector<std::string> lines = utils::split(text);
float text_height = 0;
for (const auto & i: lines)
text_height += ImGui::CalcTextSize(i.c_str()).y;
ImGui::SetCursorPosY((size.y - text_height) / 2);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0});
for (const auto & i: lines)
{
float text_width = ImGui::CalcTextSize(i.c_str()).x;
ImGui::SetCursorPosX((size.x - text_width) / 2);
ImGui::Text("%s", i.c_str());
}
ImGui::PopStyleVar();
}
+51 -25
View File
@@ -18,6 +18,8 @@
#pragma once
#include "render/growable_descriptor_pool.h"
#include "utils/thread_safe.h"
#include "wivrn_config.h"
#include "xr/hand_tracker.h"
#include "xr/space.h"
@@ -34,7 +36,40 @@
#include <vulkan/vulkan_raii.hpp>
#include <openxr/openxr.h>
class imgui_context
class imgui_textures
{
struct texture_data
{
vk::raii::Sampler sampler;
std::shared_ptr<vk::raii::ImageView> image_view;
std::shared_ptr<vk::raii::DescriptorSet> descriptor_set;
};
protected:
vk::raii::PhysicalDevice physical_device;
vk::raii::Device & device;
thread_safe<vk::raii::Queue> & queue;
vk::raii::DescriptorSetLayout ds_layout;
vk::raii::CommandPool command_pool;
private:
growable_descriptor_pool descriptor_pool;
std::unordered_map<ImTextureID, texture_data> textures;
public:
imgui_textures(
vk::raii::PhysicalDevice physical_device,
vk::raii::Device & device,
uint32_t queue_family_index,
thread_safe<vk::raii::Queue> & queue);
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);
ImTextureID load_texture(const std::span<const std::byte> & bytes);
void free_texture(ImTextureID);
};
class imgui_context : public imgui_textures
{
struct command_buffer
{
@@ -42,13 +77,6 @@ class imgui_context
vk::raii::Fence fence = nullptr;
};
struct texture_data
{
vk::raii::Sampler sampler;
std::shared_ptr<vk::raii::ImageView> image_view;
vk::raii::DescriptorSet descriptor_set;
};
public:
struct imgui_frame
{
@@ -67,6 +95,8 @@ public:
XrAction scroll; // XR_ACTION_TYPE_VECTOR2F_INPUT
// TODO: thresholds?
XrAction haptic_output;
xr::hand_tracker * hand = nullptr;
};
@@ -113,18 +143,10 @@ public:
};
private:
vk::raii::PhysicalDevice physical_device;
vk::raii::Device & device;
uint32_t queue_family_index;
vk::raii::Queue & queue;
vk::raii::Pipeline pipeline = nullptr;
vk::raii::DescriptorPool descriptor_pool;
vk::raii::DescriptorSetLayout ds_layout;
vk::raii::RenderPass renderpass;
vk::raii::CommandPool command_pool;
std::unordered_map<ImTextureID, texture_data> textures;
std::vector<imgui_frame> frames;
imgui_frame & get_frame(vk::Image destination);
@@ -153,13 +175,13 @@ private:
XrSpace world;
size_t focused_controller = (size_t)-1;
XrTime last_display_time = 0;
bool controllers_enabled = true;
bool button_pressed = false;
bool fingertip_touching = false;
ImFontGlyphRangesBuilder glyph_range_builder;
ImVector<ImWchar> glyph_ranges;
bool glyph_range_dirty = true;
ImGuiID hovered_item = 0; // Hovered item in the current frame, reset at the beginning of the frame
ImGuiID hovered_item_prev = 0; // Hovered item at the previous frame
#if WIVRN_SHOW_IMGUI_DEMO_WINDOW
bool show_demo_window = true;
@@ -175,7 +197,7 @@ public:
vk::raii::PhysicalDevice physical_device,
vk::raii::Device & device,
uint32_t queue_family_index,
vk::raii::Queue & queue,
thread_safe<vk::raii::Queue> & queue,
std::span<controller> controllers,
xr::swapchain & swapchain,
std::vector<viewport> layers);
@@ -192,7 +214,6 @@ public:
void new_frame(XrTime display_time);
std::vector<std::pair<int, XrCompositionLayerQuad>> end_frame();
ImFont * large_font;
size_t get_focused_controller() const
{
return focused_controller;
@@ -204,11 +225,16 @@ public:
// Convert position from viewport coordinates to real-world
glm::vec3 rw_from_vp(const ImVec2 & position);
ImTextureID load_texture(const std::string & filename, vk::raii::Sampler && sampler);
ImTextureID load_texture(const std::string & filename);
void free_texture(ImTextureID);
void set_current();
void add_chars(std::string_view sv);
bool is_modal_popup_shown() const;
void vibrate_on_hover();
void set_hovered_item();
void set_controllers_enabled(bool value);
void tooltip(std::string_view text);
};
void ScrollWhenDragging();
void CenterTextH(const std::string & text);
void CenterTextHV(const std::string & text);
+79
View File
@@ -0,0 +1,79 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.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 "scene_components.h"
#include <entt/entt.hpp>
#include <spdlog/spdlog.h>
entt::entity find_node_by_name(entt::registry & scene, std::string_view name)
{
for (auto && [entity, node]: scene.view<components::node>().each())
{
if (node.name == name)
return entity;
}
// TODO custom exception
throw std::runtime_error("Node \"" + (std::string)name + "\" not found");
}
entt::entity find_node_by_name(entt::registry & scene, std::string_view name, entt::entity parent)
{
for (auto && [entity, node]: scene.view<components::node>().each())
{
if (node.name != name)
continue;
auto current_parent = node.parent;
do
{
if (current_parent == parent)
return entity;
assert(current_parent != scene.get<components::node>(current_parent).parent);
current_parent = scene.get<components::node>(current_parent).parent;
} while (current_parent != entt::null);
}
// TODO custom exception
throw std::runtime_error("Node \"" + (std::string)name + "\" not found");
}
std::string get_node_name(const entt::registry & scene, entt::entity entity)
{
auto name_parent = [&](entt::entity entity) -> std::pair<std::string, entt::entity> {
const auto & node = scene.get<components::node>(entity);
if (node.name == "")
return {std::to_string((int)entity), node.parent};
else
return {node.name, node.parent};
};
std::string name;
std::tie(name, entity) = name_parent(entity);
while (entity != entt::null)
{
std::string tmp;
std::tie(tmp, entity) = name_parent(entity);
name = tmp + "/" + name;
}
return name;
}
+187
View File
@@ -0,0 +1,187 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.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 <array>
#include <memory>
#include <vector>
#include <entt/entity/entity.hpp>
#include <glm/ext/quaternion_float.hpp>
#include <glm/vec3.hpp>
#include <vulkan/vulkan_raii.hpp>
#include "utils/magic_hash.h"
#include "vk/allocation.h"
namespace renderer
{
struct sampler_info
{
vk::Filter mag_filter = vk::Filter::eLinear;
vk::Filter min_filter = vk::Filter::eLinear;
vk::SamplerMipmapMode min_filter_mipmap = vk::SamplerMipmapMode::eLinear;
vk::SamplerAddressMode wrapS = vk::SamplerAddressMode::eRepeat;
vk::SamplerAddressMode wrapT = vk::SamplerAddressMode::eRepeat;
bool operator==(const sampler_info & other) const noexcept = default;
};
struct texture
{
std::shared_ptr<vk::raii::ImageView> image_view;
sampler_info sampler;
};
struct material
{
struct gpu_data
{
glm::vec4 base_color_factor = glm::vec4(1, 1, 1, 1);
glm::vec4 base_emissive_factor = glm::vec4(0, 0, 0, 0);
float metallic_factor = 1;
float roughness_factor = 1;
float occlusion_strength = 0;
float normal_scale = 0;
uint32_t base_color_texcoord = 0;
uint32_t metallic_roughness_texcoord = 0;
uint32_t occlusion_texcoord = 0;
uint32_t emissive_texcoord = 0;
uint32_t normal_texcoord = 0;
// TODO: add fastgltf::TextureTransform?
};
std::shared_ptr<texture> base_color_texture;
std::shared_ptr<texture> metallic_roughness_texture;
std::shared_ptr<texture> occlusion_texture;
std::shared_ptr<texture> emissive_texture;
std::shared_ptr<texture> normal_texture;
// Disable back face culling with this material
bool double_sided = true;
// TODO transparency
// fastgltf::AlphaMode alphaMode;
// float alpha_cutoff;
gpu_data staging;
// Resources used by this material
std::shared_ptr<buffer_allocation> buffer;
size_t offset;
// The descriptor set is managed by the scene renderer, it is updated whenever ds_dirty is true
// Bindings 0-4: textures
// Binding 5: uniform buffer
std::shared_ptr<vk::raii::DescriptorSet> ds;
// Set to true to update the descriptor set at the next frame
bool ds_dirty;
std::string name;
std::string shader_name = "lit";
bool blend_enable = true;
};
struct primitive
{
bool indexed;
uint32_t index_count;
uint32_t vertex_count;
vk::IndexType index_type;
vk::DeviceSize index_offset;
vk::DeviceSize vertex_offset;
// See also material::double_sided
vk::CullModeFlagBits cull_mode = vk::CullModeFlagBits::eNone;
vk::FrontFace front_face = vk::FrontFace::eClockwise;
vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList;
std::shared_ptr<material> material_;
};
struct mesh
{
std::vector<primitive> primitives;
std::shared_ptr<buffer_allocation> buffer;
};
// TODO move vertex class in .cpp, put vertex description in the primitive
struct vertex
{
glm::vec3 position;
glm::vec3 normal;
glm::vec3 tangent;
std::array<glm::vec2, 2> texcoord;
glm::vec4 color;
std::array<glm::vec4, 1> joints;
std::array<glm::vec4, 1> weights;
struct description
{
vk::VertexInputBindingDescription binding;
std::vector<vk::VertexInputAttributeDescription> attributes;
std::vector<std::string> attribute_names;
vk::PipelineVertexInputStateCreateFlags flags{};
};
static description describe();
};
} // namespace renderer
namespace std
{
template <>
struct hash<renderer::sampler_info> : utils::magic_hash<renderer::sampler_info>
{};
} // namespace std
namespace components
{
struct node
{
entt::entity parent = entt::null;
std::string name;
std::shared_ptr<renderer::mesh> mesh;
glm::vec3 position = {0, 0, 0};
glm::quat orientation = {1, 0, 0, 0};
glm::vec3 scale = {1, 1, 1};
bool visible = true;
uint32_t layer_mask = -1;
std::array<glm::vec4, 4> clipping_planes;
// TODO: separate component?
std::vector<std::pair<entt::entity, glm::mat4>> joints; // Node index, inverse bind matrix of each joint
// For internal use by the renderer
glm::mat4 transform_to_root;
bool global_visible;
bool reverse_side;
uint32_t global_layer_mask;
};
} // namespace components
entt::entity find_node_by_name(entt::registry & scene, std::string_view name);
entt::entity find_node_by_name(entt::registry & scene, std::string_view name, entt::entity parent);
std::string get_node_name(const entt::registry & scene, entt::entity entity);
-992
View File
@@ -1,992 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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 "render/scene_data.h"
#include "image_loader.h"
#include "render/gpu_buffer.h"
#include "utils/fmt_glm.h"
#include "utils/ranges.h"
#include <boost/pfr/core.hpp>
#include <fastgltf/base64.hpp>
#include <fastgltf/core.hpp>
#include <fastgltf/glm_element_traits.hpp>
#include <fastgltf/tools.hpp>
#include <fastgltf/types.hpp>
#include <fastgltf/util.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <ranges>
#include <spdlog/spdlog.h>
#include <stdexcept>
#include <type_traits>
#include <variant>
#include <vk_mem_alloc.h>
#include <vulkan/vulkan_raii.hpp>
#include "asset.h"
template <class T>
constexpr vk::Format vk_attribute_format = vk::Format::eUndefined;
template <>
constexpr vk::Format vk_attribute_format<float> = vk::Format::eR32Sfloat;
template <>
constexpr vk::Format vk_attribute_format<glm::vec2> = vk::Format::eR32G32Sfloat;
template <>
constexpr vk::Format vk_attribute_format<glm::vec3> = vk::Format::eR32G32B32Sfloat;
template <>
constexpr vk::Format vk_attribute_format<glm::vec4> = vk::Format::eR32G32B32A32Sfloat;
template <typename T, size_t N>
constexpr vk::Format vk_attribute_format<std::array<T, N>> = vk_attribute_format<T>;
template <class T>
constexpr size_t nb_attributes = 1;
template <typename T, size_t N>
constexpr size_t nb_attributes<std::array<T, N>> = N;
template <class T>
struct remove_array
{
using type = T;
};
template <class T, size_t N>
struct remove_array<std::array<T, N>>
{
using type = T;
};
template <class T>
using remove_array_t = remove_array<T>::type;
template <class T>
struct is_array : std::false_type
{
};
template <class T, size_t N>
struct is_array<std::array<T, N>> : std::true_type
{
};
template <class T>
constexpr bool is_array_v = is_array<T>::value;
scene_data::vertex::description scene_data::vertex::describe()
{
scene_data::vertex::description desc;
desc.binding = vk::VertexInputBindingDescription{
.binding = 0,
.stride = sizeof(vertex),
.inputRate = vk::VertexInputRate::eVertex,
};
vk::VertexInputAttributeDescription attribute{
.location = 0,
.binding = 0,
};
#define VERTEX_ATTR(member) \
attribute.format = vk_attribute_format<decltype(vertex::member)>; \
for (size_t i = 0; i < nb_attributes<decltype(vertex::member)>; i++) \
{ \
attribute.offset = offsetof(vertex, member) + i * sizeof(remove_array_t<decltype(vertex::member)>); \
desc.attributes.push_back(attribute); \
attribute.location++; \
if (is_array_v<decltype(vertex::member)>) \
{ \
desc.attribute_names.push_back(#member "_" + std::to_string(i)); \
} \
else \
{ \
desc.attribute_names.push_back(#member); \
} \
}
VERTEX_ATTR(position);
VERTEX_ATTR(normal);
VERTEX_ATTR(tangent);
VERTEX_ATTR(texcoord);
VERTEX_ATTR(color);
VERTEX_ATTR(joints);
VERTEX_ATTR(weights);
static_assert(vertex{}.joints.size() == vertex{}.weights.size());
return desc;
}
// Conversion functions gltf -> vulkan
namespace
{
fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::filesystem::path & directory)
{
fastgltf::Parser parser(fastgltf::Extensions::KHR_texture_basisu);
auto gltf_options =
fastgltf::Options::DontRequireValidAssetMember |
fastgltf::Options::AllowDouble |
fastgltf::Options::LoadGLBBuffers |
fastgltf::Options::DecomposeNodeMatrices;
auto expected_asset = parser.loadGltf(&buffer, directory, gltf_options);
if (auto error = expected_asset.error(); error != fastgltf::Error::None)
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
return std::move(expected_asset.get());
}
std::pair<vk::Filter, vk::SamplerMipmapMode> convert(fastgltf::Filter filter)
{
switch (filter)
{
case fastgltf::Filter::Nearest:
case fastgltf::Filter::NearestMipMapNearest:
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest};
case fastgltf::Filter::Linear:
case fastgltf::Filter::LinearMipMapNearest:
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eNearest};
case fastgltf::Filter::NearestMipMapLinear:
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eLinear};
case fastgltf::Filter::LinearMipMapLinear:
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eLinear};
}
throw std::invalid_argument("filter");
}
vk::SamplerAddressMode convert(fastgltf::Wrap wrap)
{
switch (wrap)
{
case fastgltf::Wrap::ClampToEdge:
return vk::SamplerAddressMode::eClampToEdge;
case fastgltf::Wrap::MirroredRepeat:
return vk::SamplerAddressMode::eMirroredRepeat;
case fastgltf::Wrap::Repeat:
return vk::SamplerAddressMode::eRepeat;
}
throw std::invalid_argument("wrap");
}
sampler_info convert(fastgltf::Sampler & sampler)
{
sampler_info info;
info.mag_filter = convert(sampler.magFilter.value_or(fastgltf::Filter::Linear)).first;
std::tie(info.min_filter, info.min_filter_mipmap) = convert(sampler.minFilter.value_or(fastgltf::Filter::LinearMipMapLinear));
info.wrapS = convert(sampler.wrapS);
info.wrapT = convert(sampler.wrapT);
return info;
}
vk::PrimitiveTopology convert(fastgltf::PrimitiveType type)
{
switch (type)
{
case fastgltf::PrimitiveType::Points:
return vk::PrimitiveTopology::ePointList;
case fastgltf::PrimitiveType::Lines:
return vk::PrimitiveTopology::eLineList;
case fastgltf::PrimitiveType::LineLoop:
throw std::runtime_error("Unimplemented");
case fastgltf::PrimitiveType::LineStrip:
return vk::PrimitiveTopology::eLineStrip;
case fastgltf::PrimitiveType::Triangles:
return vk::PrimitiveTopology::eTriangleList;
case fastgltf::PrimitiveType::TriangleStrip:
return vk::PrimitiveTopology::eTriangleStrip;
case fastgltf::PrimitiveType::TriangleFan:
return vk::PrimitiveTopology::eTriangleFan;
}
throw std::invalid_argument("type");
}
glm::vec4 convert(const std::array<float, 4> & v)
{
return {v[0], v[1], v[2], v[3]};
}
glm::vec3 convert(const std::array<float, 3> & v)
{
return {v[0], v[1], v[2]};
}
} // namespace
template <typename T>
requires is_array_v<T>
void copy_vertex_attributes(
const fastgltf::Asset & asset,
const fastgltf::Primitive & primitive,
std::string attribute_name,
std::vector<scene_data::vertex> & vertices,
T scene_data::vertex::*attribute)
{
using U = T::value_type;
constexpr size_t N = std::tuple_size_v<T>;
for (size_t i = 0; i < N; i++)
{
auto it = primitive.findAttribute(attribute_name + std::to_string(i));
if (it == primitive.attributes.end())
continue;
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
if (vertices.size() < accessor.count)
vertices.resize(accessor.count, {});
fastgltf::iterateAccessorWithIndex<U>(asset, accessor, [&](U value, std::size_t idx) {
(vertices[idx].*attribute)[i] = value;
});
}
}
template <typename T>
requires(!is_array_v<T>)
void copy_vertex_attributes(
const fastgltf::Asset & asset,
const fastgltf::Primitive & primitive,
std::string attribute_name,
std::vector<scene_data::vertex> & vertices,
T scene_data::vertex::*attribute)
{
auto it = primitive.findAttribute(attribute_name);
if (it == primitive.attributes.end())
return;
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
if (vertices.size() < accessor.count)
vertices.resize(accessor.count, {});
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](T value, std::size_t idx) {
vertices[idx].*attribute = value;
});
}
namespace
{
constexpr bool starts_with(std::span<const std::byte> data, std::span<const uint8_t> prefix)
{
return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size());
}
fastgltf::MimeType guess_mime_type(std::span<const std::byte> image_data)
{
const uint8_t jpeg_magic[] = {0xFF, 0xD8, 0xFF};
const uint8_t png_magic[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
const uint8_t ktx1_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A};
const uint8_t ktx2_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A};
if (starts_with(image_data, png_magic))
return fastgltf::MimeType::PNG;
else if (starts_with(image_data, jpeg_magic))
return fastgltf::MimeType::JPEG;
else if (starts_with(image_data, ktx1_magic))
return fastgltf::MimeType::KTX2;
else if (starts_with(image_data, ktx2_magic))
return fastgltf::MimeType::KTX2;
else
return fastgltf::MimeType::None;
}
std::shared_ptr<vk::raii::ImageView> do_load_image(
vk::raii::PhysicalDevice & physical_device,
vk::raii::Device & device,
vk::raii::Queue & queue,
vk::raii::CommandPool & cb_pool,
std::span<const std::byte> image_data,
bool srgb)
{
switch (guess_mime_type(image_data))
{
case fastgltf::MimeType::JPEG:
case fastgltf::MimeType::PNG:
case fastgltf::MimeType::KTX2: {
try
{
image_loader loader(physical_device, device, queue, cb_pool);
loader.load(image_data, srgb);
spdlog::debug("Loaded image {}x{}, format {}, {} mipmaps", loader.extent.width, loader.extent.height, vk::to_string(loader.format), loader.num_mipmaps);
return loader.image_view;
}
catch (std::exception & e)
{
spdlog::info("Cannot load image: {}", e.what());
return {};
}
}
default:
spdlog::error("Unsupported image MIME type");
return {};
}
}
class loader_context
{
std::filesystem::path base_directory;
fastgltf::Asset & gltf;
vk::raii::PhysicalDevice physical_device;
vk::raii::Device & device;
vk::raii::Queue & queue;
vk::raii::CommandPool & cb_pool;
std::vector<asset> loaded_assets;
asset & load_from_asset(const std::filesystem::path & path)
{
return loaded_assets.emplace_back(path);
}
public:
loader_context(std::filesystem::path base_directory,
fastgltf::Asset & gltf,
vk::raii::PhysicalDevice physical_device,
vk::raii::Device & device,
vk::raii::Queue & queue,
vk::raii::CommandPool & cb_pool) :
base_directory(base_directory),
gltf(gltf),
physical_device(physical_device),
device(device),
queue(queue),
cb_pool(cb_pool)
{
}
fastgltf::span<const std::byte> load(const fastgltf::URI & uri)
{
auto path = base_directory.empty() ? std::filesystem::path(uri.path()) : base_directory / std::filesystem::path(uri.path());
std::span<const std::byte> bytes;
bytes = load_from_asset(path);
return fastgltf::span<const std::byte>(bytes.data(), bytes.size());
}
fastgltf::span<const std::byte> load(const fastgltf::sources::URI & uri)
{
return load(uri.uri);
}
template <typename T, std::size_t Extent>
fastgltf::span<T, fastgltf::dynamic_extent> subspan(fastgltf::span<T, Extent> span, size_t offset, size_t count = fastgltf::dynamic_extent)
{
assert(offset < span.size());
assert(count == fastgltf::dynamic_extent || count <= span.size() - offset);
if (count == fastgltf::dynamic_extent)
count = span.size() - offset;
return fastgltf::span<T>{span.data() + offset, count};
}
fastgltf::sources::ByteView visit_source(fastgltf::DataSource & source)
{
using return_type = fastgltf::sources::ByteView;
return std::visit(fastgltf::visitor{
[&](std::monostate) -> return_type {
throw std::runtime_error("Invalid source");
},
[&](fastgltf::sources::Fallback) -> return_type {
throw std::runtime_error("Invalid source");
},
[&](const fastgltf::sources::BufferView & buffer_view) -> return_type {
fastgltf::BufferView & view = gltf.bufferViews.at(buffer_view.bufferViewIndex);
fastgltf::Buffer & buffer = gltf.buffers.at(view.bufferIndex);
auto buffer2 = visit_source(buffer.data);
return {subspan(buffer2.bytes, view.byteOffset, view.byteLength), buffer_view.mimeType};
},
[&](const fastgltf::sources::URI & uri) -> return_type {
if (!uri.uri.isLocalPath())
throw std::runtime_error("Non local paths are not supported"); // TODO ?
fastgltf::span<const std::byte> data = load(uri);
// Don't use the MIME type from fastgltf, it's not initialized for URIs
return {subspan(data, uri.fileByteOffset), fastgltf::MimeType::None};
},
[&](const fastgltf::sources::Vector & vector) -> return_type {
fastgltf::span<const std::byte> data{reinterpret_cast<const std::byte *>(vector.bytes.data()), vector.bytes.size()};
return {data, vector.mimeType};
},
[&](const fastgltf::sources::Array & array) -> return_type {
fastgltf::span<const std::byte> data{reinterpret_cast<const std::byte *>(array.bytes.data()), array.bytes.size()};
return {data, array.mimeType};
},
[&](const fastgltf::sources::CustomBuffer & custom_buffer) -> return_type {
throw std::runtime_error("Unimplemented source CustomBuffer");
// TODO ?
},
[&](fastgltf::sources::ByteView & byte_view) -> return_type {
return {byte_view.bytes, byte_view.mimeType};
}},
source);
}
std::unordered_map<int, std::shared_ptr<vk::raii::ImageView>> images;
std::shared_ptr<vk::raii::ImageView> load_image(int index, bool srgb)
{
auto it = images.find(index);
if (it != images.end())
return it->second;
try
{
auto [image_data, mime_type] = visit_source(gltf.images[index].data);
auto image = do_load_image(physical_device, device, queue, cb_pool, image_data, srgb);
images.emplace(index, image);
return image;
}
catch (...)
{
return nullptr;
}
}
std::vector<std::shared_ptr<scene_data::texture>> load_all_textures()
{
// Determine which texture is sRGB
std::vector<uint8_t> srgb_array;
srgb_array.resize(gltf.textures.size(), false);
for (const fastgltf::Material & gltf_material: gltf.materials)
{
if (gltf_material.pbrData.baseColorTexture)
srgb_array.at(gltf_material.pbrData.baseColorTexture->textureIndex) = true;
if (gltf_material.emissiveTexture)
srgb_array.at(gltf_material.emissiveTexture->textureIndex) = true;
}
std::vector<std::shared_ptr<scene_data::texture>> textures;
textures.reserve(gltf.textures.size());
for (auto && [srgb, gltf_texture]: std::views::zip(srgb_array, gltf.textures))
{
auto & texture_ref = *textures.emplace_back(std::make_shared<scene_data::texture>());
if (gltf_texture.samplerIndex)
{
fastgltf::Sampler & sampler = gltf.samplers.at(*gltf_texture.samplerIndex);
texture_ref.sampler = convert(sampler);
}
if (gltf_texture.basisuImageIndex)
{
texture_ref.image_view = load_image(*gltf_texture.basisuImageIndex, srgb);
if (texture_ref.image_view)
continue;
}
// if (gltf_texture.ddsImageIndex)
// {
// // TODO
// }
// if (gltf_texture.webpImageIndex)
// {
// // TODO
// }
if (gltf_texture.imageIndex)
{
texture_ref.image_view = load_image(*gltf_texture.imageIndex, srgb);
if (texture_ref.image_view)
continue;
}
throw std::runtime_error("Unsupported image type");
}
return textures;
}
void load_all_buffers()
{
for (fastgltf::Buffer & buffer: gltf.buffers)
{
if (std::holds_alternative<fastgltf::sources::URI>(buffer.data))
{
fastgltf::sources::URI uri = std::get<fastgltf::sources::URI>(buffer.data);
// Don't use the MIME type from fastgltf, it's not initialized for URIs
buffer.data = fastgltf::sources::ByteView(load(uri), fastgltf::MimeType::None);
}
}
}
std::vector<std::shared_ptr<scene_data::material>> load_all_materials(std::vector<std::shared_ptr<scene_data::texture>> & textures, gpu_buffer & staging_buffer, const scene_data::material & default_material)
{
std::vector<std::shared_ptr<scene_data::material>> materials;
materials.reserve(gltf.materials.size());
for (const fastgltf::Material & gltf_material: gltf.materials)
{
// Copy the default material, without references to its buffer or descriptor set
auto & material_ref = *materials.emplace_back(std::make_shared<scene_data::material>(default_material));
material_ref.name = gltf_material.name;
spdlog::info("Loading material \"{}\"", material_ref.name);
material_ref.buffer.reset();
material_ref.ds.reset();
material_ref.double_sided = gltf_material.doubleSided;
scene_data::material::gpu_data & material_data = material_ref.staging;
material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor);
material_data.base_emissive_factor = glm::vec4(convert(gltf_material.emissiveFactor), 0);
material_data.metallic_factor = gltf_material.pbrData.metallicFactor;
material_data.roughness_factor = gltf_material.pbrData.roughnessFactor;
if (gltf_material.pbrData.baseColorTexture)
{
material_ref.base_color_texture = textures.at(gltf_material.pbrData.baseColorTexture->textureIndex);
material_data.base_color_texcoord = gltf_material.pbrData.baseColorTexture->texCoordIndex;
}
if (gltf_material.pbrData.metallicRoughnessTexture)
{
material_ref.metallic_roughness_texture = textures.at(gltf_material.pbrData.metallicRoughnessTexture->textureIndex);
material_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex;
}
if (gltf_material.occlusionTexture)
{
material_ref.occlusion_texture = textures.at(gltf_material.occlusionTexture->textureIndex);
material_data.occlusion_texcoord = gltf_material.occlusionTexture->texCoordIndex;
material_data.occlusion_strength = gltf_material.occlusionTexture->strength;
}
if (gltf_material.emissiveTexture)
{
material_ref.emissive_texture = textures.at(gltf_material.emissiveTexture->textureIndex);
material_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex;
}
if (gltf_material.normalTexture)
{
material_ref.normal_texture = textures.at(gltf_material.normalTexture->textureIndex);
material_data.normal_texcoord = gltf_material.normalTexture->texCoordIndex;
material_data.normal_scale = gltf_material.normalTexture->scale;
}
material_ref.offset = staging_buffer.add_uniform(material_data);
}
return materials;
}
std::vector<scene_data::mesh> load_all_meshes(std::vector<std::shared_ptr<scene_data::material>> & materials, gpu_buffer & staging_buffer)
{
std::vector<scene_data::mesh> meshes;
meshes.reserve(gltf.meshes.size());
for (const fastgltf::Mesh & gltf_mesh: gltf.meshes)
{
auto & mesh_ref = meshes.emplace_back();
mesh_ref.primitives.reserve(gltf_mesh.primitives.size());
for (const fastgltf::Primitive & gltf_primitive: gltf_mesh.primitives)
{
auto & primitive_ref = mesh_ref.primitives.emplace_back();
if (gltf_primitive.indicesAccessor)
{
fastgltf::Accessor & indices_accessor = gltf.accessors.at(*gltf_primitive.indicesAccessor);
primitive_ref.indexed = true;
primitive_ref.index_offset = staging_buffer.add_indices(indices_accessor);
primitive_ref.index_count = indices_accessor.count;
switch (indices_accessor.componentType)
{
case fastgltf::ComponentType::Byte:
case fastgltf::ComponentType::UnsignedByte:
primitive_ref.index_type = vk::IndexType::eUint8EXT;
break;
case fastgltf::ComponentType::Short:
case fastgltf::ComponentType::UnsignedShort:
primitive_ref.index_type = vk::IndexType::eUint16;
break;
case fastgltf::ComponentType::Int:
case fastgltf::ComponentType::UnsignedInt:
primitive_ref.index_type = vk::IndexType::eUint32;
break;
default:
throw std::runtime_error("Invalid index type");
break;
}
}
else
{
primitive_ref.indexed = false;
}
std::vector<scene_data::vertex> vertices;
copy_vertex_attributes(gltf, gltf_primitive, "POSITION", vertices, &scene_data::vertex::position);
copy_vertex_attributes(gltf, gltf_primitive, "NORMAL", vertices, &scene_data::vertex::normal);
copy_vertex_attributes(gltf, gltf_primitive, "TANGENT", vertices, &scene_data::vertex::tangent);
copy_vertex_attributes(gltf, gltf_primitive, "TEXCOORD_", vertices, &scene_data::vertex::texcoord);
copy_vertex_attributes(gltf, gltf_primitive, "COLOR", vertices, &scene_data::vertex::color);
copy_vertex_attributes(gltf, gltf_primitive, "JOINTS_", vertices, &scene_data::vertex::joints);
copy_vertex_attributes(gltf, gltf_primitive, "WEIGHTS_", vertices, &scene_data::vertex::weights);
primitive_ref.vertex_offset = staging_buffer.add_vertices(vertices);
primitive_ref.vertex_count = vertices.size();
primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC
primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC
primitive_ref.topology = convert(gltf_primitive.type);
if (gltf_primitive.materialIndex)
primitive_ref.material_ = materials.at(*gltf_primitive.materialIndex);
}
}
return meshes;
}
std::vector<scene_data::node> load_all_nodes()
{
std::vector<scene_data::node> unsorted_objects;
unsorted_objects.resize(gltf.nodes.size(), {.parent_id = scene_data::node::root_id});
for (const auto & [index, gltf_node]: utils::enumerate(gltf.nodes))
{
if (gltf_node.meshIndex)
unsorted_objects[index].mesh_id = *gltf_node.meshIndex;
if (gltf_node.skinIndex)
{
auto & skin = gltf.skins.at(*gltf_node.skinIndex);
unsorted_objects[index].joints.resize(skin.joints.size());
for (auto [i, joint_index]: utils::enumerate(skin.joints))
unsorted_objects[index].joints.at(i).first = joint_index;
if (skin.inverseBindMatrices)
{
const fastgltf::Accessor & accessor = gltf.accessors.at(*skin.inverseBindMatrices);
fastgltf::iterateAccessorWithIndex<glm::mat4>(gltf, accessor, [&](const glm::mat4 & value, std::size_t idx) {
unsorted_objects[index].joints.at(idx).second = value;
});
}
}
for (size_t child: gltf_node.children)
{
unsorted_objects[child].parent_id = index;
}
auto TRS = std::get<fastgltf::TRS>(gltf_node.transform);
unsorted_objects[index].position = glm::make_vec3(TRS.translation.data());
unsorted_objects[index].orientation = glm::make_quat(TRS.rotation.data());
unsorted_objects[index].scale = glm::make_vec3(TRS.scale.data());
unsorted_objects[index].visible = true;
unsorted_objects[index].name = gltf_node.name;
std::ranges::fill(unsorted_objects[index].clipping_planes, glm::vec4{0, 0, 0, 1});
}
return unsorted_objects;
}
std::vector<scene_data::node> topological_sort(const std::vector<scene_data::node> & unsorted_nodes)
{
std::vector<scene_data::node> sorted_nodes;
std::vector<size_t> new_index;
std::vector<bool> already_sorted;
sorted_nodes.reserve(unsorted_nodes.size());
already_sorted.resize(unsorted_nodes.size(), false);
new_index.resize(unsorted_nodes.size(), scene_data::node::root_id);
[[maybe_unused]] bool loop_detected = true;
while (sorted_nodes.size() < unsorted_nodes.size())
{
for (size_t i = 0; i < unsorted_nodes.size(); i++)
{
if (already_sorted[i])
continue;
if (unsorted_nodes[i].parent_id == scene_data::node::root_id)
{
sorted_nodes.push_back(unsorted_nodes[i]);
already_sorted[i] = true;
new_index[i] = sorted_nodes.size() - 1;
loop_detected = false;
}
else if (already_sorted[unsorted_nodes[i].parent_id])
{
sorted_nodes.emplace_back(unsorted_nodes[i]).parent_id = new_index[unsorted_nodes[i].parent_id];
already_sorted[i] = true;
new_index[i] = sorted_nodes.size() - 1;
loop_detected = false;
}
}
assert(!loop_detected);
}
// renumber joint indices
for (auto & node: sorted_nodes)
{
for (auto & joint: node.joints)
{
joint.first = new_index[joint.first];
}
}
assert(sorted_nodes.size() == unsorted_nodes.size());
for (size_t i = 0; i < sorted_nodes.size(); i++)
{
assert(sorted_nodes[i].parent_id == scene_data::node::root_id || sorted_nodes[i].parent_id < i);
}
return sorted_nodes;
}
};
} // namespace
scene_data scene_loader::operator()(const std::filesystem::path & gltf_path)
{
vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties();
vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{
.flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = queue_family_index,
}};
scene_data data;
asset asset_file(gltf_path);
fastgltf::GltfDataBuffer data_buffer;
data_buffer.copyBytes(reinterpret_cast<const uint8_t *>(asset_file.data()), asset_file.size());
fastgltf::Asset asset = load_gltf_asset(data_buffer, gltf_path.parent_path());
loader_context ctx(gltf_path.parent_path(), asset, physical_device, device, queue, cb_pool);
#ifndef NDEBUG
if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None)
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
#endif
// Load all buffers from URIs
ctx.load_all_buffers();
gpu_buffer staging_buffer(physical_device_properties, asset);
// Load all textures
auto textures = ctx.load_all_textures();
// Load all materials
auto materials = ctx.load_all_materials(textures, staging_buffer, *default_material);
// Load all meshes
data.meshes = ctx.load_all_meshes(materials, staging_buffer);
data.scene_nodes = ctx.topological_sort(ctx.load_all_nodes());
// Copy the staging buffer to the GPU
spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size());
auto buffer = std::make_shared<buffer_allocation>(staging_buffer.copy_to_gpu());
for (auto & i: materials)
i->buffer = buffer;
for (auto & i: data.meshes)
i.buffer = buffer;
return data;
}
scene_data & scene_data::import(scene_data && other, node_handle parent)
{
assert(parent.scene == this || parent.id == node::root_id);
size_t mesh_offset = meshes.size();
size_t nodes_offset = scene_nodes.size();
for (auto & mesh: other.meshes)
meshes.push_back(std::move(mesh));
for (auto node: other.scene_nodes)
{
assert(!node.mesh_id || *node.mesh_id < other.meshes.size());
if (node.mesh_id)
*node.mesh_id += mesh_offset;
for (auto & joint: node.joints)
{
joint.first += nodes_offset;
}
if (node.parent_id == node::root_id)
{
node.parent_id = parent.id;
}
else
{
assert(node.parent_id < other.scene_nodes.size());
node.parent_id += nodes_offset;
}
scene_nodes.push_back(node);
}
other.meshes.clear();
other.scene_nodes.clear();
return *this;
}
scene_data & scene_data::import(scene_data && other)
{
return import(std::move(other), {});
}
node_handle scene_data::new_node()
{
size_t id = scene_nodes.size();
scene_nodes.push_back(node{
.parent_id = node::root_id,
.position = {0, 0, 0},
.orientation = {1, 0, 0, 0},
.scale = {1, 1, 1},
.visible = true});
return {id, this};
}
node_handle scene_data::find_node(std::string_view name)
{
for (auto && [index, node]: utils::enumerate(scene_nodes))
{
if (node.name == name)
{
return {index, this};
}
}
// TODO custom exception
throw std::runtime_error("Node " + std::string(name) + " not found");
}
node_handle scene_data::find_node(node_handle root, std::string_view name)
{
assert(root.id < scene_nodes.size());
assert(root.scene == this);
std::vector<bool> flag(scene_nodes.size(), false);
flag[root.id] = true;
for (size_t index = root.id; index < scene_nodes.size(); index++)
{
size_t parent = scene_nodes[index].parent_id;
if (parent == node::root_id)
continue;
if (!flag[parent])
continue;
if (scene_nodes[index].name == name)
return {index, this};
flag[index] = true;
}
// TODO custom exception
throw std::runtime_error("Node " + std::string(name) + " not found");
}
std::vector<node_handle> scene_data::find_children(node_handle root)
{
assert(root.id < scene_nodes.size());
assert(root.scene == this);
std::vector<bool> flag(scene_nodes.size(), false);
flag[root.id] = true;
std::vector<node_handle> nodes;
for (size_t index = root.id; index < scene_nodes.size(); index++)
{
size_t parent = scene_nodes[index].parent_id;
if (parent == node::root_id)
continue;
if (!flag[parent])
continue;
nodes.emplace_back(index, this);
flag[index] = true;
}
return nodes;
}
std::shared_ptr<scene_data::material> scene_data::find_material(std::string_view name)
{
for (auto & mesh: meshes)
{
for (auto & primitive: mesh.primitives)
{
if (primitive.material_ && primitive.material_->name == name)
return primitive.material_;
}
}
return {};
}
-295
View File
@@ -1,295 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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 "utils/magic_hash.h"
#include <array>
#include <cstdint>
#include <filesystem>
#include <glm/ext/quaternion_float.hpp>
#include <glm/mat4x4.hpp>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include <vk/allocation.h>
#include <vulkan/vulkan_raii.hpp>
struct sampler_info
{
vk::Filter mag_filter = vk::Filter::eLinear;
vk::Filter min_filter = vk::Filter::eLinear;
vk::SamplerMipmapMode min_filter_mipmap = vk::SamplerMipmapMode::eLinear;
vk::SamplerAddressMode wrapS = vk::SamplerAddressMode::eRepeat;
vk::SamplerAddressMode wrapT = vk::SamplerAddressMode::eRepeat;
bool operator==(const sampler_info & other) const noexcept = default;
};
namespace std
{
template <>
struct hash<sampler_info> : utils::magic_hash<sampler_info>
{};
} // namespace std
class node_handle;
struct scene_data
{
struct texture
{
std::shared_ptr<vk::raii::ImageView> image_view;
sampler_info sampler;
};
struct material
{
struct gpu_data
{
glm::vec4 base_color_factor = glm::vec4(1, 1, 1, 1);
glm::vec4 base_emissive_factor = glm::vec4(0, 0, 0, 0);
float metallic_factor = 1;
float roughness_factor = 1;
float occlusion_strength = 0;
float normal_scale = 0;
uint32_t base_color_texcoord = 0;
uint32_t metallic_roughness_texcoord = 0;
uint32_t occlusion_texcoord = 0;
uint32_t emissive_texcoord = 0;
uint32_t normal_texcoord = 0;
// TODO: add fastgltf::TextureTransform?
};
std::shared_ptr<texture> base_color_texture;
std::shared_ptr<texture> metallic_roughness_texture;
std::shared_ptr<texture> occlusion_texture;
std::shared_ptr<texture> emissive_texture;
std::shared_ptr<texture> normal_texture;
// Disable back face culling with this material
bool double_sided = true;
// TODO transparency
// fastgltf::AlphaMode alphaMode;
// float alpha_cutoff;
gpu_data staging;
// Resources used by this material
std::shared_ptr<buffer_allocation> buffer;
size_t offset;
// The descriptor set is managed by the scene renderer, it is updated whenever ds_dirty is true
// Bindings 0-4: textures
// Binding 5: uniform buffer
std::shared_ptr<vk::raii::DescriptorSet> ds;
// Set to true to update the descriptor set at the next frame
bool ds_dirty;
std::string name;
std::string shader_name = "lit";
bool blend_enable = true;
};
struct vertex
{
glm::vec3 position;
glm::vec3 normal;
glm::vec3 tangent;
std::array<glm::vec2, 2> texcoord;
glm::vec4 color;
std::array<glm::vec4, 1> joints;
std::array<glm::vec4, 1> weights;
struct description
{
vk::VertexInputBindingDescription binding;
std::vector<vk::VertexInputAttributeDescription> attributes;
std::vector<std::string> attribute_names;
vk::PipelineVertexInputStateCreateFlags flags{};
};
static description describe();
};
struct primitive
{
bool indexed;
uint32_t index_count;
uint32_t vertex_count;
vk::IndexType index_type;
vk::DeviceSize index_offset;
vk::DeviceSize vertex_offset;
// See also material::double_sided
vk::CullModeFlagBits cull_mode = vk::CullModeFlagBits::eNone;
vk::FrontFace front_face = vk::FrontFace::eClockwise;
vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList;
std::shared_ptr<material> material_;
};
struct mesh
{
std::vector<primitive> primitives;
std::shared_ptr<buffer_allocation> buffer;
};
struct node
{
static constexpr size_t root_id = size_t(-1);
size_t parent_id;
std::optional<size_t> mesh_id;
glm::vec3 position;
glm::quat orientation;
glm::vec3 scale;
std::string name;
bool visible;
std::array<glm::vec4, 4> clipping_planes;
uint32_t layer_mask = 1;
std::vector<std::pair<size_t, glm::mat4>> joints; // Node index, inverse bind matrix of each joint
};
// TODO: lights
// TODO: skybox
std::vector<scene_data::mesh> meshes;
std::vector<scene_data::node> scene_nodes;
scene_data() = default;
scene_data(const scene_data &) = delete;
scene_data(scene_data &&) = default;
scene_data & operator=(const scene_data &) = delete;
scene_data & operator=(scene_data &&) = default;
scene_data & import(scene_data && other, node_handle parent);
scene_data & import(scene_data && other);
node_handle new_node();
node_handle find_node(std::string_view name);
node_handle find_node(node_handle parent, std::string_view name);
std::vector<node_handle> find_children(node_handle parent);
std::shared_ptr<material> find_material(std::string_view name);
};
class scene_loader
{
vk::raii::Device & device;
vk::raii::PhysicalDevice physical_device;
vk::raii::Queue & queue;
uint32_t queue_family_index;
std::shared_ptr<scene_data::material> default_material;
public:
scene_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, uint32_t queue_family_index, std::shared_ptr<scene_data::material> default_material) :
device(device),
physical_device(physical_device),
queue(queue),
queue_family_index(queue_family_index),
default_material(default_material)
{}
scene_data operator()(const std::filesystem::path & gltf_path);
};
class node_handle
{
friend struct scene_data;
size_t id = scene_data::node::root_id;
scene_data * scene = nullptr;
public:
node_handle() = default;
node_handle(size_t id, scene_data * scene) :
id(id), scene(scene) {}
node_handle(const node_handle &) = default;
node_handle & operator=(const node_handle &) = default;
scene_data::node & operator*()
{
assert(scene != nullptr);
assert(id < scene->scene_nodes.size());
return scene->scene_nodes[id];
}
const scene_data::node & operator*() const
{
assert(scene != nullptr);
assert(id < scene->scene_nodes.size());
return scene->scene_nodes[id];
}
scene_data::node * operator->()
{
assert(scene != nullptr);
assert(id < scene->scene_nodes.size());
return &scene->scene_nodes[id];
}
const scene_data::node * operator->() const
{
assert(scene != nullptr);
assert(id < scene->scene_nodes.size());
return &scene->scene_nodes[id];
}
node_handle parent()
{
assert(scene != nullptr);
assert(id < scene->scene_nodes.size());
return {scene->scene_nodes[id].parent_id, scene};
}
const node_handle parent() const
{
assert(scene != nullptr);
assert(id < scene->scene_nodes.size());
return {scene->scene_nodes[id].parent_id, scene};
}
std::vector<node_handle> children()
{
assert(scene != nullptr);
return scene->find_children(*this);
}
operator bool() const
{
return id != scene_data::node::root_id;
}
};
+840
View File
@@ -0,0 +1,840 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.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 "scene_loader.h"
#include "asset.h"
#include "gpu_buffer.h"
#include "image_loader.h"
#include "render/scene_components.h"
#include "utils/ranges.h"
#include <entt/entt.hpp>
#include <fastgltf/base64.hpp>
#include <fastgltf/core.hpp>
#include <fastgltf/glm_element_traits.hpp>
#include <fastgltf/tools.hpp>
#include <fastgltf/types.hpp>
#include <fastgltf/util.hpp>
#include <glm/ext.hpp>
#include <ranges>
#include <spdlog/spdlog.h>
namespace
{
// BEGIN Utility functions
template <class T>
constexpr vk::Format vk_attribute_format = vk::Format::eUndefined;
template <>
constexpr vk::Format vk_attribute_format<float> = vk::Format::eR32Sfloat;
template <>
constexpr vk::Format vk_attribute_format<glm::vec2> = vk::Format::eR32G32Sfloat;
template <>
constexpr vk::Format vk_attribute_format<glm::vec3> = vk::Format::eR32G32B32Sfloat;
template <>
constexpr vk::Format vk_attribute_format<glm::vec4> = vk::Format::eR32G32B32A32Sfloat;
template <typename T, size_t N>
constexpr vk::Format vk_attribute_format<std::array<T, N>> = vk_attribute_format<T>;
template <class T>
constexpr size_t nb_attributes = 1;
template <typename T, size_t N>
constexpr size_t nb_attributes<std::array<T, N>> = N;
template <class T>
struct remove_array
{
using type = T;
};
template <class T, size_t N>
struct remove_array<std::array<T, N>>
{
using type = T;
};
template <class T>
using remove_array_t = remove_array<T>::type;
template <class T>
struct is_array : std::false_type
{
};
template <class T, size_t N>
struct is_array<std::array<T, N>> : std::true_type
{
};
template <class T>
constexpr bool is_array_v = is_array<T>::value;
// END
// BEGIN GLTF -> Vulkan conversion functions
std::pair<vk::Filter, vk::SamplerMipmapMode> convert(fastgltf::Filter filter)
{
switch (filter)
{
case fastgltf::Filter::Nearest:
case fastgltf::Filter::NearestMipMapNearest:
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest};
case fastgltf::Filter::Linear:
case fastgltf::Filter::LinearMipMapNearest:
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eNearest};
case fastgltf::Filter::NearestMipMapLinear:
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eLinear};
case fastgltf::Filter::LinearMipMapLinear:
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eLinear};
}
throw std::invalid_argument("filter");
}
vk::SamplerAddressMode convert(fastgltf::Wrap wrap)
{
switch (wrap)
{
case fastgltf::Wrap::ClampToEdge:
return vk::SamplerAddressMode::eClampToEdge;
case fastgltf::Wrap::MirroredRepeat:
return vk::SamplerAddressMode::eMirroredRepeat;
case fastgltf::Wrap::Repeat:
return vk::SamplerAddressMode::eRepeat;
}
throw std::invalid_argument("wrap");
}
renderer::sampler_info convert(fastgltf::Sampler & sampler)
{
renderer::sampler_info info;
info.mag_filter = convert(sampler.magFilter.value_or(fastgltf::Filter::Linear)).first;
std::tie(info.min_filter, info.min_filter_mipmap) = convert(sampler.minFilter.value_or(fastgltf::Filter::LinearMipMapLinear));
info.wrapS = convert(sampler.wrapS);
info.wrapT = convert(sampler.wrapT);
return info;
}
vk::PrimitiveTopology convert(fastgltf::PrimitiveType type)
{
switch (type)
{
case fastgltf::PrimitiveType::Points:
return vk::PrimitiveTopology::ePointList;
case fastgltf::PrimitiveType::Lines:
return vk::PrimitiveTopology::eLineList;
case fastgltf::PrimitiveType::LineLoop:
throw std::runtime_error("Unimplemented");
case fastgltf::PrimitiveType::LineStrip:
return vk::PrimitiveTopology::eLineStrip;
case fastgltf::PrimitiveType::Triangles:
return vk::PrimitiveTopology::eTriangleList;
case fastgltf::PrimitiveType::TriangleStrip:
return vk::PrimitiveTopology::eTriangleStrip;
case fastgltf::PrimitiveType::TriangleFan:
return vk::PrimitiveTopology::eTriangleFan;
}
throw std::invalid_argument("type");
}
glm::vec4 convert(const std::array<float, 4> & v)
{
return {v[0], v[1], v[2], v[3]};
}
glm::vec3 convert(const std::array<float, 3> & v)
{
return {v[0], v[1], v[2]};
}
// END
// BEGIN Vertex attributes loading
template <typename T>
requires is_array_v<T>
void copy_vertex_attributes(
const fastgltf::Asset & asset,
const fastgltf::Primitive & primitive,
std::string attribute_name,
std::vector<renderer::vertex> & vertices,
T renderer::vertex::*attribute)
{
using U = T::value_type;
constexpr size_t N = std::tuple_size_v<T>;
for (size_t i = 0; i < N; i++)
{
auto it = primitive.findAttribute(attribute_name + std::to_string(i));
if (it == primitive.attributes.end())
continue;
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
if (vertices.size() < accessor.count)
vertices.resize(accessor.count, {});
fastgltf::iterateAccessorWithIndex<U>(asset, accessor, [&](U value, std::size_t idx) {
(vertices[idx].*attribute)[i] = value;
});
}
}
template <typename T>
requires(!is_array_v<T>)
void copy_vertex_attributes(
const fastgltf::Asset & asset,
const fastgltf::Primitive & primitive,
std::string attribute_name,
std::vector<renderer::vertex> & vertices,
T renderer::vertex::*attribute)
{
auto it = primitive.findAttribute(attribute_name);
if (it == primitive.attributes.end())
return;
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
if (vertices.size() < accessor.count)
vertices.resize(accessor.count, {});
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](T value, std::size_t idx) {
vertices[idx].*attribute = value;
});
}
// END
// BEGIN Image loading
constexpr bool starts_with(std::span<const std::byte> data, std::span<const uint8_t> prefix)
{
return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size());
}
fastgltf::MimeType guess_mime_type(std::span<const std::byte> image_data)
{
const uint8_t jpeg_magic[] = {0xFF, 0xD8, 0xFF};
const uint8_t png_magic[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
const uint8_t ktx1_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A};
const uint8_t ktx2_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A};
if (starts_with(image_data, png_magic))
return fastgltf::MimeType::PNG;
else if (starts_with(image_data, jpeg_magic))
return fastgltf::MimeType::JPEG;
else if (starts_with(image_data, ktx1_magic))
return fastgltf::MimeType::KTX2;
else if (starts_with(image_data, ktx2_magic))
return fastgltf::MimeType::KTX2;
else
return fastgltf::MimeType::None;
}
std::shared_ptr<vk::raii::ImageView> do_load_image(
vk::raii::PhysicalDevice & physical_device,
vk::raii::Device & device,
thread_safe<vk::raii::Queue> & queue,
vk::raii::CommandPool & cb_pool,
std::span<const std::byte> image_data,
bool srgb)
{
switch (guess_mime_type(image_data))
{
case fastgltf::MimeType::JPEG:
case fastgltf::MimeType::PNG:
case fastgltf::MimeType::KTX2: {
try
{
image_loader loader(physical_device, device, queue, cb_pool);
loader.load(image_data, srgb);
spdlog::debug("Loaded image {}x{}, format {}, {} mipmaps", loader.extent.width, loader.extent.height, vk::to_string(loader.format), loader.num_mipmaps);
return loader.image_view;
}
catch (std::exception & e)
{
spdlog::info("Cannot load image: {}", e.what());
return {};
}
}
default:
spdlog::error("Unsupported image MIME type");
return {};
}
}
// END
fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::filesystem::path & directory)
{
fastgltf::Parser parser(fastgltf::Extensions::KHR_texture_basisu);
auto gltf_options =
fastgltf::Options::DontRequireValidAssetMember |
fastgltf::Options::AllowDouble |
fastgltf::Options::LoadGLBBuffers |
fastgltf::Options::DecomposeNodeMatrices;
auto expected_asset = parser.loadGltf(&buffer, directory, gltf_options);
if (auto error = expected_asset.error(); error != fastgltf::Error::None)
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
return std::move(expected_asset.get());
}
class loader_context
{
std::filesystem::path base_directory;
fastgltf::Asset & gltf;
vk::raii::PhysicalDevice physical_device;
vk::raii::Device & device;
thread_safe<vk::raii::Queue> & queue;
vk::raii::CommandPool & cb_pool;
std::vector<asset> loaded_assets;
asset & load_from_asset(const std::filesystem::path & path)
{
return loaded_assets.emplace_back(path);
}
public:
loader_context(std::filesystem::path base_directory,
fastgltf::Asset & gltf,
vk::raii::PhysicalDevice physical_device,
vk::raii::Device & device,
thread_safe<vk::raii::Queue> & queue,
vk::raii::CommandPool & cb_pool) :
base_directory(base_directory),
gltf(gltf),
physical_device(physical_device),
device(device),
queue(queue),
cb_pool(cb_pool)
{
}
fastgltf::span<const std::byte> load(const fastgltf::URI & uri)
{
auto path = base_directory.empty() ? std::filesystem::path(uri.path()) : base_directory / std::filesystem::path(uri.path());
std::span<const std::byte> bytes;
bytes = load_from_asset(path);
return fastgltf::span<const std::byte>(bytes.data(), bytes.size());
}
fastgltf::span<const std::byte> load(const fastgltf::sources::URI & uri)
{
return load(uri.uri);
}
template <typename T, std::size_t Extent>
fastgltf::span<T, fastgltf::dynamic_extent> subspan(fastgltf::span<T, Extent> span, size_t offset, size_t count = fastgltf::dynamic_extent)
{
assert(offset < span.size());
assert(count == fastgltf::dynamic_extent || count <= span.size() - offset);
if (count == fastgltf::dynamic_extent)
count = span.size() - offset;
return fastgltf::span<T>{span.data() + offset, count};
}
fastgltf::sources::ByteView visit_source(fastgltf::DataSource & source)
{
using return_type = fastgltf::sources::ByteView;
return std::visit(fastgltf::visitor{
[&](std::monostate) -> return_type {
throw std::runtime_error("Invalid source");
},
[&](fastgltf::sources::Fallback) -> return_type {
throw std::runtime_error("Invalid source");
},
[&](const fastgltf::sources::BufferView & buffer_view) -> return_type {
fastgltf::BufferView & view = gltf.bufferViews.at(buffer_view.bufferViewIndex);
fastgltf::Buffer & buffer = gltf.buffers.at(view.bufferIndex);
auto buffer2 = visit_source(buffer.data);
return {subspan(buffer2.bytes, view.byteOffset, view.byteLength), buffer_view.mimeType};
},
[&](const fastgltf::sources::URI & uri) -> return_type {
if (!uri.uri.isLocalPath())
throw std::runtime_error("Non local paths are not supported"); // TODO ?
fastgltf::span<const std::byte> data = load(uri);
// Don't use the MIME type from fastgltf, it's not initialized for URIs
return {subspan(data, uri.fileByteOffset), fastgltf::MimeType::None};
},
[&](const fastgltf::sources::Vector & vector) -> return_type {
fastgltf::span<const std::byte> data{reinterpret_cast<const std::byte *>(vector.bytes.data()), vector.bytes.size()};
return {data, vector.mimeType};
},
[&](const fastgltf::sources::Array & array) -> return_type {
fastgltf::span<const std::byte> data{reinterpret_cast<const std::byte *>(array.bytes.data()), array.bytes.size()};
return {data, array.mimeType};
},
[&](const fastgltf::sources::CustomBuffer & custom_buffer) -> return_type {
throw std::runtime_error("Unimplemented source CustomBuffer");
// TODO ?
},
[&](fastgltf::sources::ByteView & byte_view) -> return_type {
return {byte_view.bytes, byte_view.mimeType};
}},
source);
}
std::unordered_map<int, std::shared_ptr<vk::raii::ImageView>> images;
std::shared_ptr<vk::raii::ImageView> load_image(int index, bool srgb)
{
auto it = images.find(index);
if (it != images.end())
return it->second;
try
{
auto [image_data, mime_type] = visit_source(gltf.images[index].data);
auto image = do_load_image(physical_device, device, queue, cb_pool, image_data, srgb);
images.emplace(index, image);
return image;
}
catch (...)
{
return nullptr;
}
}
std::vector<std::shared_ptr<renderer::texture>> load_all_textures()
{
// Determine which texture is sRGB
std::vector<uint8_t> srgb_array;
srgb_array.resize(gltf.textures.size(), false);
for (const fastgltf::Material & gltf_material: gltf.materials)
{
if (gltf_material.pbrData.baseColorTexture)
srgb_array.at(gltf_material.pbrData.baseColorTexture->textureIndex) = true;
if (gltf_material.emissiveTexture)
srgb_array.at(gltf_material.emissiveTexture->textureIndex) = true;
}
std::vector<std::shared_ptr<renderer::texture>> textures;
textures.reserve(gltf.textures.size());
for (auto && [srgb, gltf_texture]: std::views::zip(srgb_array, gltf.textures))
{
auto & texture_ref = *textures.emplace_back(std::make_shared<renderer::texture>());
if (gltf_texture.samplerIndex)
{
fastgltf::Sampler & sampler = gltf.samplers.at(*gltf_texture.samplerIndex);
texture_ref.sampler = convert(sampler);
}
if (gltf_texture.basisuImageIndex)
{
texture_ref.image_view = load_image(*gltf_texture.basisuImageIndex, srgb);
if (texture_ref.image_view)
continue;
}
// if (gltf_texture.ddsImageIndex)
// {
// // TODO
// }
// if (gltf_texture.webpImageIndex)
// {
// // TODO
// }
if (gltf_texture.imageIndex)
{
texture_ref.image_view = load_image(*gltf_texture.imageIndex, srgb);
if (texture_ref.image_view)
continue;
}
throw std::runtime_error("Unsupported image type");
}
return textures;
}
void load_all_buffers()
{
for (fastgltf::Buffer & buffer: gltf.buffers)
{
if (std::holds_alternative<fastgltf::sources::URI>(buffer.data))
{
fastgltf::sources::URI uri = std::get<fastgltf::sources::URI>(buffer.data);
// Don't use the MIME type from fastgltf, it's not initialized for URIs
buffer.data = fastgltf::sources::ByteView(load(uri), fastgltf::MimeType::None);
}
}
}
std::vector<std::shared_ptr<renderer::material>> load_all_materials(std::vector<std::shared_ptr<renderer::texture>> & textures, gpu_buffer & staging_buffer, const renderer::material & default_material)
{
std::vector<std::shared_ptr<renderer::material>> materials;
materials.reserve(gltf.materials.size());
for (const fastgltf::Material & gltf_material: gltf.materials)
{
// Copy the default material, without references to its buffer or descriptor set
auto & material_ref = *materials.emplace_back(std::make_shared<renderer::material>(default_material));
material_ref.name = gltf_material.name;
spdlog::info("Loading material \"{}\"", material_ref.name);
material_ref.buffer.reset();
material_ref.ds.reset();
material_ref.double_sided = gltf_material.doubleSided;
material_ref.blend_enable = gltf_material.alphaMode == fastgltf::AlphaMode::Blend; // TODO handle alpha cut off mode
renderer::material::gpu_data & material_data = material_ref.staging;
material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor);
material_data.base_emissive_factor = glm::vec4(convert(gltf_material.emissiveFactor), 0);
material_data.metallic_factor = gltf_material.pbrData.metallicFactor;
material_data.roughness_factor = gltf_material.pbrData.roughnessFactor;
if (gltf_material.pbrData.baseColorTexture)
{
material_ref.base_color_texture = textures.at(gltf_material.pbrData.baseColorTexture->textureIndex);
material_data.base_color_texcoord = gltf_material.pbrData.baseColorTexture->texCoordIndex;
}
if (gltf_material.pbrData.metallicRoughnessTexture)
{
material_ref.metallic_roughness_texture = textures.at(gltf_material.pbrData.metallicRoughnessTexture->textureIndex);
material_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex;
}
if (gltf_material.occlusionTexture)
{
material_ref.occlusion_texture = textures.at(gltf_material.occlusionTexture->textureIndex);
material_data.occlusion_texcoord = gltf_material.occlusionTexture->texCoordIndex;
material_data.occlusion_strength = gltf_material.occlusionTexture->strength;
}
if (gltf_material.emissiveTexture)
{
material_ref.emissive_texture = textures.at(gltf_material.emissiveTexture->textureIndex);
material_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex;
}
if (gltf_material.normalTexture)
{
material_ref.normal_texture = textures.at(gltf_material.normalTexture->textureIndex);
material_data.normal_texcoord = gltf_material.normalTexture->texCoordIndex;
material_data.normal_scale = gltf_material.normalTexture->scale;
}
material_ref.offset = staging_buffer.add_uniform(material_data);
}
return materials;
}
std::vector<std::shared_ptr<renderer::mesh>> load_all_meshes(std::vector<std::shared_ptr<renderer::material>> & materials, gpu_buffer & staging_buffer)
{
std::vector<std::shared_ptr<renderer::mesh>> meshes;
meshes.reserve(gltf.meshes.size());
for (const fastgltf::Mesh & gltf_mesh: gltf.meshes)
{
std::shared_ptr<renderer::mesh> & mesh_ref = meshes.emplace_back();
mesh_ref = std::make_shared<renderer::mesh>();
mesh_ref->primitives.reserve(gltf_mesh.primitives.size());
for (const fastgltf::Primitive & gltf_primitive: gltf_mesh.primitives)
{
auto & primitive_ref = mesh_ref->primitives.emplace_back();
if (gltf_primitive.indicesAccessor)
{
fastgltf::Accessor & indices_accessor = gltf.accessors.at(*gltf_primitive.indicesAccessor);
primitive_ref.indexed = true;
primitive_ref.index_offset = staging_buffer.add_indices(indices_accessor);
primitive_ref.index_count = indices_accessor.count;
switch (indices_accessor.componentType)
{
case fastgltf::ComponentType::Byte:
case fastgltf::ComponentType::UnsignedByte:
primitive_ref.index_type = vk::IndexType::eUint8EXT;
break;
case fastgltf::ComponentType::Short:
case fastgltf::ComponentType::UnsignedShort:
primitive_ref.index_type = vk::IndexType::eUint16;
break;
case fastgltf::ComponentType::Int:
case fastgltf::ComponentType::UnsignedInt:
primitive_ref.index_type = vk::IndexType::eUint32;
break;
default:
throw std::runtime_error("Invalid index type");
break;
}
}
else
{
primitive_ref.indexed = false;
}
std::vector<renderer::vertex> vertices;
copy_vertex_attributes(gltf, gltf_primitive, "POSITION", vertices, &renderer::vertex::position);
copy_vertex_attributes(gltf, gltf_primitive, "NORMAL", vertices, &renderer::vertex::normal);
copy_vertex_attributes(gltf, gltf_primitive, "TANGENT", vertices, &renderer::vertex::tangent);
copy_vertex_attributes(gltf, gltf_primitive, "TEXCOORD_", vertices, &renderer::vertex::texcoord);
copy_vertex_attributes(gltf, gltf_primitive, "COLOR", vertices, &renderer::vertex::color);
copy_vertex_attributes(gltf, gltf_primitive, "JOINTS_", vertices, &renderer::vertex::joints);
copy_vertex_attributes(gltf, gltf_primitive, "WEIGHTS_", vertices, &renderer::vertex::weights);
primitive_ref.vertex_offset = staging_buffer.add_vertices(vertices);
primitive_ref.vertex_count = vertices.size();
primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC
primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC
primitive_ref.topology = convert(gltf_primitive.type);
if (gltf_primitive.materialIndex)
primitive_ref.material_ = materials.at(*gltf_primitive.materialIndex);
}
}
return meshes;
}
entt::registry load_all_nodes(const std::vector<std::shared_ptr<renderer::mesh>> & meshes)
{
entt::registry registry;
std::vector<entt::entity> entities{gltf.nodes.size()};
registry.create(entities.begin(), entities.end());
// Create all node components first
registry.insert<components::node>(entities.begin(), entities.end());
for (const auto & [entity, gltf_node]: std::ranges::zip_view(entities, gltf.nodes))
{
components::node & node = registry.get<components::node>(entity);
node.name = gltf_node.name;
if (gltf_node.meshIndex)
node.mesh = meshes[*gltf_node.meshIndex];
if (gltf_node.skinIndex)
{
auto & skin = gltf.skins.at(*gltf_node.skinIndex);
node.joints.resize(skin.joints.size());
for (auto [i, joint_index]: utils::enumerate(skin.joints))
node.joints.at(i).first = entities[joint_index];
if (skin.inverseBindMatrices)
{
const fastgltf::Accessor & accessor = gltf.accessors.at(*skin.inverseBindMatrices);
fastgltf::iterateAccessorWithIndex<glm::mat4>(gltf, accessor, [&](const glm::mat4 & value, std::size_t idx) {
node.joints.at(idx).second = value;
});
}
}
for (size_t child: gltf_node.children)
{
registry.get<components::node>(entities[child]).parent = entity;
}
auto TRS = std::get<fastgltf::TRS>(gltf_node.transform);
node.position = glm::make_vec3(TRS.translation.data());
node.orientation = glm::make_quat(TRS.rotation.data());
node.scale = glm::make_vec3(TRS.scale.data());
node.visible = true;
std::ranges::fill(node.clipping_planes, glm::vec4{0, 0, 0, 1});
}
return registry;
}
};
} // namespace
renderer::vertex::description renderer::vertex::describe()
{
renderer::vertex::description desc;
desc.binding = vk::VertexInputBindingDescription{
.binding = 0,
.stride = sizeof(vertex),
.inputRate = vk::VertexInputRate::eVertex,
};
vk::VertexInputAttributeDescription attribute{
.location = 0,
.binding = 0,
};
#define VERTEX_ATTR(member) \
attribute.format = vk_attribute_format<decltype(vertex::member)>; \
for (size_t i = 0; i < nb_attributes<decltype(vertex::member)>; i++) \
{ \
attribute.offset = offsetof(vertex, member) + i * sizeof(remove_array_t<decltype(vertex::member)>); \
desc.attributes.push_back(attribute); \
attribute.location++; \
if (is_array_v<decltype(vertex::member)>) \
{ \
desc.attribute_names.push_back(#member "_" + std::to_string(i)); \
} \
else \
{ \
desc.attribute_names.push_back(#member); \
} \
}
VERTEX_ATTR(position);
VERTEX_ATTR(normal);
VERTEX_ATTR(tangent);
VERTEX_ATTR(texcoord);
VERTEX_ATTR(color);
VERTEX_ATTR(joints);
VERTEX_ATTR(weights);
static_assert(vertex{}.joints.size() == vertex{}.weights.size());
return desc;
}
entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path)
{
vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties();
vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{
.flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = queue_family_index,
}};
spdlog::debug("Loading {}", gltf_path.native());
asset asset_file(gltf_path);
fastgltf::GltfDataBuffer data_buffer;
data_buffer.copyBytes(reinterpret_cast<const uint8_t *>(asset_file.data()), asset_file.size());
fastgltf::Asset asset = load_gltf_asset(data_buffer, gltf_path.parent_path());
loader_context ctx(gltf_path.parent_path(), asset, physical_device, device, queue, cb_pool);
#ifndef NDEBUG
if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None)
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
#endif
// Load all buffers from URIs
ctx.load_all_buffers();
gpu_buffer staging_buffer(physical_device_properties, asset);
// Load all textures
auto textures = ctx.load_all_textures();
// Load all materials
auto materials = ctx.load_all_materials(textures, staging_buffer, *default_material);
// Load all meshes
auto meshes = ctx.load_all_meshes(materials, staging_buffer);
// Load all nodes
entt::registry loaded_scene = ctx.load_all_nodes(meshes);
// Copy the staging buffer to the GPU
spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size());
auto buffer = std::make_shared<buffer_allocation>(staging_buffer.copy_to_gpu(device));
for (auto & i: materials)
i->buffer = buffer;
for (auto & i: meshes)
i->buffer = buffer;
return loaded_scene;
}
template <typename T>
void copy_components(entt::registry & scene, const entt::registry & prefab, const std::unordered_map<entt::entity, entt::entity> & entity_map)
{
for (const auto & [entity, component]: prefab.view<T>().each())
{
scene.emplace<T>(entity_map.at(entity), component);
}
}
void scene_loader::add_prefab(entt::registry & scene, const entt::registry & prefab, entt::entity root)
{
assert(scene.valid(root) or root == entt::null);
auto prefab_entities = prefab.view<entt::entity>();
std::vector<entt::entity> scene_entities{prefab_entities.size()};
scene.create(scene_entities.begin(), scene_entities.end());
std::unordered_map<entt::entity, entt::entity> entity_map; // key: prefab entity, value: scene entity
entity_map.emplace(entt::null, root);
for (auto [prefab_entity, scene_entity]: std::ranges::zip_view(prefab_entities, scene_entities))
entity_map.emplace(prefab_entity, scene_entity);
copy_components<components::node>(scene, prefab, entity_map);
// update links
for (auto [prefab_entity, scene_entity]: entity_map)
{
if (prefab_entity == entt::null)
continue;
auto & node = scene.get<components::node>(scene_entity);
node.parent = entity_map.at(node.parent);
for (auto & joint: node.joints)
{
joint.first = entity_map.at(joint.first);
}
}
}
+47
View File
@@ -0,0 +1,47 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.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 <filesystem>
#include <vulkan/vulkan_raii.hpp>
#include "scene_components.h"
#include "utils/thread_safe.h"
class scene_loader
{
vk::raii::Device & device;
vk::raii::PhysicalDevice physical_device;
thread_safe<vk::raii::Queue> & queue;
uint32_t queue_family_index;
std::shared_ptr<renderer::material> default_material;
public:
scene_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, thread_safe<vk::raii::Queue> & queue, uint32_t queue_family_index, std::shared_ptr<renderer::material> default_material) :
device(device),
physical_device(physical_device),
queue(queue),
queue_family_index(queue_family_index),
default_material(default_material)
{}
entt::registry operator()(const std::filesystem::path & gltf_path);
void add_prefab(entt::registry & scene, const entt::registry & prefab, entt::entity root = entt::null);
};
+369 -282
View File
@@ -21,24 +21,26 @@
#include "application.h"
#include "render/growable_descriptor_pool.h"
#include "render/image_loader.h"
#include "render/scene_data.h"
#include "render/scene_components.h"
#include "utils/alignment.h"
#include "utils/fmt_glm.h"
#include "utils/ranges.h"
#include "vk/allocation.h"
#include "vk/pipeline.h"
#include "vk/shader.h"
#include "vk/specialization_constants.h"
#include <boost/pfr/core.hpp>
#include <entt/entity/entity.hpp>
#include <entt/entt.hpp>
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/quaternion.hpp>
#include <map>
#include <memory>
#include <ranges>
#include <spdlog/spdlog.h>
#include <vk_mem_alloc.h>
extern const std::map<std::string, std::vector<uint32_t>> shaders;
#include <vulkan/vulkan_enums.hpp>
#include <vulkan/vulkan_structs.hpp>
// TODO move in lobby?
vk::Format scene_renderer::find_usable_image_format(
@@ -74,7 +76,7 @@ vk::Format scene_renderer::find_usable_image_format(
return vk::Format::eUndefined;
}
std::shared_ptr<scene_data::texture> scene_renderer::create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel)
std::shared_ptr<renderer::texture> scene_renderer::create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel)
{
vk::Format format;
@@ -99,12 +101,12 @@ std::shared_ptr<scene_data::texture> scene_renderer::create_default_texture(vk::
std::shared_ptr<vk::raii::ImageView> image_view = loader.image_view;
return std::make_shared<scene_data::texture>(image_view, sampler_info{});
return std::make_shared<renderer::texture>(image_view, renderer::sampler_info{});
}
std::shared_ptr<scene_data::material> scene_renderer::create_default_material(vk::raii::CommandPool & cb_pool)
std::shared_ptr<renderer::material> scene_renderer::create_default_material(vk::raii::CommandPool & cb_pool)
{
auto default_material = std::make_shared<scene_data::material>();
auto default_material = std::make_shared<renderer::material>();
default_material->name = "default";
default_material->base_color_texture = create_default_texture(cb_pool, {255, 255, 255, 255});
@@ -198,25 +200,16 @@ static std::array layout_bindings_1{
scene_renderer::scene_renderer(
vk::raii::Device & device,
vk::raii::PhysicalDevice physical_device,
vk::raii::Queue & queue,
thread_safe<vk::raii::Queue> & queue,
vk::raii::CommandPool & cb_pool,
vk::Extent2D output_size,
vk::Format output_format,
// std::span<vk::Format> depth_formats,
vk::Format depth_format,
int frames_in_flight,
bool keep_depth_buffer) :
int frames_in_flight) :
physical_device(physical_device),
device(device),
physical_device_properties(physical_device.getProperties()),
queue(queue),
output_size(output_size),
output_format(output_format),
depth_format(depth_format),
layout_0(create_descriptor_set_layout(layout_bindings_0, vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR)),
layout_1(create_descriptor_set_layout(layout_bindings_1)),
ds_pool_material(device, layout_1, layout_bindings_1, 100), // TODO tunable
keep_depth_buffer(keep_depth_buffer)
ds_pool_material(device, layout_1, layout_bindings_1, 100) // TODO tunable
{
// Create the default material
default_material = create_default_material(cb_pool);
@@ -243,8 +236,6 @@ scene_renderer::scene_renderer(
.queryCount = uint32_t(2 * frames_in_flight),
});
renderpass = create_renderpass();
std::array layouts{*layout_0, *layout_1};
pipeline_layout = create_pipeline_layout(layouts);
}
@@ -264,40 +255,40 @@ void scene_renderer::wait_idle()
throw std::runtime_error("vkWaitForfences: " + vk::to_string(result));
}
// #define MSAA_4x
vk::raii::RenderPass & scene_renderer::get_renderpass(const renderpass_info & info)
{
auto it = renderpasses.find(info);
if (it != renderpasses.end())
return it->second;
#ifdef MSAA_4x
#define MSAA_SAMPLES vk::SampleCountFlagBits::e4
#else
#define MSAA_SAMPLES vk::SampleCountFlagBits::e1
#endif
return renderpasses.emplace(info, create_renderpass(info)).first->second;
}
vk::raii::RenderPass scene_renderer::create_renderpass()
vk::raii::RenderPass scene_renderer::create_renderpass(const renderpass_info & info_)
{
vk::RenderPassCreateInfo info;
std::array attachments = {
vk::AttachmentDescription{
.format = output_format,
.samples = MSAA_SAMPLES,
.format = info_.color_format,
.samples = info_.msaa_samples,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eStore,
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
},
vk::AttachmentDescription{
.format = depth_format,
.samples = MSAA_SAMPLES,
.format = info_.depth_format,
.samples = info_.msaa_samples,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = keep_depth_buffer ? vk::AttachmentStoreOp::eStore : vk::AttachmentStoreOp::eDontCare,
.storeOp = info_.keep_depth_buffer ? vk::AttachmentStoreOp::eStore : vk::AttachmentStoreOp::eDontCare,
.stencilLoadOp = vk::AttachmentLoadOp::eClear,
.stencilStoreOp = vk::AttachmentStoreOp::eDontCare,
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal,
},
#ifdef MSAA_4x
vk::AttachmentDescription{
.format = output_format,
.format = info_.color_format,
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eDontCare,
.storeOp = vk::AttachmentStoreOp::eStore,
@@ -306,10 +297,17 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
}
#endif
};
info.setAttachments(attachments);
}};
if (info_.msaa_samples != vk::SampleCountFlagBits::e1)
{
info.setAttachments(attachments);
}
else
{
info.setPAttachments(attachments.data());
info.setAttachmentCount(2);
}
vk::AttachmentReference color_attachment{
.attachment = 0,
@@ -321,22 +319,22 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal,
};
#ifdef MSAA_4x
// Only used if MSAA is enabled
vk::AttachmentReference resolve_attachment{
.attachment = 2,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
};
#endif
vk::SubpassDescription subpasses{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
.colorAttachmentCount = 1,
.pColorAttachments = &color_attachment,
#ifdef MSAA_4x
.pResolveAttachments = &resolve_attachment,
#endif
.pDepthStencilAttachment = &depth_attachment,
};
if (info_.msaa_samples != vk::SampleCountFlagBits::e1)
subpasses.pResolveAttachments = &resolve_attachment;
info.setSubpasses(subpasses);
std::array dependencies{
@@ -361,53 +359,53 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
return vk::raii::RenderPass(device, info);
}
scene_renderer::output_image & scene_renderer::get_output_image_data(vk::Image output_color, vk::Image output_depth)
scene_renderer::output_image & scene_renderer::get_output_image_data(const output_image_info & info)
{
std::pair images{output_color, output_depth};
auto it = output_images.find(images);
auto it = output_images.find(info);
if (it != output_images.end())
return it->second;
return output_images.emplace(images, create_output_image_data(output_color, output_depth)).first->second;
return output_images.emplace(info, create_output_image_data(info)).first->second;
}
scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image output_color, vk::Image output_depth)
scene_renderer::output_image scene_renderer::create_output_image_data(const output_image_info & info)
{
output_image out;
// TODO: use image view from xr::swapchain
out.image_view = vk::raii::ImageView(
device, vk::ImageViewCreateInfo{
.image = output_color,
.image = info.color,
.viewType = vk::ImageViewType::e2D,
.format = output_format,
.format = info.renderpass.color_format,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.baseArrayLayer = info.base_array_layer,
.layerCount = 1,
},
});
// TODO: check requiredFlags
if (not output_depth)
if (not info.depth)
out.depth_buffer = image_allocation{
device,
vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = depth_format,
.format = info.renderpass.depth_format,
.extent = {
.width = output_size.width,
.height = output_size.height,
.width = info.output_size.width,
.height = info.output_size.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = MSAA_SAMPLES,
.samples = info.renderpass.msaa_samples,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment},
.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
@@ -417,77 +415,87 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image
out.depth_view = vk::raii::ImageView(
device,
vk::ImageViewCreateInfo{
.image = output_depth ? output_depth : out.depth_buffer,
.image = info.depth ? info.depth : out.depth_buffer,
.viewType = vk::ImageViewType::e2D,
.format = depth_format,
.format = info.renderpass.depth_format,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eDepth,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.baseArrayLayer = info.depth ? info.base_array_layer : 0,
.layerCount = 1,
},
});
#ifdef MSAA_4x
out.multisample_image = image_allocation{vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = output_format,
.extent = {
.width = output_size.width,
.height = output_size.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = MSAA_SAMPLES,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check
.preferredFlags = VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT,
}};
if (info.renderpass.msaa_samples != vk::SampleCountFlagBits::e1)
{
out.multisample_image = image_allocation{
device,
vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = info.renderpass.color_format,
.extent = {
.width = info.output_size.width,
.height = info.output_size.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = info.renderpass.msaa_samples,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check
.preferredFlags = VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT,
}};
out.multisample_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{
.image = out.multisample_image,
.viewType = vk::ImageViewType::e2D,
.format = output_format,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
});
#endif
out.multisample_view = vk::raii::ImageView(
device,
vk::ImageViewCreateInfo{
.image = out.multisample_image,
.viewType = vk::ImageViewType::e2D,
.format = info.renderpass.color_format,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
});
}
vk::FramebufferCreateInfo fb_info{
.renderPass = *renderpass,
.width = output_size.width,
.height = output_size.height,
.renderPass = *get_renderpass(info.renderpass),
.width = info.output_size.width,
.height = info.output_size.height,
.layers = 1,
};
#ifdef MSAA_4x
std::array attachments{
vk::ImageView{*out.multisample_view},
vk::ImageView{*out.depth_view},
vk::ImageView{*out.image_view},
};
#else
std::array attachments{
vk::ImageView{*out.image_view},
vk::ImageView{*out.depth_view},
};
#endif
fb_info.setAttachments(attachments);
out.framebuffer = vk::raii::Framebuffer(device, fb_info);
if (info.renderpass.msaa_samples != vk::SampleCountFlagBits::e1)
{
std::array attachments{
vk::ImageView{*out.multisample_view},
vk::ImageView{*out.depth_view},
vk::ImageView{*out.image_view},
};
fb_info.setAttachments(attachments);
out.framebuffer = vk::raii::Framebuffer(device, fb_info);
}
else
{
std::array attachments{
vk::ImageView{*out.image_view},
vk::ImageView{*out.depth_view},
};
fb_info.setAttachments(attachments);
out.framebuffer = vk::raii::Framebuffer(device, fb_info);
}
return out;
}
@@ -518,41 +526,18 @@ vk::raii::PipelineLayout scene_renderer::create_pipeline_layout(std::span<vk::De
vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
{
auto vertex_description = scene_data::vertex::describe();
auto vertex_description = renderer::vertex::describe();
spdlog::debug("Creating pipeline");
auto vertex_shader = load_shader(device, info.shader_name + ".vert");
auto fragment_shader = load_shader(device, info.shader_name + ".frag");
std::array specialization_constants_desc{
vk::SpecializationMapEntry{
.constantID = 0,
.offset = offsetof(pipeline_info, nb_texcoords),
.size = sizeof(int32_t),
},
vk::SpecializationMapEntry{
.constantID = 1,
.offset = offsetof(pipeline_info, dithering),
.size = sizeof(VkBool32),
},
vk::SpecializationMapEntry{
.constantID = 2,
.offset = offsetof(pipeline_info, alpha_cutout),
.size = sizeof(VkBool32),
},
vk::SpecializationMapEntry{
.constantID = 3,
.offset = offsetof(pipeline_info, skinning),
.size = sizeof(VkBool32),
}};
vk::SpecializationInfo specialization{
.mapEntryCount = specialization_constants_desc.size(),
.pMapEntries = specialization_constants_desc.data(),
.dataSize = sizeof(pipeline_info),
.pData = &info,
};
auto specialization = make_specialization_constants(
int32_t(info.nb_texcoords),
VkBool32(info.dithering),
VkBool32(info.alpha_cutout),
VkBool32(info.skinning));
return vk::raii::Pipeline{
device,
@@ -563,14 +548,14 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.pName = "main",
.pSpecializationInfo = &specialization,
.pSpecializationInfo = specialization,
},
vk::PipelineShaderStageCreateInfo{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.pName = "main",
.pSpecializationInfo = &specialization,
.pSpecializationInfo = specialization,
},
},
@@ -580,18 +565,8 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
.topology = info.topology,
.primitiveRestartEnable = false,
}},
.Viewports = {vk::Viewport{
.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1,
}},
.Scissors = {vk::Rect2D{
.offset = {0, 0},
.extent = output_size,
}},
.Viewports = {vk::Viewport{}}, // Dynamic scissor / viewport but the count must be set
.Scissors = {vk::Rect2D{}},
.RasterizationState = {vk::PipelineRasterizationStateCreateInfo{
.polygonMode = vk::PolygonMode::eFill,
.cullMode = info.cull_mode,
@@ -599,7 +574,7 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
.lineWidth = 1.0,
}},
.MultisampleState = {vk::PipelineMultisampleStateCreateInfo{
.rasterizationSamples = MSAA_SAMPLES,
.rasterizationSamples = info.renderpass.msaa_samples,
}},
.DepthStencilState = {vk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = info.depth_test_enable,
@@ -619,13 +594,17 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
.dstAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha,
.alphaBlendOp = vk::BlendOp::eAdd,
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA}},
.DynamicStates = {
vk::DynamicState::eViewport,
vk::DynamicState::eScissor,
},
.layout = *pipeline_layout,
.renderPass = *renderpass,
.renderPass = *get_renderpass(info.renderpass),
.subpass = 0,
}};
}
vk::Sampler scene_renderer::get_sampler(const sampler_info & info)
vk::Sampler scene_renderer::get_sampler(const renderer::sampler_info & info)
{
auto it = samplers.find(info);
if (it != samplers.end())
@@ -702,11 +681,11 @@ void scene_renderer::end_frame()
f.cb.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, *query_pool, current_frame_index * 2 + 1);
f.cb.end();
queue.submit(vk::SubmitInfo{
.commandBufferCount = 1,
.pCommandBuffers = &*f.cb,
},
*f.fence);
queue.lock()->submit(vk::SubmitInfo{
.commandBufferCount = 1,
.pCommandBuffers = &*f.cb,
},
*f.fence);
f.query_pool_filled = true;
}
@@ -715,14 +694,14 @@ scene_renderer::per_frame_resources & scene_renderer::current_frame()
return frame_resources[current_frame_index];
}
void scene_renderer::update_material_descriptor_set(scene_data::material & material)
void scene_renderer::update_material_descriptor_set(renderer::material & material)
{
if (!material.ds || !material.ds.unique())
if (!material.ds || material.ds.use_count() != 1)
material.ds = ds_pool_material.allocate();
vk::DescriptorSet ds = **material.ds;
auto f = [&](std::shared_ptr<scene_data::texture> & texture) {
auto f = [&](std::shared_ptr<renderer::texture> & texture) {
return vk::DescriptorImageInfo{
.sampler = get_sampler(texture->sampler),
.imageView = **texture->image_view,
@@ -741,7 +720,7 @@ void scene_renderer::update_material_descriptor_set(scene_data::material & mater
vk::DescriptorBufferInfo write_ds_buffer{
.buffer = *material.buffer,
.offset = material.offset,
.range = sizeof(scene_data::material::gpu_data),
.range = sizeof(renderer::material::gpu_data),
};
// Write each descriptor separately because the HTC XR Elite needs it for some reason
@@ -793,24 +772,74 @@ void scene_renderer::update_material_descriptor_set(scene_data::material & mater
device.updateDescriptorSets(write_ds, {});
}
// static void print_scene_hierarchy(const scene_data& scene, std::span<glm::mat4> model_matrices, size_t root = scene_data::node::root_id, int level = 0)
[[maybe_unused]] static void print_scene_hierarchy(const entt::registry & scene, entt::entity root = entt::null, int level = 0)
{
if (level == 0)
spdlog::info("Node hierarchy:");
for (auto && [entity, node]: scene.view<components::node>().each())
{
if (node.parent != root)
continue;
// glm::mat4 M = model_matrices[index];
// glm::vec4 pos = glm::column(M, 3);
// spdlog::info("{:{}} {} pos={}, rot={}, pos to root={}", "", level * 2, node.name, node.translation, node.rotation, glm::vec3(pos));
spdlog::info("{:{}} {} ({}, visible: {}, {})", "", level * 2, node.name, (int)entity, node.visible, node.global_visible);
print_scene_hierarchy(scene, entity, level + 1);
}
if (level == 0)
spdlog::info("---------------");
}
// Topological sort of all nodes
// static std::vector<entt::entity> sort_nodes(entt::registry & scene)
// {
// for(const auto&& [index, node]: utils::enumerate(scene.scene_nodes))
// std::vector<std::pair<entt::entity, entt::entity>> unsorted; // first: child, second: parent
// std::unordered_set<entt::entity> processed;
// std::vector<entt::entity> sorted;
//
// for(auto && [entity, node]: scene.view<components::node>().each())
// {
// if (node.parent_id != root)
// continue;
//
// // glm::mat4 M = model_matrices[index];
// // glm::vec4 pos = glm::column(M, 3);
// // spdlog::info("{:{}} {} pos={}, rot={}, pos to root={}", "", level * 2, node.name, node.translation, node.rotation, glm::vec3(pos));
//
// spdlog::info("{:{}} {}", "", level * 2, node.name);
//
// print_scene_hierarchy(scene, model_matrices, index, level + 1);
// if (scene.valid(node.parent))
// unsorted.push_back({entity, node.parent});
// else
// {
// processed.emplace(entity);
// sorted.push_back(entity);
// }
// }
//
// while(not unsorted.empty())
// {
// for(auto it = unsorted.begin(); it != unsorted.end(); )
// {
// if (processed.contains(it->second))
// {
// processed.emplace(it->first);
// sorted.push_back(it->first);
// it = unsorted.erase(it);
// }
// else
// ++it;
// }
// }
//
// return sorted;
// }
void scene_renderer::render(scene_data & scene, const std::array<float, 4> & clear_color, std::span<frame_info> frames)
void scene_renderer::render(
entt::registry & scene,
const std::array<float, 4> & clear_color,
uint32_t layer_mask,
vk::Extent2D output_size,
vk::Format color_format,
vk::Format depth_format,
vk::Image color_buffer,
vk::Image depth_buffer,
std::span<frame_info> frames)
{
per_frame_resources & resources = current_frame();
@@ -826,41 +855,48 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
vk::ClearDepthStencilValue{0.0, 0},
};
auto vertex_layout = scene_data::vertex::describe();
std::vector<glm::mat4> transform_to_root(scene.scene_nodes.size());
std::vector<bool> reverse_side(scene.scene_nodes.size());
std::vector<bool> visible(scene.scene_nodes.size());
for (const auto & [index, object]: utils::enumerate(scene.scene_nodes))
// TODO once per frame, even if render is called several times
for (auto && [entity, node]: scene.view<components::node>().each())
{
glm::mat4 transform_to_parent = glm::translate(glm::mat4(1), object.position) * (glm::mat4)object.orientation * glm::scale(glm::mat4(1), object.scale);
float det = object.scale.x * object.scale.y * object.scale.z;
glm::mat4 transform_to_root{1.0}; // Identity
bool visible = true;
bool reverse_side = false;
uint32_t layers = -1;
if (object.parent_id == scene_data::node::root_id)
for (auto i = &node; i != nullptr and visible; i = scene.try_get<components::node>(i->parent))
{
transform_to_root[index] = transform_to_parent;
reverse_side[index] = det < 0;
visible[index] = object.visible;
float det = i->scale.x * i->scale.y * i->scale.z;
glm::mat4 transform_to_parent = glm::translate(glm::mat4(1), i->position) * (glm::mat4)i->orientation * glm::scale(glm::mat4(1), i->scale);
transform_to_root = transform_to_parent * transform_to_root;
reverse_side = reverse_side ^ (det < 0);
visible = visible and i->visible;
layers = layers bitand i->layer_mask;
}
else
{
size_t parent = object.parent_id;
assert(parent < index);
transform_to_root[index] = transform_to_root.at(parent) * transform_to_parent;
reverse_side[index] = reverse_side[parent] ^ (det < 0);
visible[index] = visible[parent] && object.visible;
}
node.transform_to_root = transform_to_root;
node.global_visible = visible;
node.reverse_side = reverse_side;
node.global_layer_mask = layers;
}
// print_scene_hierarchy(scene, transform_to_root);
// print_scene_hierarchy(scene);
for (const auto && [frame_index, frame]: utils::enumerate(frames))
{
scene_renderer::output_image & output = get_output_image_data(frame.destination, frame.depth_buffer);
scene_renderer::output_image & output = get_output_image_data(output_image_info{
.renderpass = {
.color_format = color_format,
.depth_format = depth_format,
.keep_depth_buffer = depth_buffer != vk::Image{},
.msaa_samples = vk::SampleCountFlagBits::e1,
// .msaa_samples = vk::SampleCountFlagBits::e4, // FIXME: MSAA does not work
},
.output_size = output_size,
.color = color_buffer,
.depth = depth_buffer,
.base_array_layer = (uint32_t)frame_index,
});
glm::mat4 viewproj = frame.projection * frame.view;
vk::DeviceSize frame_ubo_offset = resources.uniform_buffer_offset;
@@ -873,13 +909,19 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
// frame_ubo.ambient_color = glm::vec4(0.2,0.2,0.2,0); // TODO
// frame_ubo.light_color = glm::vec4(0.8,0.8,0.8,0); // TODO
frame_ubo.ambient_color = glm::vec4(0, 0, 0, 0); // TODO
frame_ubo.light_color = glm::vec4(0.8, 0.8, 0.8, 0); // TODO
frame_ubo.ambient_color = glm::vec4(0.1, 0.1, 0.1, 0); // TODO
frame_ubo.light_color = glm::vec4(0.8, 0.8, 0.8, 0); // TODO
frame_ubo.light_position = glm::vec4(1, 1, 1, 0); // TODO
frame_ubo.proj = frame.projection;
frame_ubo.view = frame.view;
vk::raii::RenderPass & renderpass = get_renderpass(renderpass_info{
.color_format = color_format,
.depth_format = depth_format,
.keep_depth_buffer = depth_buffer != vk::Image{},
});
cb.beginRenderPass(
vk::RenderPassBeginInfo{
.renderPass = *renderpass,
@@ -893,17 +935,46 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
},
vk::SubpassContents::eInline);
for (const auto & [index, node]: utils::enumerate(scene.scene_nodes))
// Accumulate all visible primitives
std::vector<std::tuple<bool, float, components::node *, renderer::primitive *>> primitives; // TODO keep it between frames
for (auto && [entity, node]: scene.view<components::node>().each())
{
if (!node.mesh_id)
if (not node.global_visible or not node.mesh or (node.global_layer_mask & layer_mask) == 0)
continue;
if (!visible[index])
continue;
// Position relative to the camera
glm::vec4 position = frame.view * node.transform_to_root * glm::vec4(0, 0, 0, 1);
scene_data::mesh & mesh = scene.meshes.at(*node.mesh_id);
glm::mat4 & transform = transform_to_root[index];
for (renderer::primitive & primitive: node.mesh->primitives)
{
renderer::material & material = primitive.material_ ? *primitive.material_ : *default_material;
primitives.emplace_back(material.blend_enable, position.z, &node, &primitive);
}
}
// Sort by blending / distance
// TODO add frustum culling
std::ranges::stable_sort(primitives, [](const auto & a, const auto & b) -> bool {
// Put the opaque objects first
if (std::get<0>(a) < std::get<0>(b))
return true;
if (std::get<0>(a) > std::get<0>(b))
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 objeccts first
return std::get<0>(a) ^ (std::get<1>(a) > std::get<1>(b));
});
// TODO try to add a depth pre-pass
for (auto & [blend_enable, distance, node_ptr, primitive_ptr]: primitives)
{
components::node & node = *node_ptr;
renderer::primitive & primitive = *primitive_ptr;
glm::mat4 & transform = node.transform_to_root;
// TODO: reuse the UBO if another primitive of the same mesh has already been drawn
vk::DeviceSize instance_ubo_offset = resources.uniform_buffer_offset;
instance_gpu_data & object_ubo = *reinterpret_cast<instance_gpu_data *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(instance_gpu_data));
@@ -918,7 +989,8 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
for (auto && [idx, joint]: utils::enumerate(node.joints))
{
joint_matrices[idx] = glm::inverse(transform) * transform_to_root[joint.first] * joint.second;
glm::mat4 & joint_transform = scene.get<components::node>(joint.first).transform_to_root;
joint_matrices[idx] = glm::inverse(transform) * joint_transform * joint.second;
}
}
@@ -927,87 +999,102 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
object_ubo.modelviewproj = viewproj * transform;
object_ubo.clipping_planes = node.clipping_planes;
for (scene_data::primitive & primitive: mesh.primitives)
{
// Get the material
std::shared_ptr<scene_data::material> material = primitive.material_ ? primitive.material_ : default_material;
// Get the material
std::shared_ptr<renderer::material> material = primitive.material_ ? primitive.material_ : default_material;
if (material->ds_dirty || !material->ds)
update_material_descriptor_set(*material);
if (material->ds_dirty || !material->ds)
update_material_descriptor_set(*material);
// Get the pipeline
pipeline_info info{
.shader_name = material->shader_name,
.cull_mode = primitive.cull_mode,
.front_face = primitive.front_face,
.topology = primitive.topology,
.blend_enable = material->blend_enable,
// Get the pipeline
pipeline_info info{
.renderpass = {
.color_format = color_format,
.depth_format = depth_format,
.keep_depth_buffer = depth_buffer != vk::Image{}},
.shader_name = material->shader_name,
.cull_mode = primitive.cull_mode,
.front_face = primitive.front_face,
.topology = primitive.topology,
.blend_enable = material->blend_enable,
.nb_texcoords = 2, // TODO
.skinning = !node.joints.empty(),
};
.nb_texcoords = 2, // TODO
.skinning = !node.joints.empty(),
};
if (material->double_sided)
info.cull_mode = vk::CullModeFlagBits::eNone;
if (material->double_sided)
info.cull_mode = vk::CullModeFlagBits::eNone;
if (reverse_side[index])
info.front_face = reverse(info.front_face);
if (node.reverse_side)
info.front_face = reverse(info.front_face);
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
if (primitive.indexed)
cb.bindIndexBuffer(*mesh.buffer, primitive.index_offset, primitive.index_type);
cb.setViewport(0, vk::Viewport{
.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1,
});
cb.bindVertexBuffers(0, (vk::Buffer)*mesh.buffer, primitive.vertex_offset);
cb.setScissor(0, vk::Rect2D{
.offset = {0, 0},
.extent = output_size,
});
vk::DescriptorBufferInfo buffer_info_1{
.buffer = resources.uniform_buffer,
.offset = frame_ubo_offset,
.range = sizeof(frame_gpu_data)
if (primitive.indexed)
cb.bindIndexBuffer(*node.mesh->buffer, primitive.index_offset, primitive.index_type);
};
vk::DescriptorBufferInfo buffer_info_2{
.buffer = resources.uniform_buffer,
.offset = instance_ubo_offset,
.range = sizeof(instance_gpu_data)};
vk::DescriptorBufferInfo buffer_info_3{
.buffer = resources.uniform_buffer,
.offset = joints_ubo_offset,
.range = sizeof(glm::mat4) * 32};
cb.bindVertexBuffers(0, (vk::Buffer)*node.mesh->buffer, primitive.vertex_offset);
std::array descriptors{
vk::WriteDescriptorSet{
.dstBinding = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_1,
},
vk::WriteDescriptorSet{
.dstBinding = 1,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_2,
},
vk::WriteDescriptorSet{
.dstBinding = 2,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_3,
},
};
vk::DescriptorBufferInfo buffer_info_1{
.buffer = resources.uniform_buffer,
.offset = frame_ubo_offset,
.range = sizeof(frame_gpu_data)
cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors);
};
vk::DescriptorBufferInfo buffer_info_2{
.buffer = resources.uniform_buffer,
.offset = instance_ubo_offset,
.range = sizeof(instance_gpu_data)};
vk::DescriptorBufferInfo buffer_info_3{
.buffer = resources.uniform_buffer,
.offset = joints_ubo_offset,
.range = sizeof(glm::mat4) * 32};
// Set 1: material
cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 1, **material->ds, {});
std::array descriptors{
vk::WriteDescriptorSet{
.dstBinding = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_1,
},
vk::WriteDescriptorSet{
.dstBinding = 1,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_2,
},
vk::WriteDescriptorSet{
.dstBinding = 2,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_3,
},
};
if (primitive.indexed)
cb.drawIndexed(primitive.index_count, 1, 0, 0, 0);
else
cb.draw(primitive.vertex_count, 1, 0, 0);
cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors);
resources.resources.push_back(material->ds);
}
// Set 1: material
cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 1, **material->ds, {});
if (primitive.indexed)
cb.drawIndexed(primitive.index_count, 1, 0, 0, 0);
else
cb.draw(primitive.vertex_count, 1, 0, 0);
resources.resources.push_back(material->ds);
}
cb.endRenderPass();
}
+66 -34
View File
@@ -24,7 +24,6 @@
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <map>
#include <span>
#include <unordered_map>
#include <vector>
@@ -34,10 +33,23 @@
#include "vk/allocation.h"
#include "render/growable_descriptor_pool.h"
#include "render/scene_data.h"
#include "render/scene_components.h"
#include "utils/thread_safe.h"
struct renderpass_info
{
vk::Format color_format;
vk::Format depth_format;
bool keep_depth_buffer;
vk::SampleCountFlagBits msaa_samples = vk::SampleCountFlagBits::e1;
bool operator==(const renderpass_info & other) const noexcept = default;
};
struct pipeline_info
{
renderpass_info renderpass;
std::string shader_name;
vk::CullModeFlags cull_mode = vk::CullModeFlagBits::eNone;
@@ -56,11 +68,35 @@ struct pipeline_info
bool operator==(const pipeline_info & other) const noexcept = default;
};
struct output_image_info
{
renderpass_info renderpass;
vk::Extent2D output_size;
VkImage color;
VkImage depth;
uint32_t base_array_layer;
bool operator==(const output_image_info & other) const noexcept = default;
};
namespace std
{
template <>
struct hash<renderpass_info> : utils::magic_hash<renderpass_info>
{};
template <>
struct hash<pipeline_info> : utils::magic_hash<pipeline_info>
{};
template <>
struct hash<vk::Extent2D> : utils::magic_hash<vk::Extent2D>
{};
template <>
struct hash<output_image_info> : utils::magic_hash<output_image_info>
{};
} // namespace std
class scene_renderer
@@ -68,12 +104,7 @@ class scene_renderer
vk::raii::PhysicalDevice physical_device;
vk::raii::Device & device;
vk::PhysicalDeviceProperties physical_device_properties;
vk::raii::Queue & queue;
// Scene format
const vk::Extent2D output_size;
const vk::Format output_format;
const vk::Format depth_format;
thread_safe<vk::raii::Queue> & queue;
// Destination images
struct output_image
@@ -84,26 +115,28 @@ class scene_renderer
image_allocation depth_buffer;
vk::raii::ImageView depth_view = nullptr;
// image_allocation multisample_image;
// vk::raii::ImageView multisample_view = nullptr;
image_allocation multisample_image;
vk::raii::ImageView multisample_view = nullptr;
};
// Initialization functions
output_image create_output_image_data(vk::Image output_color, vk::Image output_depth);
vk::raii::RenderPass create_renderpass();
output_image create_output_image_data(const output_image_info & info);
vk::raii::RenderPass create_renderpass(const renderpass_info & info);
vk::raii::PipelineLayout create_pipeline_layout(std::span<vk::DescriptorSetLayout> layouts);
vk::raii::Pipeline create_pipeline(const pipeline_info & info);
std::shared_ptr<scene_data::texture> create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel);
std::shared_ptr<scene_data::material> create_default_material(vk::raii::CommandPool & cb_pool);
std::shared_ptr<renderer::texture> create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel);
std::shared_ptr<renderer::material> create_default_material(vk::raii::CommandPool & cb_pool);
vk::raii::DescriptorSetLayout create_descriptor_set_layout(std::span<vk::DescriptorSetLayoutBinding> bindings, vk::DescriptorSetLayoutCreateFlags flags = {});
// Caches
std::/*unordered_*/ map<std::pair<VkImage, VkImage>, output_image> output_images; // TODO: use an unordered_map, create a hash for std::pair
std::unordered_map<renderpass_info, vk::raii::RenderPass> renderpasses;
std::unordered_map<output_image_info, output_image> output_images;
std::unordered_map<pipeline_info, vk::raii::Pipeline> pipelines;
output_image & get_output_image_data(vk::Image output_color, vk::Image output_depth);
output_image & get_output_image_data(const output_image_info & info);
vk::raii::Pipeline & get_pipeline(const pipeline_info & info);
vk::raii::RenderPass & get_renderpass(const renderpass_info & info);
vk::raii::DescriptorSetLayout layout_0; // Descriptor set 0: per-frame/view data (UBO) and per-instance data (UBO + SSBO)
vk::raii::DescriptorSetLayout layout_1; // Descriptor set 1: per-material data (5 combined image samplers and 1 uniform buffer)
@@ -114,11 +147,8 @@ class scene_renderer
vk::raii::PipelineLayout pipeline_layout = nullptr;
// Texture samplers
std::unordered_map<sampler_info, std::shared_ptr<vk::raii::Sampler>> samplers;
vk::Sampler get_sampler(const sampler_info & info);
// Render pass
vk::raii::RenderPass renderpass = nullptr;
std::unordered_map<renderer::sampler_info, std::shared_ptr<vk::raii::Sampler>> samplers;
vk::Sampler get_sampler(const renderer::sampler_info & info);
// Default material and textures
// This material has 1x1 textures with the following values:
@@ -134,7 +164,7 @@ class scene_renderer
// roughness_factor 1.0
// occlusion_strength 0.0
// normal_scale 0.0
std::shared_ptr<scene_data::material> default_material;
std::shared_ptr<renderer::material> default_material;
struct frame_gpu_data
{
@@ -170,11 +200,10 @@ class scene_renderer
int current_frame_index;
vk::raii::QueryPool query_pool = nullptr;
double gpu_time_s = 0;
bool keep_depth_buffer = false;
per_frame_resources & current_frame();
void update_material_descriptor_set(scene_data::material & material);
void update_material_descriptor_set(renderer::material & material);
public:
static vk::Format find_usable_image_format(
@@ -189,26 +218,29 @@ public:
scene_renderer(
vk::raii::Device & device,
vk::raii::PhysicalDevice physical_device,
vk::raii::Queue & queue,
thread_safe<vk::raii::Queue> & queue,
vk::raii::CommandPool & cb_pool,
vk::Extent2D output_size,
vk::Format output_format,
vk::Format depth_format,
int frames_in_flight = 2,
bool keep_depth_buffer = false);
int frames_in_flight = 2);
~scene_renderer();
struct frame_info
{
vk::Image destination;
vk::Image depth_buffer;
glm::mat4 projection;
glm::mat4 view;
};
void start_frame();
void render(scene_data & scene, const std::array<float, 4> & clear_color, std::span<frame_info> info);
void render(
entt::registry & scene,
const std::array<float, 4> & clear_color,
uint32_t layer_mask,
vk::Extent2D output_size,
vk::Format output_format,
vk::Format depth_format,
vk::Image color_buffer,
vk::Image depth_buffer,
std::span<frame_info> info);
void end_frame();
double get_gpu_time() const
@@ -216,7 +248,7 @@ public:
return gpu_time_s;
}
std::shared_ptr<scene_data::material> get_default_material()
std::shared_ptr<renderer::material> get_default_material()
{
return default_material;
}
+32 -36
View File
@@ -139,46 +139,42 @@ text_rasterizer::text_rasterizer(vk::raii::Device & device, vk::raii::PhysicalDe
image_allocation text_rasterizer::create_image(vk::Extent2D size)
{
image_allocation alloc{device,
vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = text::format,
.extent = {
.width = size.width,
.height = size.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst,
.sharingMode = vk::SharingMode::eExclusive,
.initialLayout = vk::ImageLayout::eUndefined,
},
VmaAllocationCreateInfo{
.flags = 0,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
application::set_debug_reports_name<vk::Image>(alloc, "text_rasterizer image");
return alloc;
return {device,
vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = text::format,
.extent = {
.width = size.width,
.height = size.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst,
.sharingMode = vk::SharingMode::eExclusive,
.initialLayout = vk::ImageLayout::eUndefined,
},
VmaAllocationCreateInfo{
.flags = 0,
.usage = VMA_MEMORY_USAGE_AUTO,
},
"text_rasterizer image"};
}
buffer_allocation text_rasterizer::create_buffer(size_t size)
{
buffer_allocation alloc{device,
vk::BufferCreateInfo{
.size = size,
.usage = vk::BufferUsageFlagBits::eTransferSrc,
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
application::set_debug_reports_name<vk::Buffer>(alloc, "text_rasterizer buffer");
return alloc;
return {device,
vk::BufferCreateInfo{
.size = size,
.usage = vk::BufferUsageFlagBits::eTransferSrc,
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
},
"text_rasterizer buffer"};
}
text_rasterizer::~text_rasterizer()
+397 -2
View File
@@ -19,14 +19,25 @@
#include "scene.h"
#include "application.h"
#include "render/scene_loader.h"
#include "utils/contains.h"
#include "utils/i18n.h"
#include "utils/overloaded.h"
#include "utils/ranges.h"
#include <magic_enum.hpp>
#include <spdlog/spdlog.h>
#include <vulkan/vulkan_raii.hpp>
#include <vulkan/vulkan_structs.hpp>
#include <openxr/openxr.h>
// TODO remove constants
#include "constants.h"
std::vector<scene::meta *> scene::scene_registry;
scene::~scene() {}
scene::scene(key, const meta & current_meta) :
scene::scene(key, const meta & current_meta, std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats) :
instance(application::instance().xr_instance),
system(application::instance().xr_system_id),
session(application::instance().xr_session),
@@ -36,11 +47,48 @@ scene::scene(key, const meta & current_meta) :
device(application::instance().vk_device),
physical_device(application::instance().vk_physical_device),
queue(application::instance().vk_queue),
commandpool(application::instance().vk_cmdpool),
queue_family_index(application::instance().vk_queue_family_index),
commandpool(application::instance().vk_cmdpool),
current_meta(current_meta)
{
swapchain_format = vk::Format::eUndefined;
spdlog::info("Supported swapchain formats:");
for (auto format: session.get_swapchain_formats())
{
spdlog::info(" {}", vk::to_string(format));
}
for (auto format: session.get_swapchain_formats())
{
if (utils::contains(supported_color_formats, format))
{
swapchain_format = format;
break;
}
}
if (swapchain_format == vk::Format::eUndefined)
throw std::runtime_error(_("No supported swapchain format"));
auto views = system.view_configuration_views(viewconfig);
depth_format = scene_renderer::find_usable_image_format(
physical_device,
supported_depth_formats,
{
views[0].recommendedImageRectWidth,
views[0].recommendedImageRectHeight,
1,
},
vk::ImageUsageFlagBits::eDepthStencilAttachment);
composition_layer_depth_test_supported =
instance.has_extension(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME) and
instance.has_extension(XR_FB_COMPOSITION_LAYER_DEPTH_TEST_EXTENSION_NAME);
composition_layer_color_scale_bias_supported = instance.has_extension(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME);
}
void scene::set_focused(bool status)
{
if (status != focused)
@@ -53,6 +101,353 @@ void scene::set_focused(bool status)
}
}
glm::mat4 scene::projection_matrix(XrFovf fov, float zn)
{
float r = tan(fov.angleRight);
float l = tan(fov.angleLeft);
float t = tan(fov.angleUp);
float b = tan(fov.angleDown);
// reversed Z projection, infinite far plane
// clang-format off
return glm::mat4{
{ 2/(r-l), 0, 0, 0 },
{ 0, 2/(b-t), 0, 0 },
{ (l+r)/(r-l), (t+b)/(b-t), 0, -1 },
{ 0, 0, zn, 0 }
};
// clang-format on
}
glm::mat4 scene::view_matrix(XrPosef pose)
{
XrQuaternionf q = pose.orientation;
XrVector3f pos = pose.position;
glm::mat4 inv_view_matrix = glm::mat4_cast(glm::quat(q.w, q.x, q.y, q.z));
inv_view_matrix = glm::translate(glm::mat4(1), glm::vec3(pos.x, pos.y, pos.z)) * inv_view_matrix;
return glm::inverse(inv_view_matrix);
}
void scene::render_world(
XrCompositionLayerFlags flags,
XrSpace space,
std::span<XrView> views,
uint32_t width,
uint32_t height,
bool keep_depth_buffer,
uint32_t layer_mask,
XrColor4f clear_color)
{
std::vector<scene_renderer::frame_info> frames;
frames.reserve(views.size());
// TODO inplace vector
std::vector<XrCompositionLayerProjectionView> composition_layer_color;
std::vector<XrCompositionLayerDepthInfoKHR> composition_layer_depth;
composition_layer_color.reserve(views.size());
if (keep_depth_buffer)
composition_layer_depth.reserve(views.size());
auto [color_swapchain, color_image] = [&]() -> std::pair<XrSwapchain, vk::Image> {
xr::swapchain & color_swapchain = get_swapchain(swapchain_format, width, height, 1, views.size());
int color_image_index = color_swapchain.acquire();
vk::Image color_image = color_swapchain.images()[color_image_index].image;
color_swapchain.wait();
return {color_swapchain, color_image};
}();
auto [depth_swapchain, depth_image] = [&]() -> std::pair<XrSwapchain, vk::Image> {
if (keep_depth_buffer)
{
xr::swapchain & depth_swapchain = get_swapchain(depth_format, width, height, 1, views.size());
int depth_image_index = depth_swapchain.acquire();
vk::Image depth_image = depth_swapchain.images()[depth_image_index].image;
depth_swapchain.wait();
return {depth_swapchain, depth_image};
}
else
return {};
}();
for (auto && [index, view]: utils::enumerate(views))
{
frames.push_back({
.projection = projection_matrix(view.fov, constants::lobby::near_plane),
.view = view_matrix(view.pose),
});
composition_layer_color.push_back({
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW,
.pose = view.pose,
.fov = view.fov,
.subImage = {
.swapchain = color_swapchain,
.imageRect = {
.offset = {0, 0},
.extent = {(int)width, (int)height},
},
.imageArrayIndex = (uint32_t)index,
},
});
if (keep_depth_buffer)
{
composition_layer_depth.push_back({
.type = XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR,
.subImage = {
.swapchain = depth_swapchain,
.imageRect = {
.offset = {0, 0},
.extent = {(int)width, (int)height},
},
.imageArrayIndex = (uint32_t)index,
},
.minDepth = 0,
.maxDepth = 1,
.nearZ = std::numeric_limits<float>::infinity(),
.farZ = constants::lobby::near_plane,
});
}
}
// TODO: compute transforms only once
renderer->render(
world,
{clear_color.r, clear_color.g, clear_color.b, clear_color.a},
layer_mask,
vk::Extent2D{width, height},
swapchain_format,
depth_format,
color_image,
depth_image,
frames);
add_projection_layer(
XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT,
space,
std::move(composition_layer_color),
std::move(composition_layer_depth));
}
xr::swapchain & scene::get_swapchain(vk::Format format, int32_t width, int32_t height, int sample_count, uint32_t array_size)
{
for (swapchain_entry & entry: swapchains)
{
if (not entry.used and
entry.format == format and
entry.width == width and
entry.height == height and
entry.sample_count == sample_count and
entry.array_size == array_size)
{
entry.used = true;
return entry.swapchain;
}
}
spdlog::info("Creating new swapchain: {}, {}x{}, {} sample(s), {} level(s)", magic_enum::enum_name(format), width, height, sample_count, array_size);
return swapchains.emplace_back(swapchain_entry{
.format = format,
.width = width,
.height = height,
.sample_count = sample_count,
.array_size = array_size,
.used = true,
.swapchain = xr::swapchain(session, device, format, width, height, sample_count, array_size),
})
.swapchain;
}
void scene::clear_swapchains()
{
swapchains.clear();
}
void scene::render_start(bool passthrough, XrTime predicted_display_time_)
{
blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
predicted_display_time = predicted_display_time_;
layers.clear();
openxr_layers.clear();
for (swapchain_entry & swapchain: swapchains)
swapchain.used = false;
if (renderer)
renderer->start_frame();
if (passthrough)
{
std::visit(
utils::overloaded{
[&](std::monostate &) {
assert(false);
},
[&](xr::passthrough_alpha_blend & p) {
blend_mode = XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND;
},
[&](auto & p) {
layers.push_back(layer{
.composition_layer = p.layer(),
});
}},
session.get_passthrough());
}
}
void scene::add_projection_layer(
XrCompositionLayerFlags flags,
XrSpace space,
std::vector<XrCompositionLayerProjectionView> && color_views,
std::vector<XrCompositionLayerDepthInfoKHR> && depth_views)
{
layers.push_back(layer{
.composition_layer = XrCompositionLayerProjection{
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION,
.next = nullptr,
.layerFlags = flags,
.space = space,
.viewCount = (uint32_t)color_views.size(),
.views = nullptr,
},
.color_views = std::move(color_views),
.depth_views = std::move(depth_views),
});
}
void scene::add_quad_layer(
XrCompositionLayerFlags flags,
XrSpace space,
XrEyeVisibility eyeVisibility,
XrSwapchainSubImage subImage,
XrPosef pose,
XrExtent2Df size)
{
layers.push_back(layer{
.composition_layer = XrCompositionLayerQuad{
.type = XR_TYPE_COMPOSITION_LAYER_QUAD,
.next = nullptr,
.layerFlags = flags,
.space = space,
.eyeVisibility = eyeVisibility,
.subImage = subImage,
.pose = pose,
.size = size,
},
});
}
void scene::set_color_scale_bias(XrColor4f scale, XrColor4f bias)
{
assert(not layers.empty());
layers.back().color_scale_bias = XrCompositionLayerColorScaleBiasKHR{
.type = XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR,
.colorScale = scale,
.colorBias = bias,
};
}
void scene::set_depth_test(bool write, XrCompareOpFB op)
{
assert(not layers.empty());
layers.back().depth_test = XrCompositionLayerDepthTestFB{
.type = XR_TYPE_COMPOSITION_LAYER_DEPTH_TEST_FB,
.depthMask = write,
.compareOp = op,
};
}
void scene::set_layer_settings(XrCompositionLayerSettingsFlagsFB flags)
{
assert(not layers.empty());
layers.back().settings = XrCompositionLayerSettingsFB{
.type = XR_TYPE_COMPOSITION_LAYER_SETTINGS_FB,
.layerFlags = flags,
};
}
void scene::render_end()
{
// Fixup all pointers
for (auto & i: layers)
{
XrCompositionLayerBaseHeader * base = std::visit(
utils::overloaded{
[&](XrCompositionLayerProjection & layer) {
layer.views = i.color_views.data();
for (auto [color, depth]: std::views::zip(i.color_views, i.depth_views))
color.next = &depth;
return reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer);
},
[&](XrCompositionLayerQuad & layer) {
return reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer);
},
[&](XrCompositionLayerBaseHeader * layer) {
return layer;
},
},
i.composition_layer);
if (i.color_scale_bias)
{
i.color_scale_bias->next = base->next;
base->next = &*i.color_scale_bias;
}
if (i.depth_test)
{
i.depth_test->next = base->next;
base->next = &*i.depth_test;
}
if (i.settings)
{
i.settings->type = XR_TYPE_COMPOSITION_LAYER_SETTINGS_FB;
i.settings->next = base->next;
base->next = &*i.settings;
}
openxr_layers.push_back(base);
}
if (renderer)
renderer->end_frame();
// Release all swapchains after the renderer has submitted the command buffers
for (auto & swapchain: swapchains)
{
if (swapchain.used)
swapchain.swapchain.release();
}
session.end_frame(predicted_display_time, openxr_layers, blend_mode);
}
std::pair<entt::entity, components::node &> scene::load_gltf(const std::filesystem::path & path, uint32_t layer_mask)
{
auto entity = world.create();
auto & node = world.emplace<components::node>(entity);
node.layer_mask = layer_mask;
assert(renderer);
scene_loader loader(device, physical_device, queue, queue_family_index, renderer->get_default_material());
loader.add_prefab(world, loader(path), entity);
return {entity, node};
}
void scene::on_unfocused() {}
void scene::on_focused() {}
void scene::on_xr_event(const xr::event &) {}
+106 -6
View File
@@ -19,16 +19,25 @@
#pragma once
#include "render/scene_loader.h"
#include "xr/actionset.h"
#include "xr/instance.h"
#include "xr/session.h"
#include "xr/swapchain.h"
#include "xr/system.h"
#include <cstdint>
#include <filesystem>
#include <span>
#include <string>
#include <unordered_map>
#include <vector>
#include "render/imgui_impl.h"
#include "render/scene_renderer.h"
#include <entt/entity/registry.hpp>
#include <openxr/openxr.h>
// See http://www.nirfriedman.com/2018/04/29/unforgettable-factory/
// for automatic registration of scenes
@@ -43,7 +52,7 @@ public:
struct suggested_binding
{
std::string profile_name;
std::vector<std::string> profile_names;
std::vector<action_binding> paths;
};
@@ -77,15 +86,29 @@ protected:
XrViewConfigurationType viewconfig;
bool focused = false;
public:
vk::raii::Instance & vk_instance;
vk::raii::Device & device;
vk::raii::PhysicalDevice & physical_device;
vk::raii::Queue & queue;
vk::raii::CommandPool & commandpool;
thread_safe<vk::raii::Queue> & queue;
uint32_t queue_family_index;
protected:
vk::raii::CommandPool & commandpool;
const meta & current_meta;
std::optional<scene_renderer> renderer;
public:
std::optional<scene_loader> loader;
protected:
vk::Format swapchain_format;
vk::Format depth_format;
bool composition_layer_depth_test_supported;
bool composition_layer_color_scale_bias_supported;
std::pair<XrAction, XrActionType> get_action(const std::string & name)
{
return current_meta.actions_by_name.at(name);
@@ -96,17 +119,94 @@ protected:
return current_meta.spaces_by_name.at(name);
}
// Helper functions
static glm::mat4 projection_matrix(XrFovf fov, float zn = 0.02);
static glm::mat4 view_matrix(XrPosef pose);
// Layer rendering
XrEnvironmentBlendMode blend_mode;
XrTime predicted_display_time;
struct layer
{
std::variant<XrCompositionLayerProjection, XrCompositionLayerQuad, XrCompositionLayerBaseHeader *> composition_layer;
// TODO in place vectors
std::vector<XrCompositionLayerProjectionView> color_views; // Used by XrCompositionLayerProjection
std::vector<XrCompositionLayerDepthInfoKHR> depth_views; // Used by XrCompositionLayerProjection
std::optional<XrCompositionLayerColorScaleBiasKHR> color_scale_bias;
std::optional<XrCompositionLayerDepthTestFB> depth_test;
std::optional<XrCompositionLayerSettingsFB> settings;
};
std::vector<layer> layers;
std::vector<XrCompositionLayerBaseHeader *> openxr_layers;
struct swapchain_entry
{
vk::Format format;
int32_t width;
int32_t height;
int sample_count;
uint32_t array_size;
bool used;
xr::swapchain swapchain;
};
std::vector<swapchain_entry> swapchains;
// The returned reference is valid until the next call to get_swapchain
xr::swapchain & get_swapchain(vk::Format format, int32_t width, int32_t height, int sample_count, uint32_t array_size);
void clear_swapchains();
void render_start(bool passthrough, XrTime predicted_display_time);
void add_projection_layer(
XrCompositionLayerFlags flags,
XrSpace space,
std::vector<XrCompositionLayerProjectionView> && color_views,
std::vector<XrCompositionLayerDepthInfoKHR> && depth_views = {});
void add_quad_layer(
XrCompositionLayerFlags flags,
XrSpace space,
XrEyeVisibility eyeVisibility,
XrSwapchainSubImage subImage,
XrPosef pose,
XrExtent2Df size);
void render_world(
XrCompositionLayerFlags flags,
XrSpace space,
std::span<XrView> views,
uint32_t width,
uint32_t height,
bool keep_depth_buffer,
uint32_t layer_mask,
XrColor4f clear_color);
void set_color_scale_bias(XrColor4f scale, XrColor4f bias);
void set_depth_test(bool write, XrCompareOpFB op);
void set_layer_settings(XrCompositionLayerSettingsFlagsFB flags);
void render_end();
virtual void on_unfocused();
virtual void on_focused();
public:
scene(key, const meta &);
scene(key, const meta &, std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats);
virtual ~scene();
void set_focused(bool status);
virtual void render(const XrFrameState &) = 0;
virtual void on_xr_event(const xr::event &);
entt::registry world;
std::pair<entt::entity, components::node &> load_gltf(const std::filesystem::path & path, uint32_t layer_mask = -1);
void remove(entt::entity entity); // TODO
};
template <typename T>
@@ -124,8 +224,8 @@ class scene_impl : public scene
static inline bool registered = scene_impl<T>::register_scene();
scene_impl() :
scene(key{}, T::get_meta_scene())
scene_impl(std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats = {}) :
scene(key{}, T::get_meta_scene(), supported_color_formats, supported_depth_formats)
{
(void)registered;
}
+284
View File
@@ -0,0 +1,284 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2025 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/>.
*/
#define IMGUI_DEFINE_MATH_OPERATORS
#include "app_launcher.h"
#include "constants.h"
#include "imgui.h"
#include "imgui_internal.h"
#include "scenes/stream.h"
#include "utils/i18n.h"
#include "utils/ranges.h"
#include <imspinner.h>
#include <spdlog/fmt/fmt.h>
#include <uni_algo/case.h>
using namespace std::chrono_literals;
// 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))
{
// Based on ImGui::ButtonEx and ImGui::ImageButtonEx
ImGuiWindow * window = ImGui::GetCurrentWindow();
const ImGuiStyle & style = ImGui::GetStyle();
if (window->SkipItems)
return false;
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);
ImGuiID id = window->GetID(text.c_str());
if (!ImGui::ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held, flags);
// 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);
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;
}
app_launcher::app_launcher(
scenes::stream & stream,
std::string server_name) :
server_name(std::move(server_name)),
stream(stream),
textures(
stream.physical_device,
stream.device,
stream.queue_family_index,
stream.queue)
{
try
{
default_icon = textures.load_texture("default_icon.ktx2");
}
catch (...)
{
default_icon = textures.load_texture("default_icon.png");
}
}
app_launcher::~app_launcher()
{
stream.device.waitIdle();
for (const auto & [app_id, app_icon]: app_icons)
textures.free_texture(app_icon);
textures.free_texture(default_icon);
}
app_launcher::clicked app_launcher::draw_gui(imgui_context & imgui_ctx, const std::string & cancel)
{
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 and
stream.current_state() != scenes::stream::state::streaming;
auto cancel_size = ImGui::CalcTextSize(cancel.c_str());
auto apps = applications.lock();
ImGui::PushFont(nullptr, constants::gui::font_size_large);
if (server_name.empty())
CenterTextH(_("Connected to WiVRn server"));
else
CenterTextH(fmt::format(_F("Connected to {}"), server_name));
ImGui::PopFont();
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {20, 20});
if (apps->empty())
{
CenterTextHV(_("Start an application on the server to start streaming."));
}
else
{
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);
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))
{
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}))
{
res = clicked::Start;
start_time = t0;
stream.start_application(app.id);
}
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::EndDisabled();
if (app_starting)
{
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::PopStyleVar(); // ImGuiStyleVar_WindowPadding
}
ImGui::PopStyleVar();
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;
}
void app_launcher::operator()(to_headset::application_list && apps)
{
std::ranges::sort(apps.applications, [](auto & l, auto & r) {
return una::casesens::collate_utf8(l.name, r.name) < 0;
});
auto locked = applications.lock();
locked->clear();
locked->reserve(apps.applications.size());
for (const auto & i: apps.applications)
{
locked->push_back(app{
.id = std::move(i.id),
.name = std::move(i.name),
});
}
}
void app_launcher::operator()(to_headset::application_icon && icon)
{
auto locked = applications.lock();
if (auto it = std::ranges::find(*locked, icon.id, &app::id); it != locked->end())
it->image = std::move(icon.image);
}
+65
View File
@@ -0,0 +1,65 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2025 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 "render/imgui_impl.h"
#include "wivrn_packets.h"
#include <chrono>
#include <unordered_map>
namespace scenes
{
class stream;
}
class app_launcher
{
struct app
{
std::string id;
std::string name;
std::vector<std::byte> image;
};
std::chrono::steady_clock::time_point start_time{};
std::string server_name;
scenes::stream & stream;
imgui_textures textures;
ImTextureID default_icon;
std::unordered_map<std::string, ImTextureID> app_icons;
// Last application list received from server
thread_safe<std::vector<app>> applications;
public:
app_launcher(scenes::stream &, std::string server_name);
~app_launcher();
enum clicked
{
None,
Cancel,
Start,
};
// cancel: text to display on the quit/disconnect/cancel button
clicked draw_gui(imgui_context &, const std::string & cancel);
void operator()(wivrn::to_headset::application_list && apps);
void operator()(wivrn::to_headset::application_icon && icon);
};
+364
View File
@@ -0,0 +1,364 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "blitter.h"
#include "application.h"
#include "utils/ranges.h"
#include "vk/pipeline.h"
#include "vk/shader.h"
#include "vk/specialization_constants.h"
#include <format>
#include <ranges>
#include <spdlog/spdlog.h>
namespace wivrn
{
static const uint32_t num_views = 2;
blitter::blitter(vk::raii::Device & device, size_t view) :
device(device), view(view)
{
}
void blitter::reset(const to_headset::video_stream_description & desc)
{
using channels_t = to_headset::video_stream_description::channels_t;
this->desc = desc;
current = {};
target = image_allocation();
image_view = nullptr;
rp = nullptr;
fb = nullptr;
sampler = nullptr;
pipelines.clear();
passthrough_rgb = passthrough_a = -1;
auto w = desc.width / num_views;
for (auto [i, item]: utils::enumerate(desc.items))
{
if (item.offset_x <= view * w and
item.offset_y == 0 and
item.offset_x + item.width * item.subsampling >= (view + 1) * w and
item.height * item.subsampling >= desc.height)
{
spdlog::info("Stream {} is eligible for blit-less path on view {}", i, view);
switch (item.channels)
{
case channels_t::colour:
passthrough_rgb = i;
break;
case channels_t::alpha:
passthrough_a = i;
break;
}
const bool alpha = item.channels == to_headset::video_stream_description::channels_t::alpha;
auto & r = alpha ? current.rect_a : current.rect_rgb;
r = vk::Rect2D{
.offset = {
.x = int32_t(view * w) - item.offset_x,
.y = 0,
},
};
}
}
if (passthrough_rgb != -1 and passthrough_a != -1)
return;
target = image_allocation(
device,
vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = vk::Format::eB8G8R8A8Srgb,
.extent = {
.width = w,
.height = desc.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment,
},
{
.usage = VMA_MEMORY_USAGE_AUTO,
},
std::format("blit image {}", view));
image_view = device.createImageView(vk::ImageViewCreateInfo{
.image = vk::Image(target),
.viewType = vk::ImageViewType::e2D,
.format = target.info().format,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.levelCount = 1,
.layerCount = 1,
}});
// render pass
{
vk::AttachmentReference color_ref{
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::SubpassDescription subpass{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
.colorAttachmentCount = 1,
.pColorAttachments = &color_ref,
};
vk::AttachmentDescription color_desc{
.format = target.info().format,
.loadOp = vk::AttachmentLoadOp::eDontCare,
.finalLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
};
rp = device.createRenderPass(vk::RenderPassCreateInfo{
.attachmentCount = 1,
.pAttachments = &color_desc,
.subpassCount = 1,
.pSubpasses = &subpass,
});
}
fb = device.createFramebuffer(
vk::FramebufferCreateInfo{
.renderPass = *rp,
.attachmentCount = 1,
.pAttachments = &*image_view,
.width = w,
.height = desc.height,
.layers = 1,
});
sampler = device.createSampler(vk::SamplerCreateInfo{
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.addressModeU = vk::SamplerAddressMode::eClampToBorder,
.addressModeV = vk::SamplerAddressMode::eClampToBorder,
.addressModeW = vk::SamplerAddressMode::eClampToBorder,
.borderColor = vk::BorderColor::eFloatOpaqueBlack,
});
pipelines.resize(desc.items.size());
for (auto [i, item]: utils::enumerate(desc.items))
{
pipelines[i].used = item.offset_x < (view + 1) * w and
item.offset_x + item.width * item.subsampling > view * w;
}
current.rgb = *image_view;
current.sampler_rgb = *sampler;
current.rect_rgb = vk::Rect2D{.extent = {w, desc.height}};
current.layout_rgb = vk::ImageLayout::eShaderReadOnlyOptimal;
}
void blitter::begin(vk::raii::CommandBuffer & cmd)
{
assert(not desc.items.empty());
if (*fb == VK_NULL_HANDLE)
{
current.rgb = nullptr;
current.a = nullptr;
current.sampler_rgb = nullptr;
current.sampler_a = nullptr;
return;
}
current.rgb = *image_view;
current.sampler_rgb = *sampler;
cmd.beginRenderPass(
{
.renderPass = *rp,
.framebuffer = *fb,
.renderArea = {
.offset = {0, 0},
.extent = {target.info().extent.width, target.info().extent.height},
},
},
vk::SubpassContents::eInline);
}
void blitter::push_image(vk::raii::CommandBuffer & cmd, uint8_t stream, vk::Sampler sampler, const vk::Extent2D & extent_, vk::ImageView image, vk::ImageLayout layout)
{
if (stream == passthrough_rgb)
{
current.rgb = image;
current.sampler_rgb = sampler;
current.layout_rgb = layout;
current.rect_rgb.extent = vk::Extent2D{
extent_.width * desc.items[stream].subsampling,
extent_.height * desc.items[stream].subsampling,
};
return;
}
if (stream == passthrough_a)
{
current.a = image;
current.sampler_a = sampler;
current.layout_a = layout;
current.rect_a.extent = vk::Extent2D{
extent_.width * desc.items[stream].subsampling,
extent_.height * desc.items[stream].subsampling,
};
return;
}
if (pipelines.empty())
return;
assert(stream < pipelines.size());
auto & p = pipelines[stream];
if (not p.used)
return;
const auto & extent = target.info().extent;
const auto & description = desc.items[stream];
if (not *p.pipeline)
{
const bool alpha = description.channels == to_headset::video_stream_description::channels_t::alpha;
vk::DescriptorSetLayoutBinding sampler_layout_binding{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
.pImmutableSamplers = &sampler,
};
p.set_layout = device.createDescriptorSetLayout(vk::DescriptorSetLayoutCreateInfo{
.flags = vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR,
.bindingCount = 1,
.pBindings = &sampler_layout_binding,
});
auto vert_constants = make_specialization_constants(
float(description.width) / extent_.width,
float(description.height) / extent_.height);
auto frag_constants = make_specialization_constants(
VkBool32(alpha));
// Create graphics pipeline
vk::raii::ShaderModule vertex_shader = load_shader(device, "stream.vert");
vk::raii::ShaderModule fragment_shader = load_shader(device, "stream.frag");
p.layout = device.createPipelineLayout(vk::PipelineLayoutCreateInfo{
.setLayoutCount = 1,
.pSetLayouts = &*p.set_layout,
});
vk::pipeline_builder pipeline_info{
.Stages = {{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.pName = "main",
.pSpecializationInfo = vert_constants,
},
{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.pName = "main",
.pSpecializationInfo = frag_constants,
}},
.VertexBindingDescriptions = {},
.VertexAttributeDescriptions = {},
.InputAssemblyState = {{
.topology = vk::PrimitiveTopology::eTriangleStrip,
}},
// With vk::DynamicState::eViewport, vk::DynamicState::eScissor the number of viewports
// and scissors is still used, put a vector with one element
.Viewports = {{}},
.Scissors = {{}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
}},
.MultisampleState = {{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
}},
.ColorBlendAttachments = {
{.colorWriteMask = alpha ? vk::ColorComponentFlagBits::eA
: vk::ColorComponentFlagBits::eA | vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB}},
.DynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor},
.layout = *p.layout,
.renderPass = *rp,
.subpass = 0,
};
p.pipeline = device.createGraphicsPipeline(application::get_pipeline_cache(), pipeline_info);
spdlog::info("Created blit pipeline for stream {}, view {}", stream, view);
}
cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, *p.pipeline);
vk::DescriptorImageInfo image_info{
.imageView = image,
.imageLayout = layout,
};
cmd.pushDescriptorSetKHR(
vk::PipelineBindPoint::eGraphics,
*p.layout,
0,
vk::WriteDescriptorSet{
.dstBinding = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info,
});
int x0 = description.offset_x - view * extent.width;
int y0 = description.offset_y;
int x1 = x0 + description.width * description.subsampling;
int y1 = y0 + description.height * description.subsampling;
cmd.setViewport(
0,
vk::Viewport{
.x = (float)x0,
.y = (float)y0,
.width = float(description.width * description.subsampling),
.height = float(description.height * description.subsampling),
.minDepth = 0,
.maxDepth = 1,
});
x0 = std::clamp<int>(x0, 0, extent.width);
x1 = std::clamp<int>(x1, 0, extent.width);
y0 = std::clamp<int>(y0, 0, extent.height);
y1 = std::clamp<int>(y1, 0, extent.height);
cmd.setScissor(
0,
vk::Rect2D{
.offset = {.x = x0, .y = y0},
.extent = {.width = uint32_t(x1 - x0), .height = uint32_t(y1 - y0)},
});
cmd.draw(3, 1, 0, 0);
}
blitter::output blitter::end(vk::raii::CommandBuffer & cmd)
{
if (*fb)
cmd.endRenderPass();
return current;
}
} // namespace wivrn
+72
View File
@@ -0,0 +1,72 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "vk/allocation.h"
#include "wivrn_packets.h"
#include <vulkan/vulkan_raii.hpp>
namespace wivrn
{
class blitter
{
public:
struct output
{
vk::ImageView rgb;
vk::Sampler sampler_rgb;
vk::Rect2D rect_rgb;
vk::ImageLayout layout_rgb;
vk::ImageView a;
vk::Sampler sampler_a;
vk::Rect2D rect_a;
vk::ImageLayout layout_a;
};
private:
vk::raii::Device & device;
size_t view;
to_headset::video_stream_description desc;
// indices to simply passthrough, if -1 image needs to be blitted
int passthrough_rgb = -1;
int passthrough_a = -1;
image_allocation target;
vk::raii::ImageView image_view = nullptr;
vk::raii::RenderPass rp = nullptr;
vk::raii::Framebuffer fb = nullptr;
vk::raii::Sampler sampler = nullptr;
struct pipeline_t
{
vk::raii::DescriptorSetLayout set_layout = nullptr;
vk::raii::PipelineLayout layout = nullptr;
vk::raii::Pipeline pipeline = nullptr;
bool used = false; // true if we need this image for blitting
};
std::vector<pipeline_t> pipelines;
output current;
public:
blitter(vk::raii::Device & device, size_t view);
void reset(const to_headset::video_stream_description & desc);
void begin(vk::raii::CommandBuffer &);
void push_image(vk::raii::CommandBuffer & buf, uint8_t stream, vk::Sampler sampler, const vk::Extent2D &, vk::ImageView image, vk::ImageLayout);
output end(vk::raii::CommandBuffer &);
};
} // namespace wivrn
+96 -55
View File
@@ -18,72 +18,113 @@
#include "hand_model.h"
#include "openxr/openxr.h"
#include <ranges>
#include "render/scene_components.h"
#include <entt/entt.hpp>
#include <magic_enum.hpp>
#include <spdlog/spdlog.h>
hand_model::hand_model(const std::filesystem::path & gltf_path, scene_loader & loader, scene_data & scene)
namespace components
{
root_node = scene.new_node();
root_node->name = gltf_path.stem();
struct hand_joint
{
XrHandEXT hand;
XrHandJointEXT joint;
};
} // namespace components
scene.import(loader(gltf_path), root_node);
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"},
{XR_HAND_JOINT_THUMB_METACARPAL_EXT, "thumb-metacarpal"},
{XR_HAND_JOINT_THUMB_PROXIMAL_EXT, "thumb-phalanx-proximal"},
{XR_HAND_JOINT_THUMB_DISTAL_EXT, "thumb-phalanx-distal"},
{XR_HAND_JOINT_THUMB_TIP_EXT, "thumb-tip"},
{XR_HAND_JOINT_INDEX_METACARPAL_EXT, "index-finger-metacarpal"},
{XR_HAND_JOINT_INDEX_PROXIMAL_EXT, "index-finger-phalanx-proximal"},
{XR_HAND_JOINT_INDEX_INTERMEDIATE_EXT, "index-finger-phalanx-intermediate"},
{XR_HAND_JOINT_INDEX_DISTAL_EXT, "index-finger-phalanx-distal"},
{XR_HAND_JOINT_INDEX_TIP_EXT, "index-finger-tip"},
{XR_HAND_JOINT_MIDDLE_METACARPAL_EXT, "middle-finger-metacarpal"},
{XR_HAND_JOINT_MIDDLE_PROXIMAL_EXT, "middle-finger-phalanx-proximal"},
{XR_HAND_JOINT_MIDDLE_INTERMEDIATE_EXT, "middle-finger-phalanx-intermediate"},
{XR_HAND_JOINT_MIDDLE_DISTAL_EXT, "middle-finger-phalanx-distal"},
{XR_HAND_JOINT_MIDDLE_TIP_EXT, "middle-finger-tip"},
{XR_HAND_JOINT_RING_METACARPAL_EXT, "ring-finger-metacarpal"},
{XR_HAND_JOINT_RING_PROXIMAL_EXT, "ring-finger-phalanx-proximal"},
{XR_HAND_JOINT_RING_INTERMEDIATE_EXT, "ring-finger-phalanx-intermediate"},
{XR_HAND_JOINT_RING_DISTAL_EXT, "ring-finger-phalanx-distal"},
{XR_HAND_JOINT_RING_TIP_EXT, "ring-finger-tip"},
{XR_HAND_JOINT_LITTLE_METACARPAL_EXT, "pinky-finger-metacarpal"},
{XR_HAND_JOINT_LITTLE_PROXIMAL_EXT, "pinky-finger-phalanx-proximal"},
{XR_HAND_JOINT_LITTLE_INTERMEDIATE_EXT, "pinky-finger-phalanx-intermediate"},
{XR_HAND_JOINT_LITTLE_DISTAL_EXT, "pinky-finger-phalanx-distal"},
{XR_HAND_JOINT_LITTLE_TIP_EXT, "pinky-finger-tip"},
// clang-format on
}};
joints.resize(XR_HAND_JOINT_COUNT_EXT);
// clang-format off
joints[XR_HAND_JOINT_PALM_EXT] = node_handle();
joints[XR_HAND_JOINT_WRIST_EXT] = scene.find_node(root_node, "wrist");
joints[XR_HAND_JOINT_THUMB_METACARPAL_EXT] = scene.find_node(root_node, "thumb-metacarpal");
joints[XR_HAND_JOINT_THUMB_PROXIMAL_EXT] = scene.find_node(root_node, "thumb-phalanx-proximal");
joints[XR_HAND_JOINT_THUMB_DISTAL_EXT] = scene.find_node(root_node, "thumb-phalanx-distal");
joints[XR_HAND_JOINT_THUMB_TIP_EXT] = scene.find_node(root_node, "thumb-tip");
joints[XR_HAND_JOINT_INDEX_METACARPAL_EXT] = scene.find_node(root_node, "index-finger-metacarpal");
joints[XR_HAND_JOINT_INDEX_PROXIMAL_EXT] = scene.find_node(root_node, "index-finger-phalanx-proximal");
joints[XR_HAND_JOINT_INDEX_INTERMEDIATE_EXT] = scene.find_node(root_node, "index-finger-phalanx-intermediate");
joints[XR_HAND_JOINT_INDEX_DISTAL_EXT] = scene.find_node(root_node, "index-finger-phalanx-distal");
joints[XR_HAND_JOINT_INDEX_TIP_EXT] = scene.find_node(root_node, "index-finger-tip");
joints[XR_HAND_JOINT_MIDDLE_METACARPAL_EXT] = scene.find_node(root_node, "middle-finger-metacarpal");
joints[XR_HAND_JOINT_MIDDLE_PROXIMAL_EXT] = scene.find_node(root_node, "middle-finger-phalanx-proximal");
joints[XR_HAND_JOINT_MIDDLE_INTERMEDIATE_EXT] = scene.find_node(root_node, "middle-finger-phalanx-intermediate");
joints[XR_HAND_JOINT_MIDDLE_DISTAL_EXT] = scene.find_node(root_node, "middle-finger-phalanx-distal");
joints[XR_HAND_JOINT_MIDDLE_TIP_EXT] = scene.find_node(root_node, "middle-finger-tip");
joints[XR_HAND_JOINT_RING_METACARPAL_EXT] = scene.find_node(root_node, "ring-finger-metacarpal");
joints[XR_HAND_JOINT_RING_PROXIMAL_EXT] = scene.find_node(root_node, "ring-finger-phalanx-proximal");
joints[XR_HAND_JOINT_RING_INTERMEDIATE_EXT] = scene.find_node(root_node, "ring-finger-phalanx-intermediate");
joints[XR_HAND_JOINT_RING_DISTAL_EXT] = scene.find_node(root_node, "ring-finger-phalanx-distal");
joints[XR_HAND_JOINT_RING_TIP_EXT] = scene.find_node(root_node, "ring-finger-tip");
joints[XR_HAND_JOINT_LITTLE_METACARPAL_EXT] = scene.find_node(root_node, "pinky-finger-metacarpal");
joints[XR_HAND_JOINT_LITTLE_PROXIMAL_EXT] = scene.find_node(root_node, "pinky-finger-phalanx-proximal");
joints[XR_HAND_JOINT_LITTLE_INTERMEDIATE_EXT] = scene.find_node(root_node, "pinky-finger-phalanx-intermediate");
joints[XR_HAND_JOINT_LITTLE_DISTAL_EXT] = scene.find_node(root_node, "pinky-finger-phalanx-distal");
joints[XR_HAND_JOINT_LITTLE_TIP_EXT] = scene.find_node(root_node, "pinky-finger-tip");
// clang-format on
void hand_model::add_hand(scene & scene,
XrHandEXT hand,
const std::filesystem::path & gltf_path,
uint32_t layer_mask)
{
auto && [entity, node] = scene.load_gltf(gltf_path, layer_mask);
node.name = gltf_path.stem();
for (auto [joint, name]: joints)
{
entt::entity joint_entity = find_node_by_name(scene.world, name, entity);
scene.world.emplace<components::hand_joint>(joint_entity, hand, joint);
}
// Fake joint to hide the hand when it should not be visible
scene.world.emplace<components::hand_joint>(entity, hand, (XrHandJointEXT)-1);
}
void hand_model::apply(const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints_location)
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)
{
if (joints_location and xr::hand_tracker::check_flags(*joints_location, XR_SPACE_LOCATION_POSITION_VALID_BIT | XR_SPACE_LOCATION_POSITION_TRACKED_BIT, 0))
for (auto && [entity, hj, node]: scene.view<components::hand_joint, components::node>().each())
{
root_node->visible = true;
auto f = [&](const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints) {
if (joints.has_value())
{
node.visible = true;
for (auto && [joint, loc]: std::views::zip(joints, *joints_location))
if (hj.joint < 0 or hj.joint > XR_HAND_JOINT_COUNT_EXT)
return;
const auto & pose = (*joints)[hj.joint].first.pose;
node.position = {
pose.position.x,
pose.position.y,
pose.position.z};
node.orientation = {
pose.orientation.w,
pose.orientation.x,
pose.orientation.y,
pose.orientation.z};
}
else
{
node.visible = false;
}
};
switch (hj.hand)
{
if (!joint)
continue;
joint->position = {
loc.first.pose.position.x,
loc.first.pose.position.y,
loc.first.pose.position.z};
joint->orientation = {
loc.first.pose.orientation.w,
loc.first.pose.orientation.x,
loc.first.pose.orientation.y,
loc.first.pose.orientation.z};
case XR_HAND_LEFT_EXT:
f(left_hand);
break;
case XR_HAND_RIGHT_EXT:
f(right_hand);
break;
default:
break;
}
}
else
{
root_node->visible = false;
}
}
+12 -8
View File
@@ -18,16 +18,20 @@
#pragma once
#include "scene.h"
#include "xr/hand_tracker.h"
#include <render/scene_data.h>
#include <entt/fwd.hpp>
#include <filesystem>
#include <openxr/openxr.h>
struct hand_model
namespace hand_model
{
node_handle root_node;
std::vector<node_handle> joints;
void add_hand(scene & scene,
XrHandEXT hand,
const std::filesystem::path & gltf_path,
uint32_t layer_mask);
hand_model(const std::filesystem::path & gltf_path, scene_loader & loader, scene_data & scene);
void apply(const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints);
};
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);
}; // namespace hand_model
+130 -91
View File
@@ -21,6 +21,9 @@
#include "application.h"
#include "asset.h"
#include "hardware.h"
#include "render/scene_components.h"
#include "xr/space.h"
#include <entt/entt.hpp>
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/quaternion.hpp>
#include <magic_enum.hpp>
@@ -29,9 +32,47 @@
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <variant>
namespace components
{
namespace details
{
struct node_state_transform
{
glm::vec3 position;
glm::quat orientation;
};
struct node_state_visibility
{
};
using node_state = std::variant<std::pair<node_state_transform, node_state_transform>, node_state_visibility>;
} // namespace details
// Component added to nodes affected by actions
struct visual_response
{
XrAction action;
XrActionType type;
int axis; // Only if type is XR_ACTION_TYPE_VECTOR2F_INPUT
float bias;
float scale;
details::node_state state;
};
} // namespace components
namespace
{
// Component added to nodes bound to an action space
struct bound_space
{
xr::spaces space;
};
// clang-format off
const std::unordered_map<std::string, std::string> input_mappings = {
{"xr-standard-squeeze" , "/input/squeeze/value" },
@@ -125,14 +166,14 @@ struct json_visual_response
component_type type;
component_property property;
std::string target_node;
input_profile::node_state state;
components::details::node_state state;
// OpenXR component path
std::string component_subpath;
};
} // namespace
input_profile::input_profile(const std::filesystem::path & json_profile, scene_loader & loader, scene_data & scene_controllers, scene_data & scene_rays)
input_profile::input_profile(scene & scene, const std::filesystem::path & json_profile, uint32_t layer_mask_controller, uint32_t layer_mask_ray)
{
std::string json = asset(json_profile);
@@ -141,17 +182,20 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
id = std::string(root["profileId"]);
// Don't load them into the scene right now in case there is an exception
std::vector<std::pair<std::string, scene_data>> models;
std::vector<std::tuple<std::string, entt::entity, entt::registry>> models;
std::vector<json_visual_response> json_responses;
// Fill models with the different models to be loaded and their name ("left" or "right")
// Don't load them into the scene right now in case there is an exception
for (simdjson::dom::key_value_pair layout: simdjson::dom::object(root["layouts"]))
{
// TODO handle case where i.key is none and there is no left or right
// std::string user_path = "/user/hand/" + std::string(layout.key);
std::filesystem::path asset_path = json_profile.parent_path() / std::string(layout.value["assetPath"]);
scene_data & data = models.emplace_back(layout.key, loader(asset_path)).second;
// scene.load_gltf(asset_path);
entt::registry & data = std::get<2>(models.emplace_back(layout.key, entt::null, (*scene.loader)(asset_path)));
for (simdjson::dom::key_value_pair component: simdjson::dom::object(layout.value["components"]))
{
@@ -177,40 +221,38 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
vr.component_subpath = component_subpath;
// Check if the node exists
data.find_node(vr.target_node);
find_node_by_name(data, vr.target_node);
auto node_property = parse_value_node_property(response.value["valueNodeProperty"]);
switch (node_property)
{
case value_node_property::transform: {
auto min_node = data.find_node(response.value["minNodeName"]);
auto max_node = data.find_node(response.value["maxNodeName"]);
auto min_node = data.get<components::node>(find_node_by_name(data, std::string(response.value["minNodeName"])));
auto max_node = data.get<components::node>(find_node_by_name(data, std::string(response.value["maxNodeName"])));
node_state_transform min{
min_node->position,
min_node->orientation};
components::details::node_state_transform min{
min_node.position,
min_node.orientation};
node_state_transform max{
max_node->position,
max_node->orientation};
components::details::node_state_transform max{
max_node.position,
max_node.orientation};
vr.state = std::make_pair(min, max);
}
break;
case value_node_property::visibility:
vr.state = node_state_visibility{};
vr.state = components::details::node_state_visibility{};
break;
}
}
}
}
for (auto && [layout, model]: models)
// Add all models in the scene
for (auto & [layout, entity, model]: models)
{
node_handle root_node = scene_controllers.new_node();
root_node->name = layout;
xr::spaces space;
if (layout == "left")
space = xr::spaces::grip_left;
@@ -223,9 +265,16 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
else
continue;
model_handles.emplace_back(space, root_node);
entity = scene.world.create();
scene.world.emplace<bound_space>(entity, space);
scene.world.emplace<components::node>(entity, components::node{
.name = layout,
.layer_mask = layer_mask_controller,
});
scene_controllers.import(std::move(model), root_node);
scene.loader->add_prefab(scene.world, std::move(model), entity);
spdlog::debug("Created entity {}", layout);
}
for (simdjson::dom::key_value_pair layout: simdjson::dom::object(root["layouts"]))
@@ -238,16 +287,16 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
else
continue;
node_handle root_node = scene_rays.new_node();
root_node->name = (std::string)layout.key + "_ray";
model_handles.emplace_back(space, root_node);
auto && [entity, node] = scene.load_gltf(controller_ray_model_name(), layer_mask_ray);
node.name = (std::string)layout.key + "_ray";
spdlog::debug("Created entity {}", node.name);
scene_rays.import(loader(controller_ray_model_name()), root_node);
scene.world.emplace<bound_space>(entity, space);
if (layout.key == "left")
left_ray = root_node;
left_ray = entity;
else if (layout.key == "right")
right_ray = root_node;
right_ray = entity;
}
for (auto & json_response: json_responses)
@@ -264,7 +313,7 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
continue;
}
auto & response = responses.emplace_back();
components::visual_response response;
response.action = action.first;
response.type = action.second;
@@ -289,107 +338,101 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
break;
}
node_handle controller_root_node;
for (auto && [i, j]: model_handles)
entt::entity controller_entity = entt::null;
for (const auto & [layout, entity, model]: models)
{
if (j->name == json_response.layout)
if (layout == json_response.layout)
{
controller_root_node = j;
assert(controller_root_node->name == json_response.layout);
controller_entity = entity;
break;
}
}
response.target.node = scene_controllers.find_node(controller_root_node, json_response.target_node);
response.target.state = json_response.state;
response.state = json_response.state;
auto target = find_node_by_name(scene.world, json_response.target_node, controller_entity);
scene.world.emplace<components::visual_response>(target, response);
}
offset.fill({{0, 0, 0}, {1, 0, 0, 0}});
}
static void apply_visual_response(node_handle node, std::pair<input_profile::node_state_transform, input_profile::node_state_transform> transforms, float value)
static void apply_visual_response(components::node & node, std::pair<components::details::node_state_transform, components::details::node_state_transform> transforms, float value)
{
node->position = glm::mix(transforms.first.position, transforms.second.position, value);
node->orientation = glm::slerp(transforms.first.orientation, transforms.second.orientation, value);
node.position = glm::mix(transforms.first.position, transforms.second.position, value);
node.orientation = glm::slerp(transforms.first.orientation, transforms.second.orientation, value);
}
static void apply_visual_response(node_handle node, input_profile::node_state_visibility, float value)
static void apply_visual_response(components::node & node, components::details::node_state_visibility, float value)
{
node->visible = value > 0.5;
node.visible = value > 0.5;
}
static void set_clipping_planes(node_handle node, std::span<glm::vec4> clipping_planes)
static void set_clipping_planes(entt::registry & scene, entt::entity entity, std::span<glm::vec4> clipping_planes)
{
if (not node)
return;
// If the ray starts on the wrong side of the GUI, hide it entirely
// This assumes the node is a child of the root node
components::node & node = scene.get<components::node>(entity);
for (glm::vec4 & plane: clipping_planes)
{
if (glm::dot(plane, glm::vec4(node->position, 1)) < 0)
if (glm::dot(plane, glm::vec4(node.position, 1)) < 0)
{
node->visible = false;
scene.get<components::node>(entity).visible = false;
return;
}
}
node->visible = true;
for (auto child_node: node.children())
// Apply the clipping planes on direct children of the target entity
for (auto && [child_entity, child_node]: scene.view<components::node>().each())
{
size_t nb_clipping_planes = std::min(child_node->clipping_planes.size(), clipping_planes.size());
if (child_node.parent == entity)
{
size_t nb_clipping_planes = std::min(child_node.clipping_planes.size(), clipping_planes.size());
auto copy_results = std::ranges::copy_n(
clipping_planes.begin(),
nb_clipping_planes,
child_node->clipping_planes.begin());
auto copy_results = std::ranges::copy_n(
clipping_planes.begin(),
nb_clipping_planes,
child_node.clipping_planes.begin());
// Disable the remaining clipping planes
std::ranges::fill_n(
copy_results.out,
child_node->clipping_planes.size() - nb_clipping_planes,
glm::vec4(0, 0, 0, 1));
// Disable the remaining clipping planes
std::ranges::fill_n(
copy_results.out,
child_node.clipping_planes.size() - nb_clipping_planes,
glm::vec4(0, 0, 0, 1));
}
}
}
void input_profile::apply(XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right, std::span<glm::vec4> pointer_limits)
void input_profile::apply(entt::registry & scene, XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right, std::span<glm::vec4> pointer_limits)
{
for (auto && [space, node]: model_handles)
for (auto && [entity, node, space]: scene.view<components::node, bound_space>().each())
{
if ((space == xr::spaces::grip_left or space == xr::spaces::aim_left) and hide_left)
if ((space.space == xr::spaces::grip_left or space.space == xr::spaces::aim_left) and hide_left)
{
node->visible = false;
continue;
node.visible = false;
}
if ((space == xr::spaces::grip_right or space == xr::spaces::aim_right) and hide_right)
else if ((space.space == xr::spaces::grip_right or space.space == xr::spaces::aim_right) and hide_right)
{
node->visible = false;
continue;
node.visible = false;
}
if (auto location = application::locate_controller(application::space(space), world_space, predicted_display_time); location)
else if (auto location = application::locate_controller(application::space(space.space), world_space, predicted_display_time); location)
{
node->visible = true;
node.visible = true;
assert((int)space >= 0);
assert((int)space < offset.size());
auto & [p, q] = offset[space];
assert((int)space.space >= 0);
assert((int)space.space < offset.size());
auto & [p, q] = offset[space.space];
node->position = location->first + glm::mat3_cast(location->second * q) * p;
node->orientation = location->second * q;
node.position = location->first + glm::mat3_cast(location->second * q) * p;
node.orientation = location->second * q;
}
else
{
node->visible = false;
node.visible = false;
}
}
set_clipping_planes(left_ray, pointer_limits);
set_clipping_planes(right_ray, pointer_limits);
for (auto & response: responses)
for (auto && [entity, node, response]: scene.view<components::node, components::visual_response>().each())
{
assert(response.action);
@@ -441,20 +484,16 @@ void input_profile::apply(XrSpace world_space, XrTime predicted_display_time, bo
if ((scaled_value < 0) || (scaled_value > 1))
{
std::string full_name = response.target.node->name;
for (auto i = response.target.node; i; i = i.parent())
{
full_name = i->name + "/" + full_name;
}
spdlog::warn("Out of range value {} (scaled to {}) for node {}", *value, scaled_value, full_name);
spdlog::warn("Out of range value {} (scaled to {}) for node {}", *value, scaled_value, get_node_name(scene, entity));
}
std::visit([&](auto & transform) {
apply_visual_response(response.target.node, transform, scaled_value);
apply_visual_response(node, transform, scaled_value);
},
response.target.state);
response.state);
}
}
set_clipping_planes(scene, left_ray, pointer_limits);
set_clipping_planes(scene, right_ray, pointer_limits);
}
+7 -38
View File
@@ -18,58 +18,27 @@
#pragma once
#include "scene.h"
#include <cstdint>
#include <entt/fwd.hpp>
#include <filesystem>
#include <glm/glm.hpp>
#include <magic_enum_containers.hpp>
#include <render/scene_data.h>
#include <span>
#include <variant>
#include <xr/space.h>
#include <openxr/openxr.h>
struct input_profile
{
struct node_state_transform
{
glm::vec3 position;
glm::quat orientation;
};
struct node_state_visibility
{
};
using node_state = std::variant<std::pair<node_state_transform, node_state_transform>, node_state_visibility>;
struct node_target
{
node_handle node;
node_state state;
};
struct visual_response
{
XrAction action;
XrActionType type;
int axis; // Only if type is XR_ACTION_TYPE_VECTOR2F_INPUT
float bias;
float scale;
node_target target;
};
std::string id;
std::vector<visual_response> responses;
std::vector<std::pair<xr::spaces, node_handle>> model_handles;
node_handle left_ray;
node_handle right_ray;
entt::entity left_ray;
entt::entity right_ray;
magic_enum::containers::array<xr::spaces, std::pair<glm::vec3, glm::quat>> offset;
input_profile(const std::filesystem::path & json_profile, scene_loader & loader, scene_data & scene_controllers, scene_data & scene_rays);
input_profile(scene & scene, const std::filesystem::path & json_profile, uint32_t layer_mask_controller, uint32_t layer_mask_ray);
// application::poll_actions() must have been called before
void apply(XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right, std::span<glm::vec4> pointer_limits);
void apply(entt::registry & scene, XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right, std::span<glm::vec4> pointer_limits);
};
+275 -593
View File
File diff suppressed because it is too large Load Diff
+27 -31
View File
@@ -22,23 +22,20 @@
#include "asset.h"
#include "configuration.h"
#include "crypto.h"
#include "render/scene_data.h"
#include "scene.h"
#include "scenes/hand_model.h"
#include "scenes/lobby_keyboard.h"
#include "utils/thread_safe.h"
#include "wifi_lock.h"
#include "wivrn_config.h"
#include "wivrn_discover.h"
#include "xr/face_tracker.h"
#include <vulkan/vulkan_raii.hpp>
#include <openxr/openxr.h>
#include "xr/system.h"
#include <optional>
#include <vector>
#include "input_profile.h"
#include "render/imgui_impl.h"
#include "render/scene_renderer.h"
#include "utils/async.h"
class wivrn_session;
@@ -64,37 +61,32 @@ class lobby : public scene_impl<lobby>
std::string server_name;
bool autoconnect_enabled = true;
std::optional<scene_renderer> renderer;
std::optional<scene_data> lobby_scene;
std::optional<scene_data> controllers_scene;
std::optional<input_profile> input;
std::optional<hand_model> left_hand;
std::optional<hand_model> right_hand;
node_handle lobby_handle;
bool composition_layer_depth_test_supported;
bool composition_layer_color_scale_bias_supported;
entt::entity lobby_entity;
std::optional<imgui_context> imgui_ctx;
std::array<XrAction, 2> haptic_output;
std::optional<xr::hand_tracker> left_hand;
std::optional<xr::hand_tracker> right_hand;
xr::face_tracker face_tracker;
std::string selected_item;
std::unique_ptr<asset> license;
ImGuiID hovered_item;
std::vector<xr::swapchain> swapchains_lobby;
std::vector<xr::swapchain> swapchains_lobby_depth;
std::vector<xr::swapchain> swapchains_controllers;
std::vector<xr::swapchain> swapchains_controllers_depth;
static inline const uint32_t layer_lobby = 1 << 0;
static inline const uint32_t layer_controllers = 1 << 1;
static inline const uint32_t layer_rays = 1 << 2;
uint32_t width;
uint32_t height;
xr::swapchain swapchain_imgui;
vk::Format swapchain_format;
vk::Format depth_format;
xr::system::passthrough_type passthrough_supported;
XrViewConfigurationView stream_view;
#if WIVRN_CLIENT_DEBUG_MENU
// GUI debug
node_handle xyz_axes_left_controller;
node_handle xyz_axes_right_controller;
entt::entity xyz_axes_left_controller;
entt::entity xyz_axes_right_controller;
bool display_debug_axes = false;
bool display_grip_instead_of_aim = false;
glm::vec3 offset_position{};
@@ -108,14 +100,16 @@ class lobby : public scene_impl<lobby>
XrAction recenter_left_action = XR_NULL_HANDLE;
XrAction recenter_right_action = XR_NULL_HANDLE;
std::optional<glm::vec3> gui_recenter_position;
std::optional<float> gui_recenter_distance;
// std::optional<glm::vec3> gui_recenter_position;
// std::optional<float> gui_recenter_distance;
// Which controller is used for recentering, position of the pointed point in the GUI, in GUI axes, and distance between the controller and the pointed point during recentering
std::optional<std::tuple<xr::spaces, glm::vec3, float>> recentering_context;
bool recenter_gui = true;
void move_gui(glm::vec3 head_position, glm::vec3 new_gui_position);
void tooltip(std::string_view text);
enum class tab
{
first_run,
server_list,
settings,
post_processing,
@@ -124,11 +118,13 @@ class lobby : public scene_impl<lobby>
#endif
about,
licenses,
exit
exit,
connected,
};
tab current_tab = tab::server_list;
tab last_current_tab = tab::server_list;
int optional_feature_index = 0; // Which step of the first run screen are we in
ImTextureID about_picture;
virtual_keyboard keyboard;
@@ -146,6 +142,7 @@ class lobby : public scene_impl<lobby>
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_server_list();
void gui_new_server();
void gui_settings();
@@ -154,15 +151,14 @@ class lobby : public scene_impl<lobby>
void gui_about();
void gui_licenses();
void gui_keyboard();
void gui_first_run();
void setup_passthrough();
void vibrate_on_hover();
void connect(const configuration::server_data & data);
std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service service, bool manual_connection);
std::optional<glm::vec3> check_recenter_gesture(const std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT> & joints);
std::optional<glm::vec3> check_recenter_gesture(xr::spaces space, const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints);
std::optional<glm::vec3> check_recenter_action(XrTime predicted_display_time, glm::vec3 head_position);
std::optional<glm::vec3> check_recenter_gui(glm::vec3 head_position, glm::quat head_orientation);
File diff suppressed because it is too large Load Diff
+12 -12
View File
@@ -319,14 +319,14 @@ virtual_keyboard::key_status virtual_keyboard::button_behavior(const ImRect & bb
float prev_held_duration = held_duration;
held_duration += g.IO.DeltaTime;
if ((flags & ImGuiButtonFlags_Repeat) and held_duration > g.IO.KeyRepeatDelay)
{
int n1 = (prev_held_duration - g.IO.KeyRepeatDelay) / g.IO.KeyRepeatRate;
int n2 = (held_duration - g.IO.KeyRepeatDelay) / g.IO.KeyRepeatRate;
if (n2 != n1)
pressed = true;
}
// if ((flags & ImGuiButtonFlags_Repeat) and held_duration > g.IO.KeyRepeatDelay)
// {
// int n1 = (prev_held_duration - g.IO.KeyRepeatDelay) / g.IO.KeyRepeatRate;
// int n2 = (held_duration - g.IO.KeyRepeatDelay) / g.IO.KeyRepeatRate;
//
// if (n2 != n1)
// pressed = true;
// }
}
else
{
@@ -381,8 +381,8 @@ virtual_keyboard::key_status virtual_keyboard::draw_single_key(const key & k, in
ImGuiButtonFlags flags = ImGuiButtonFlags_None;
if (k.flag & key_flag_repeat)
flags |= ImGuiButtonFlags_Repeat;
// if (k.flag & key_flag_repeat)
// flags |= ImGuiButtonFlags_Repeat;
auto status = button_behavior(bb, id, window_hovered, flags);
@@ -462,7 +462,7 @@ void virtual_keyboard::press_single_key(const key & k)
}
}
void virtual_keyboard::display(ImGuiID & hovered_id)
void virtual_keyboard::display(imgui_context & ctx)
{
ImGuiStyle & style = ImGui::GetStyle();
@@ -534,7 +534,7 @@ void virtual_keyboard::display(ImGuiID & hovered_id)
auto status = draw_single_key(key, id++, ImVec2{base_key_width * key.width - style.ItemSpacing.x, key_height}, window_hovered);
if (status.hovered)
hovered_id = ImGui::GetItemID();
ctx.set_hovered_item();
}
key_position.x += base_key_width * key.width;
+2 -1
View File
@@ -20,6 +20,7 @@
#pragma once
#include "imgui.h"
#include "render/imgui_impl.h"
#include <string>
#include <vector>
@@ -80,7 +81,7 @@ private:
bool symbols_shown = false;
public:
void display(ImGuiID & hovered);
void display(imgui_context & ctx);
const std::string_view get_layout() const;
void set_layout(std::string_view layout_name);
};
+491 -488
View File
File diff suppressed because it is too large Load Diff
+90 -32
View File
@@ -19,15 +19,19 @@
#pragma once
#include "app_launcher.h"
#include "audio/audio.h"
#include "decoder/shard_accumulator.h"
#include "render/imgui_impl.h"
#include "scene.h"
#include "stream_reprojection.h"
#include "scenes/blitter.h"
#include "scenes/input_profile.h"
#include "stream_defoveator.h"
#include "utils/thread_safe.h"
#include "wifi_lock.h"
#include "wivrn_client.h"
#include "wivrn_packets.h"
#include "xr/passthrough.h"
#include "xr/space.h"
#include <mutex>
#include <shared_mutex>
#include <thread>
@@ -46,6 +50,8 @@ public:
};
static const size_t image_buffer_size = 3;
app_launcher apps;
private:
static const size_t view_count = 2;
@@ -54,16 +60,12 @@ private:
struct accumulator_images
{
std::unique_ptr<wivrn::shard_accumulator> decoder;
vk::raii::DescriptorSetLayout descriptor_set_layout = nullptr;
vk::DescriptorSet descriptor_set = nullptr;
vk::raii::PipelineLayout blit_pipeline_layout = nullptr;
vk::raii::Pipeline blit_pipeline = nullptr;
// latest frames from oldest to most recent
// latest frames, rolling buffer
std::array<std::shared_ptr<wivrn::shard_accumulator::blit_handle>, image_buffer_size> latest_frames;
std::shared_ptr<wivrn::shard_accumulator::blit_handle> frame(uint64_t id) const;
bool alpha() const;
std::vector<uint64_t> frames() const;
bool empty() const;
};
wifi_lock::wifi wifi;
@@ -75,9 +77,9 @@ private:
std::unique_ptr<wivrn_session> network_session;
std::atomic<bool> exiting = false;
std::thread network_thread;
std::mutex tracking_control_mutex;
to_headset::tracking_control tracking_control{};
thread_safe<to_headset::tracking_control> tracking_control{};
std::array<std::atomic<interaction_profile>, 2> interaction_profiles; // left and right hand
std::atomic<bool> interaction_profile_changed = false;
std::atomic<bool> recenter_requested = false;
std::atomic<XrDuration> display_time_phase = 0;
std::atomic<XrDuration> display_time_period = 0;
@@ -88,23 +90,10 @@ private:
std::shared_mutex decoder_mutex;
std::optional<to_headset::video_stream_description> video_stream_description;
std::vector<accumulator_images> decoders; // Locked by decoder_mutex
vk::raii::DescriptorPool blit_descriptor_pool = nullptr;
vk::raii::RenderPass blit_render_pass = nullptr;
vk::Extent2D decoder_out_size;
vk::Format decoder_out_format;
image_allocation decoder_out_image;
std::array<blitter, view_count> blitters;
struct renderpass_output
{
vk::raii::ImageView image_view = nullptr;
vk::raii::Framebuffer frame_buffer = nullptr;
};
std::array<renderpass_output, view_count> decoder_output;
std::optional<stream_reprojection> reprojector;
std::optional<xr::passthrough> passthrough;
std::optional<stream_defoveator> defoveator;
vk::raii::Fence fence = nullptr;
vk::raii::CommandBuffer command_buffer = nullptr;
@@ -122,24 +111,76 @@ private:
xr::swapchain swapchain;
xr::swapchain swapchain_imgui;
vk::Format swapchain_format;
std::optional<audio> audio_handle;
std::optional<xr::hand_tracker> left_hand;
std::optional<xr::hand_tracker> right_hand;
std::optional<input_profile> input;
static inline const uint32_t layer_controllers = 1 << 0;
static inline const uint32_t layer_rays = 1 << 1;
// Size of the composition layer used for the controllers
uint32_t width;
uint32_t height;
std::optional<imgui_context> imgui_ctx;
bool plots_visible = true;
enum class gui_status
{
hidden,
overlay_only,
compact,
stats,
settings,
foveation_settings,
applications,
application_launcher,
};
bool is_gui_interactable() const;
std::atomic<gui_status> gui_status = gui_status::hidden;
enum gui_status last_gui_status = gui_status::hidden;
enum gui_status next_gui_status = gui_status::stats;
XrTime gui_status_last_change;
float dimming = 0;
XrAction plots_toggle_1 = XR_NULL_HANDLE;
XrAction plots_toggle_2 = XR_NULL_HANDLE;
XrAction recenter_left = XR_NULL_HANDLE;
XrAction recenter_right = XR_NULL_HANDLE;
XrAction foveation_pitch = 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
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};
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);
// Keep a reference to the resources needed to blit the images until vkWaitForFences
std::vector<std::shared_ptr<wivrn::shard_accumulator::blit_handle>> current_blit_handles;
stream() = default;
XrTime running_application_req = 0;
thread_safe<to_headset::running_applications> running_applications;
stream(std::string server_name);
public:
~stream();
static std::shared_ptr<stream> create(std::unique_ptr<wivrn_session> session, float guessed_fps);
static std::shared_ptr<stream> create(
std::unique_ptr<wivrn_session> session,
float guessed_fps,
std::string server_name);
void render(const XrFrameState &) override;
void on_focused() override;
@@ -157,6 +198,9 @@ public:
void operator()(to_headset::audio_stream_description &&);
void operator()(to_headset::video_stream_description &&);
void operator()(to_headset::refresh_rate_change &&);
void operator()(to_headset::application_list &&);
void operator()(to_headset::application_icon &&);
void operator()(to_headset::running_applications &&);
void operator()(audio_data &&);
void push_blit_handle(wivrn::shard_accumulator * decoder, std::shared_ptr<wivrn::shard_accumulator::blit_handle> handle);
@@ -173,6 +217,8 @@ public:
return !exiting;
}
void start_application(std::string appid);
static meta & get_meta_scene();
private:
@@ -183,14 +229,15 @@ private:
void on_interaction_profile_changed(const XrEventDataInteractionProfileChanged &);
void setup(const to_headset::video_stream_description &);
void setup_reprojection_swapchain();
void setup_reprojection_swapchain(uint32_t width, uint32_t height);
void exit();
vk::raii::QueryPool query_pool = nullptr;
bool query_pool_filled = false;
uint64_t bytes_sent = 0;
// Used for plots
uint64_t bytes_received = 0;
uint64_t bytes_sent = 0;
float bandwidth_rx = 0;
float bandwidth_tx = 0;
@@ -245,7 +292,18 @@ private:
XrTime last_metric_time = 0;
int metrics_offset = 0;
// Used for compact view
float compact_bandwidth_rx = 0;
float compact_bandwidth_tx = 0;
float compact_cpu_time = 0;
float compact_gpu_time = 0;
void accumulate_metrics(XrTime predicted_display_time, const std::vector<std::shared_ptr<wivrn::shard_accumulator::blit_handle>> & blit_handles, const gpu_timestamps & timestamps);
std::vector<XrCompositionLayerQuad> plot_performance_metrics(XrTime predicted_display_time);
void gui_performance_metrics();
void gui_compact_view();
void gui_settings();
void gui_foveation_settings(float predicted_display_period);
void gui_applications();
void draw_gui(XrTime predicted_display_time, XrDuration predicted_display_period);
};
} // namespace scenes
+31 -27
View File
@@ -25,39 +25,43 @@ void scenes::stream::read_actions()
{
from_headset::inputs inputs;
for (const auto & [id, action, action_type]: input_actions)
if (not is_gui_interactable())
{
switch (action_type)
for (const auto & [id, action, action_type]: input_actions)
{
case XR_ACTION_TYPE_BOOLEAN_INPUT: {
auto value = application::read_action_bool(action);
if (value)
inputs.values.push_back({id, (float)value->second, value->first});
}
break;
case XR_ACTION_TYPE_FLOAT_INPUT: {
auto value = application::read_action_float(action);
if (value)
inputs.values.push_back({id, value->second, value->first});
}
break;
case XR_ACTION_TYPE_VECTOR2F_INPUT: {
auto value = application::read_action_vec2(action);
if (value)
{
inputs.values.push_back({id, value->second.x, value->first});
inputs.values.push_back({(device_id)((int)id + 1), value->second.y, value->first});
switch (action_type)
{
case XR_ACTION_TYPE_BOOLEAN_INPUT: {
auto value = application::read_action_bool(action);
if (value)
inputs.values.push_back({id, (float)value->second, value->first});
}
}
break;
case XR_ACTION_TYPE_POSE_INPUT:
default:
break;
case XR_ACTION_TYPE_FLOAT_INPUT: {
auto value = application::read_action_float(action);
if (value)
inputs.values.push_back({id, value->second, value->first});
}
break;
case XR_ACTION_TYPE_VECTOR2F_INPUT: {
auto value = application::read_action_vec2(action);
if (value)
{
inputs.values.push_back({id, value->second.x, value->first});
inputs.values.push_back({(device_id)((int)id + 1), value->second.y, value->first});
}
}
break;
case XR_ACTION_TYPE_POSE_INPUT:
default:
break;
}
}
}
try
{
network_session->send_stream(std::move(inputs));
+452
View File
@@ -0,0 +1,452 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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 "stream_defoveator.h"
#include "application.h"
#include "utils/ranges.h"
#include "vk/allocation.h"
#include "vk/pipeline.h"
#include "vk/shader.h"
#include "vk/specialization_constants.h"
#include <array>
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <vk_mem_alloc.h>
#include <vulkan/vulkan_core.h>
#include <vulkan/vulkan_raii.hpp>
struct stream_defoveator::vertex
{
// output image position
alignas(8) glm::vec2 position;
// input texture coordinates
alignas(8) glm::uvec2 uv;
};
struct vert_pc
{
glm::ivec4 rgb_rect;
glm::ivec4 a_rect;
};
void stream_defoveator::ensure_vertices(size_t num_vertices)
{
vk::BufferCreateInfo create_info{
.size = num_vertices * sizeof(vertex) * view_count,
.usage = vk::BufferUsageFlagBits::eVertexBuffer,
.sharingMode = vk::SharingMode::eExclusive,
};
if (create_info.size <= buffer.info().size)
return;
VmaAllocationCreateInfo alloc_info{
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
};
buffer = buffer_allocation(device, create_info, alloc_info);
vertices_size = num_vertices * sizeof(vertex);
}
stream_defoveator::vertex * stream_defoveator::get_vertices(size_t view)
{
assert(buffer);
return reinterpret_cast<vertex *>(reinterpret_cast<uintptr_t>(buffer.map()) + view * vertices_size);
}
stream_defoveator::pipeline_t & stream_defoveator::ensure_pipeline(size_t view, vk::Sampler rgb, vk::Sampler a)
{
auto & target = a ? pipeline_a[view] : pipeline_rgb[view];
if (*target.pipeline)
return target;
std::array samplers{rgb, a};
int32_t alpha = a ? 1 : 0;
// Create VkDescriptorSetLayout
std::array layout_binding{
vk::DescriptorSetLayoutBinding{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = uint32_t(alpha + 1),
.stageFlags = vk::ShaderStageFlagBits::eFragment,
.pImmutableSamplers = samplers.data(),
},
};
target.descriptor_set_layout = device.createDescriptorSetLayout(vk::DescriptorSetLayoutCreateInfo{
.bindingCount = layout_binding.size(),
.pBindings = layout_binding.data(),
});
target.ds = device.allocateDescriptorSets(vk::DescriptorSetAllocateInfo{
.descriptorPool = *ds_pool,
.descriptorSetCount = 1,
.pSetLayouts = &*target.descriptor_set_layout,
})[0]
.release();
// pipeline layout
vk::PushConstantRange pc_range{
.stageFlags = vk::ShaderStageFlagBits::eVertex,
.size = sizeof(vert_pc),
};
vk::PipelineLayoutCreateInfo pipeline_layout_info{
.setLayoutCount = 1,
.pSetLayouts = &*target.descriptor_set_layout,
.pushConstantRangeCount = 1,
.pPushConstantRanges = &pc_range,
};
target.layout = vk::raii::PipelineLayout(device, pipeline_layout_info);
const auto & vk_device_extensions = application::get_vk_device_extensions();
// Vertex shader
vk::raii::ShaderModule vertex_shader = load_shader(device, "reprojection.vert");
// Fragment shader
auto specialization = make_specialization_constants(
int32_t(alpha),
VkBool32(need_srgb_conversion(guess_model())));
vk::raii::ShaderModule fragment_shader = load_shader(device, "reprojection.frag");
vk::pipeline_builder pipeline_info{
.flags = {},
.Stages = {
{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.pName = "main",
},
{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.pName = "main",
.pSpecializationInfo = specialization,
},
},
.VertexBindingDescriptions = {
{
.binding = 0,
.stride = sizeof(vertex),
.inputRate = vk::VertexInputRate::eVertex,
},
},
.VertexAttributeDescriptions = {
{
.location = 0,
.binding = 0,
.format = vk::Format::eR32G32Sfloat,
.offset = offsetof(vertex, position),
},
{
.location = 1,
.binding = 0,
.format = vk::Format::eR32G32Uint,
.offset = offsetof(vertex, uv),
},
},
.InputAssemblyState = {{
.topology = vk::PrimitiveTopology::eTriangleStrip,
}},
.Viewports = {{}},
.Scissors = {{}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
}},
.MultisampleState = {{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
}},
.ColorBlendState = {.flags = {}},
.ColorBlendAttachments = {{
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA,
}},
.DynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor},
.layout = *target.layout,
.renderPass = *renderpass,
.subpass = 0,
};
target.pipeline = device.createGraphicsPipeline(application::get_pipeline_cache(), pipeline_info);
return target;
}
stream_defoveator::stream_defoveator(
vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
std::vector<vk::Image> output_images_,
vk::Extent2D output_extent,
vk::Format format) :
device(device),
physical_device(physical_device),
output_images(std::move(output_images_)),
output_extent(output_extent)
{
// Create renderpass
vk::AttachmentDescription attachment{
.format = format,
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eDontCare,
.storeOp = vk::AttachmentStoreOp::eStore,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::AttachmentReference color_ref{
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::SubpassDescription subpass{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
.colorAttachmentCount = 1,
.pColorAttachments = &color_ref,
};
vk::StructureChain renderpass_info{
vk::RenderPassCreateInfo{
.attachmentCount = 1,
.pAttachments = &attachment,
.subpassCount = 1,
.pSubpasses = &subpass,
},
};
renderpass = vk::raii::RenderPass(device, renderpass_info.get());
vk::DescriptorPoolSize pool_size{
.type = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = view_count * 4,
};
ds_pool = device.createDescriptorPool(vk::DescriptorPoolCreateInfo{
.maxSets = view_count * 2,
.poolSizeCount = 1,
.pPoolSizes = &pool_size,
});
// Create image views and framebuffers
output_image_views.reserve(output_images.size() * view_count);
framebuffers.reserve(output_images.size() * view_count);
for (vk::Image image: output_images)
{
for (uint32_t view = 0; view < view_count; ++view)
{
vk::ImageViewCreateInfo iv_info{
.image = image,
.viewType = vk::ImageViewType::e2DArray,
.format = format,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = view,
.layerCount = 1,
},
};
output_image_views.emplace_back(device, iv_info);
vk::FramebufferCreateInfo fb_create_info{
.renderPass = *renderpass,
.width = output_extent.width,
.height = output_extent.height,
.layers = 1,
};
fb_create_info.setAttachments(*output_image_views.back());
framebuffers.emplace_back(device, fb_create_info);
}
}
}
static size_t required_vertices(const wivrn::to_headset::foveation_parameter & p)
{
// strips are constructed like this:
// 0 2 4
// 1 3 5 5*
// there is one such line per value in y
// the last element is repeated to break the line
return (2 * (p.x.size() + 1) + 1) * p.y.size();
}
void stream_defoveator::defoveate(vk::raii::CommandBuffer & command_buffer,
const std::array<wivrn::to_headset::foveation_parameter, 2> & foveation,
std::span<wivrn::blitter::output> inputs,
int destination)
{
if (destination < 0 || destination >= (int)output_images.size())
throw std::runtime_error("Invalid destination image index");
ensure_vertices(std::max(required_vertices(foveation[0]), required_vertices(foveation[1])));
for (size_t view = 0; view < view_count; ++view)
{
const auto out_size = defoveated_size(foveation[view]);
auto vertices = get_vertices(view);
const auto & [px, py] = foveation[view];
assert(px.size() % 2 == 1);
assert(py.size() % 2 == 1);
const int n_ratio_y = (py.size() - 1) / 2;
const int n_ratio_x = (px.size() - 1) / 2;
command_buffer.setScissor(
0,
vk::Rect2D{
.extent = {.width = uint32_t(out_size.width), .height = uint32_t(out_size.height)},
});
command_buffer.setViewport(
0,
vk::Viewport{
.x = 0,
.y = 0,
.width = float(out_size.width),
.height = float(out_size.height),
.minDepth = 0,
.maxDepth = 1,
});
glm::uvec2 in(0);
glm::vec2 out(-0.5 * out_size.width, -0.5 * out_size.height); // pixel coordinates
glm::vec2 out_pixel_size(2. / out_size.width,
2. / out_size.height);
for (auto [iy, n_out_y]: utils::enumerate_range(py))
{
// number of output pixels per source pixels
const int ratio_y = std::abs(n_ratio_y - int(iy)) + 1;
in.x = 0;
out.x = -0.5 * out_size.width;
for (auto [ix, n_out_x]: utils::enumerate_range(px))
{
const int ratio_x = std::abs(n_ratio_x - int(ix)) + 1;
*vertices++ = {
.position = out * out_pixel_size,
.uv = in,
};
*vertices++ = {
.position = (out + glm::vec2(0, n_out_y * ratio_y)) * out_pixel_size,
.uv = (in + glm::uvec2(0, n_out_y)),
};
in.x += n_out_x;
out.x += n_out_x * ratio_x;
}
*vertices++ = {
.position = out * out_pixel_size,
.uv = in,
};
in.y += n_out_y;
out.y += n_out_y * ratio_y;
*vertices++ = {
.position = out * out_pixel_size,
.uv = in,
};
*vertices++ = {
.position = out * out_pixel_size,
.uv = in,
};
}
}
for (size_t view = 0; view < view_count; ++view)
{
vk::RenderPassBeginInfo begin_info{
.renderPass = *renderpass,
.framebuffer = *framebuffers[destination * view_count + view],
.renderArea = {
.offset = {0, 0},
.extent = output_extent,
},
};
const auto & input = inputs[view];
auto & pipeline = ensure_pipeline(view, input.sampler_rgb, input.sampler_a);
std::array image_info{
vk::DescriptorImageInfo{
.sampler = input.sampler_rgb,
.imageView = input.rgb,
.imageLayout = input.layout_rgb,
},
vk::DescriptorImageInfo{
.sampler = input.sampler_a,
.imageView = input.a,
.imageLayout = input.layout_a,
},
};
std::array descriptor_writes{
vk::WriteDescriptorSet{
.dstSet = pipeline.ds,
.dstBinding = 0,
.descriptorCount = input.sampler_a ? 2u : 1u,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = image_info.data(),
},
};
vert_pc pc{
.rgb_rect = glm::ivec4(input.rect_rgb.offset.x,
input.rect_rgb.offset.y,
input.rect_rgb.extent.width,
input.rect_rgb.extent.height),
.a_rect = glm::ivec4(input.rect_a.offset.x,
input.rect_a.offset.y,
input.rect_a.extent.width,
input.rect_a.extent.height),
};
device.updateDescriptorSets(descriptor_writes, {});
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, 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();
}
}
static uint16_t count_pixels(const std::vector<uint16_t> & param)
{
uint16_t res = 0;
const int n_ratio = (param.size() - 1) / 2;
for (auto [i, n_out]: utils::enumerate_range(param))
{
// number of output pixels per source pixels
const int ratio = std::abs(n_ratio - int(i)) + 1;
res += ratio * n_out;
}
return res;
}
XrExtent2Di stream_defoveator::defoveated_size(const wivrn::to_headset::foveation_parameter & view) const
{
return {
count_pixels(view.x),
count_pixels(view.y),
};
}
@@ -19,34 +19,35 @@
#pragma once
#include "blitter.h"
#include "vk/allocation.h"
#include "wivrn_packets.h"
#include <vulkan/vulkan_raii.hpp>
#include <openxr/openxr.h>
class stream_reprojection
class stream_defoveator
{
struct vertex;
const uint32_t view_count;
static const uint32_t view_count = 2;
// Vertex buffer
buffer_allocation buffer;
size_t vertices_size = 0;
vk::raii::Device & device;
vk::raii::PhysicalDevice & physical_device;
// Graphic pipeline
vk::raii::DescriptorSetLayout descriptor_set_layout = nullptr;
vk::raii::DescriptorPool descriptor_pool = nullptr;
vk::raii::PipelineLayout layout = nullptr;
vk::raii::RenderPass renderpass = nullptr;
vk::raii::Pipeline pipeline = nullptr;
// Source image
vk::raii::Sampler sampler = nullptr;
vk::Image input_image;
std::vector<vk::raii::ImageView> input_image_views;
std::vector<vk::DescriptorSet> descriptor_sets;
vk::Extent2D input_extent;
vk::raii::DescriptorPool ds_pool = nullptr;
struct pipeline_t
{
vk::raii::DescriptorSetLayout descriptor_set_layout = nullptr;
vk::DescriptorSet ds;
vk::raii::PipelineLayout layout = nullptr;
vk::raii::Pipeline pipeline = nullptr;
};
pipeline_t pipeline_rgb[view_count];
pipeline_t pipeline_a[view_count];
// Destination images
std::vector<vk::Image> output_images;
@@ -57,21 +58,23 @@ class stream_reprojection
void ensure_vertices(size_t num_vertices);
vertex * get_vertices(size_t view);
pipeline_t & ensure_pipeline(size_t view, vk::Sampler rgb, vk::Sampler a);
public:
stream_reprojection(
stream_defoveator(
vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
vk::Image input_image,
vk::Extent2D input_extent,
uint32_t view_count,
std::vector<vk::Image> output_images,
vk::Extent2D output_extent,
vk::Format format);
stream_reprojection(const stream_reprojection &) = delete;
stream_defoveator(const stream_defoveator &) = delete;
std::vector<XrExtent2Di> reproject(
void defoveate(
vk::raii::CommandBuffer & command_buffer,
const std::array<wivrn::to_headset::foveation_parameter, 2> & foveation,
std::span<wivrn::blitter::output> inputs,
int destination);
XrExtent2Di defoveated_size(const wivrn::to_headset::foveation_parameter &) const;
};
File diff suppressed because it is too large Load Diff
+28
View File
@@ -19,9 +19,15 @@
#include "stream.h"
#ifdef __ANDROID__
#include "application.h"
#endif
#include "utils/named_thread.h"
#include <algorithm>
#include <spdlog/spdlog.h>
#include <uni_algo/case.h>
void scenes::stream::process_packets()
{
@@ -99,3 +105,25 @@ void scenes::stream::send_feedback(const wivrn::from_headset::feedback & feedbac
spdlog::warn("Exception while sending feedback packet: {}", e.what());
}
}
void scenes::stream::operator()(to_headset::application_list && l)
{
apps(std::move(l));
}
void scenes::stream::operator()(to_headset::application_icon && icon)
{
apps(std::move(icon));
}
void scenes::stream::operator()(to_headset::running_applications && apps)
{
*running_applications.lock() = std::move(apps);
}
void scenes::stream::start_application(std::string appid)
{
network_session->send_control(wivrn::from_headset::start_app{
.app_id = std::move(appid),
});
}
-500
View File
@@ -1,500 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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 "stream_reprojection.h"
#include "application.h"
#include "utils/contains.h"
#include "utils/ranges.h"
#include "vk/allocation.h"
#include "vk/pipeline.h"
#include "vk/shader.h"
#include <array>
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <vk_mem_alloc.h>
#include <vulkan/vulkan_core.h>
#include <vulkan/vulkan_raii.hpp>
struct stream_reprojection::vertex
{
// output image position
alignas(8) glm::vec2 position;
// input texture coordinates
alignas(8) glm::vec2 uv;
};
struct SgsrSpecializationConstants
{
VkBool32 use_edge_direction;
float edge_threshold;
float edge_sharpness;
};
void stream_reprojection::ensure_vertices(size_t num_vertices)
{
vk::BufferCreateInfo create_info{
.size = num_vertices * sizeof(vertex) * view_count,
.usage = vk::BufferUsageFlagBits::eVertexBuffer,
.sharingMode = vk::SharingMode::eExclusive,
};
if (create_info.size <= buffer.info().size)
return;
VmaAllocationCreateInfo alloc_info{
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
};
buffer = buffer_allocation(device, create_info, alloc_info);
vertices_size = num_vertices * sizeof(vertex);
}
stream_reprojection::vertex * stream_reprojection::get_vertices(size_t view)
{
assert(buffer);
return reinterpret_cast<vertex *>(reinterpret_cast<uintptr_t>(buffer.map()) + view * vertices_size);
}
stream_reprojection::stream_reprojection(
vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
vk::Image input_image_,
vk::Extent2D input_extent,
uint32_t view_count,
std::vector<vk::Image> output_images_,
vk::Extent2D output_extent,
vk::Format format) :
view_count(view_count),
device(device),
input_image(input_image_),
input_extent(input_extent),
output_images(std::move(output_images_)),
output_extent(output_extent)
{
vk::SamplerCreateInfo sampler_info{
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.mipmapMode = vk::SamplerMipmapMode::eNearest,
.addressModeU = vk::SamplerAddressMode::eClampToBorder,
.addressModeV = vk::SamplerAddressMode::eClampToBorder,
.addressModeW = vk::SamplerAddressMode::eClampToBorder,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1,
.compareEnable = VK_FALSE,
.compareOp = vk::CompareOp::eNever,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = vk::BorderColor::eFloatOpaqueBlack,
.unnormalizedCoordinates = VK_FALSE,
};
if (utils::contains(application::get_vk_device_extensions(), VK_IMG_FILTER_CUBIC_EXTENSION_NAME))
sampler_info.magFilter = vk::Filter::eCubicIMG;
sampler = vk::raii::Sampler(device, sampler_info);
// Create VkDescriptorSetLayout
vk::DescriptorSetLayoutBinding layout_binding{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
};
vk::DescriptorSetLayoutCreateInfo layout_info;
layout_info.setBindings(layout_binding);
descriptor_set_layout = vk::raii::DescriptorSetLayout(device, layout_info);
std::array pool_size{
vk::DescriptorPoolSize{
.type = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = (uint32_t)view_count,
},
};
vk::DescriptorPoolCreateInfo pool_info{
.maxSets = view_count,
.poolSizeCount = pool_size.size(),
.pPoolSizes = pool_size.data(),
};
descriptor_pool = vk::raii::DescriptorPool(device, pool_info);
// Create image views and descriptor sets
for (uint32_t view = 0; view < view_count; ++view)
{
vk::ImageViewCreateInfo iv_info{
.image = input_image,
.viewType = vk::ImageViewType::e2D,
.format = vk::Format::eA8B8G8R8SrgbPack32,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = view,
.layerCount = 1,
},
};
vk::ImageView input_image_view = *input_image_views.emplace_back(device, iv_info);
vk::DescriptorSetAllocateInfo ds_info{
.descriptorPool = *descriptor_pool,
.descriptorSetCount = 1,
.pSetLayouts = &*descriptor_set_layout,
};
auto descriptor_set = descriptor_sets.emplace_back(device.allocateDescriptorSets(ds_info)[0].release());
vk::DescriptorImageInfo image_info{
.sampler = *sampler,
.imageView = input_image_view,
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
};
device.updateDescriptorSets(
vk::WriteDescriptorSet{
.dstSet = descriptor_set,
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info,
},
{});
}
// Create renderpass
vk::AttachmentReference color_ref{
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::AttachmentDescription attachment{
.format = format,
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eDontCare,
.storeOp = vk::AttachmentStoreOp::eStore,
.initialLayout = vk::ImageLayout::eColorAttachmentOptimal,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::SubpassDescription subpass{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
};
subpass.setColorAttachments(color_ref);
vk::StructureChain renderpass_info{
vk::RenderPassCreateInfo{
.attachmentCount = 1,
.pAttachments = &attachment,
.subpassCount = 1,
.pSubpasses = &subpass,
},
};
renderpass = vk::raii::RenderPass(device, renderpass_info.get());
// Vertex shader
vk::raii::ShaderModule vertex_shader = load_shader(device, "reprojection.vert");
// Fragment shader
std::string fragment_shader_name = "reprojection.frag";
vk::SpecializationInfo fragment_specialization_info;
SgsrSpecializationConstants fragment_specialization_constants;
std::vector<vk::SpecializationMapEntry> fragment_specialization_constants_desc;
const configuration::sgsr_settings sgsr = application::get_config().sgsr;
if (sgsr.enabled)
{
fragment_shader_name = "reprojection_sgsr.frag";
fragment_specialization_constants = {
.use_edge_direction = sgsr.use_edge_direction,
.edge_threshold = float(sgsr.edge_threshold / 255.0),
.edge_sharpness = sgsr.edge_sharpness,
};
fragment_specialization_constants_desc = {
vk::SpecializationMapEntry{
.constantID = 0,
.offset = offsetof(SgsrSpecializationConstants, use_edge_direction),
.size = sizeof(fragment_specialization_constants.use_edge_direction),
},
vk::SpecializationMapEntry{
.constantID = 1,
.offset = offsetof(SgsrSpecializationConstants, edge_threshold),
.size = sizeof(fragment_specialization_constants.edge_threshold),
},
vk::SpecializationMapEntry{
.constantID = 2,
.offset = offsetof(SgsrSpecializationConstants, edge_sharpness),
.size = sizeof(fragment_specialization_constants.edge_sharpness),
},
};
fragment_specialization_info.setMapEntries(fragment_specialization_constants_desc);
fragment_specialization_info.setDataSize(sizeof(fragment_specialization_constants));
fragment_specialization_info.setPData(&fragment_specialization_constants);
}
vk::raii::ShaderModule fragment_shader = load_shader(device, fragment_shader_name);
// Create graphics pipeline
vk::PipelineLayoutCreateInfo pipeline_layout_info;
pipeline_layout_info.setSetLayouts(*descriptor_set_layout);
layout = vk::raii::PipelineLayout(device, pipeline_layout_info);
vk::pipeline_builder pipeline_info{
.flags = {},
.Stages = {
{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.pName = "main",
},
{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.pName = "main",
.pSpecializationInfo = &fragment_specialization_info,
},
},
.VertexBindingDescriptions = {
{
.binding = 0,
.stride = sizeof(vertex),
.inputRate = vk::VertexInputRate::eVertex,
},
},
.VertexAttributeDescriptions = {
{
.location = 0,
.binding = 0,
.format = vk::Format::eR32G32Sfloat,
.offset = offsetof(vertex, position),
},
{
.location = 1,
.binding = 0,
.format = vk::Format::eR32G32Sfloat,
.offset = offsetof(vertex, uv),
},
},
.InputAssemblyState = {{
.topology = vk::PrimitiveTopology::eTriangleStrip,
}},
.Viewports = {{
.x = 0,
.y = 0,
.width = (float)output_extent.width,
.height = (float)output_extent.height,
.minDepth = 0,
.maxDepth = 1,
}},
.Scissors = {{
.offset = {.x = 0, .y = 0},
.extent = output_extent,
}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
}},
.MultisampleState = {{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
}},
.ColorBlendState = {.flags = {}},
.ColorBlendAttachments = {{
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA,
}},
.layout = *layout,
.renderPass = *renderpass,
.subpass = 0,
};
pipeline = vk::raii::Pipeline(device, application::get_pipeline_cache(), pipeline_info);
// Create image views and framebuffers
output_image_views.reserve(output_images.size() * view_count);
framebuffers.reserve(output_images.size() * view_count);
for (vk::Image image: output_images)
{
for (uint32_t view = 0; view < view_count; ++view)
{
vk::ImageViewCreateInfo iv_info{
.image = image,
.viewType = vk::ImageViewType::e2DArray,
.format = format,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = view,
.layerCount = 1,
},
};
output_image_views.emplace_back(device, iv_info);
vk::FramebufferCreateInfo fb_create_info{
.renderPass = *renderpass,
.width = output_extent.width,
.height = output_extent.height,
.layers = 1,
};
fb_create_info.setAttachments(*output_image_views.back());
framebuffers.emplace_back(device, fb_create_info);
}
}
}
static size_t required_vertices(const wivrn::to_headset::foveation_parameter & p)
{
// strips are constructed like this:
// 0 2 4
// 1 3 5 5*
// there is one such line per value in y
// the last element is repeated to break the line
return (2 * (p.x.size() + 1) + 1) * p.y.size();
}
std::vector<XrExtent2Di> stream_reprojection::reproject(vk::raii::CommandBuffer & command_buffer,
const std::array<wivrn::to_headset::foveation_parameter, 2> & foveation,
int destination)
{
if (destination < 0 || destination >= (int)output_images.size())
throw std::runtime_error("Invalid destination image index");
ensure_vertices(std::max(required_vertices(foveation[0]), required_vertices(foveation[1])));
std::vector<XrExtent2Di> out_extents(view_count, XrExtent2Di{});
for (size_t view = 0; view < view_count; ++view)
{
auto vertices = get_vertices(view);
const auto & [px, py] = foveation[view];
assert(px.size() % 2 == 1);
assert(py.size() % 2 == 1);
const int n_ratio_y = (py.size() - 1) / 2;
const int n_ratio_x = (px.size() - 1) / 2;
for (auto [ix, n_out_x]: utils::enumerate_range(px))
{
// number of output pixels per source pixels
const int ratio_x = std::abs(n_ratio_x - int(ix)) + 1;
out_extents[view].width += ratio_x * n_out_x;
}
glm::vec2 in(0), out(0); // pixel coordinates
glm::vec2 in_pixel_size(1. / input_extent.width,
1. / input_extent.height);
glm::vec2 out_pixel_size(2. / output_extent.width,
2. / output_extent.height);
for (auto [iy, n_out_y]: utils::enumerate_range(py))
{
// number of output pixels per source pixels
const int ratio_y = std::abs(n_ratio_y - int(iy)) + 1;
out_extents[view].height += ratio_y * n_out_y;
in.x = 0;
out.x = 0;
for (auto [ix, n_out_x]: utils::enumerate_range(px))
{
const int ratio_x = std::abs(n_ratio_x - int(ix)) + 1;
*vertices++ = {
.position = out * out_pixel_size - glm::vec2(1),
.uv = in * in_pixel_size,
};
*vertices++ = {
.position = (out + glm::vec2(0, n_out_y * ratio_y)) * out_pixel_size - glm::vec2(1),
.uv = (in + glm::vec2(0, n_out_y)) * in_pixel_size,
};
in.x += n_out_x;
out.x += n_out_x * ratio_x;
}
*vertices++ = {
.position = out * out_pixel_size - glm::vec2(1),
.uv = in * in_pixel_size,
};
*vertices++ = {
.position = (out + glm::vec2(0, n_out_y * ratio_y)) * out_pixel_size - glm::vec2(1),
.uv = (in + glm::vec2(0, n_out_y)) * in_pixel_size,
};
*vertices++ = {
.position = (out + glm::vec2(0, n_out_y * ratio_y)) * out_pixel_size - glm::vec2(1),
.uv = (in + glm::vec2(0, n_out_y)) * in_pixel_size,
};
in.y += n_out_y;
out.y += n_out_y * ratio_y;
}
}
command_buffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTopOfPipe,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
{},
{},
{},
vk::ImageMemoryBarrier{
.srcAccessMask = {},
.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eColorAttachmentOptimal,
.image = output_images[destination],
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.levelCount = 1,
.layerCount = view_count,
},
});
for (size_t view = 0; view < view_count; ++view)
{
vk::RenderPassBeginInfo begin_info{
.renderPass = *renderpass,
.framebuffer = *framebuffers[destination * view_count + view],
.renderArea = {
.offset = {0, 0},
.extent = output_extent,
},
};
command_buffer.beginRenderPass(begin_info, vk::SubpassContents::eInline);
command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *pipeline);
command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *layout, 0, descriptor_sets[view], {});
command_buffer.bindVertexBuffers(0, vk::Buffer(buffer), vertices_size * view);
command_buffer.draw(required_vertices(foveation[view]), 1, 0, 0);
command_buffer.endRenderPass();
}
return out_extents;
}
-339
View File
@@ -1,339 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 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/>.
*/
#define IMGUI_DEFINE_MATH_OPERATORS
#include "stream.h"
#include "application.h"
#include "imgui_internal.h"
#include "implot.h"
#include "utils/i18n.h"
#include "utils/ranges.h"
#include <cmath>
#include <limits>
#include <ranges>
#include <spdlog/spdlog.h>
namespace
{
float compute_plot_max_value(float * data, int count, ptrdiff_t stride)
{
float max = 0;
uintptr_t ptr = (uintptr_t)data;
for (int i = 0; i < count; i++)
{
max = std::max(max, *(float *)(ptr + i * stride));
}
// First power of 10 less than the max
float x = pow(10, floor(log10(max)));
return ceil(max / x) * x;
}
std::pair<float, std::string> compute_plot_unit(float max_value)
{
if (max_value > 1e9)
return {1e-9, "G"};
if (max_value > 1e6)
return {1e-6, "M"};
if (max_value > 1e3)
return {1e-3, "k"};
if (max_value > 1)
return {1, ""};
if (max_value > 1e-3)
return {1e3, "m"};
if (max_value > 1e-6)
return {1e6, "u"};
return {1e9, "n"};
}
struct getter_data
{
uintptr_t data;
int stride;
float multiplier;
};
ImPlotPoint getter(int index, void * data_)
{
getter_data & data = *(getter_data *)data_;
return ImPlotPoint(index, *(float *)(data.data + index * data.stride) * data.multiplier);
}
} // namespace
void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std::vector<std::shared_ptr<shard_accumulator::blit_handle>> & blit_handles, const gpu_timestamps & timestamps)
{
uint64_t rx = network_session->bytes_received();
uint64_t tx = network_session->bytes_sent();
float dt = (predicted_display_time - last_metric_time) * 1e-9f;
bandwidth_rx = 0.8 * bandwidth_rx + 0.2 * float(rx - bytes_received) / dt;
bandwidth_tx = 0.8 * bandwidth_tx + 0.2 * float(tx - bytes_sent) / dt;
last_metric_time = predicted_display_time;
bytes_received = rx;
bytes_sent = tx;
*(gpu_timestamps *)&global_metrics[metrics_offset] = timestamps;
global_metrics[metrics_offset].cpu_time = application::get_cpu_time().count() * 1e-9f;
global_metrics[metrics_offset].bandwidth_rx = bandwidth_rx * 8;
global_metrics[metrics_offset].bandwidth_tx = bandwidth_tx * 8;
std::vector<shard_accumulator::blit_handle *> active_handles;
active_handles.reserve(blit_handles.size());
for (const auto & h: blit_handles)
{
if (h)
active_handles.push_back(h.get());
}
if (decoder_metrics.size() != active_handles.size())
decoder_metrics.resize(active_handles.size());
auto min_encode_begin = std::numeric_limits<decltype(active_handles[0]->feedback.encode_begin)>::max();
for (const auto & bh: active_handles)
{
if (bh)
min_encode_begin = std::min(min_encode_begin, bh->feedback.encode_begin);
}
for (auto && [metrics, bh]: std::views::zip(decoder_metrics, active_handles))
{
if (metrics.size() != global_metrics.size())
metrics.resize(global_metrics.size());
if (not bh)
continue;
// clang-format off
metrics[metrics_offset] = bh ? decoder_metric{
.encode_begin = (bh->feedback.encode_begin - min_encode_begin) * 1e-9f,
.encode_end = (bh->feedback.encode_end - min_encode_begin) * 1e-9f,
.send_begin = (bh->feedback.send_begin - min_encode_begin) * 1e-9f,
.send_end = (bh->feedback.send_end - min_encode_begin) * 1e-9f,
.received_first_packet = (bh->feedback.received_first_packet - min_encode_begin) * 1e-9f,
.received_last_packet = (bh->feedback.received_last_packet - min_encode_begin) * 1e-9f,
.sent_to_decoder = (bh->feedback.sent_to_decoder - min_encode_begin) * 1e-9f,
.received_from_decoder = (bh->feedback.received_from_decoder - min_encode_begin) * 1e-9f,
.blitted = (bh->feedback.blitted - min_encode_begin) * 1e-9f,
.displayed = (bh->feedback.displayed - min_encode_begin) * 1e-9f,
.predicted_display = (bh->view_info.display_time - min_encode_begin) * 1e-9f,
}: decoder_metric{};
// clang-format on
}
metrics_offset = (metrics_offset + 1) % global_metrics.size();
}
std::vector<XrCompositionLayerQuad> scenes::stream::plot_performance_metrics(XrTime predicted_display_time)
{
imgui_ctx->new_frame(predicted_display_time);
const ImGuiStyle & style = ImGui::GetStyle();
ImGui::SetNextWindowPos({0, 0});
ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size);
ImGui::Begin("Performance metrics", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
ImVec2 window_size = ImGui::GetWindowSize() - ImVec2(2, 2) * style.WindowPadding;
static const std::array plots = {
// clang-format off
plot(_("CPU time"), {{"", &global_metric::cpu_time}}, "s"),
plot(_("GPU time"), {{_("Reproject"), &global_metric::gpu_time},
{_("Blit"), &global_metric::gpu_barrier}}, "s"),
plot(_("Network"), {{_("Download"), &global_metric::bandwidth_rx},
{_("Upload"), &global_metric::bandwidth_tx}}, "bit/s"),
// clang-format on
};
int n_plots = plots.size() + decoder_metrics.size();
axis_scale.resize(n_plots);
int n_cols = 2;
int n_rows = ceil((float)n_plots / n_cols);
ImVec2 plot_size = ImVec2(
window_size.x / n_cols - style.ItemSpacing.x * (n_cols - 1) / n_cols,
(window_size.y - ImGui::GetCurrentContext()->FontSize - style.ItemSpacing.y) / n_rows - style.ItemSpacing.y * (n_rows - 1) / n_rows);
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));
ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, IM_COL32(0, 0, 0, 0));
int n = 0;
for (const auto & [title, subplots, unit]: plots)
{
if (ImPlot::BeginPlot(title.c_str(), plot_size, ImPlotFlags_NoTitle | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMouseText | ImPlotFlags_NoChild))
{
float min_v = 0;
float max_v = 0;
for (const auto & [subtitle, data]: subplots)
{
max_v = std::max(max_v, compute_plot_max_value(&(global_metrics.data()->*data), global_metrics.size(), sizeof(global_metric)));
}
auto [multiplier, prefix] = compute_plot_unit(max_v);
if (axis_scale[n] == 0 || std::isnan(axis_scale[n]))
axis_scale[n] = max_v;
else
axis_scale[n] = 0.99 * axis_scale[n] + 0.01 * max_v;
auto color = ImPlot::GetColormapColor(n);
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);
ImPlot::SetNextLineStyle(color);
ImPlot::SetNextFillStyle(color, 0.25);
for (const auto & [subtitle, data]: subplots)
{
getter_data gdata{
.data = (uintptr_t) & (global_metrics.data()->*data),
.stride = sizeof(global_metric),
.multiplier = multiplier,
};
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};
ImPlot::SetNextLineStyle(ImVec4(1, 1, 1, 1));
ImPlot::PlotLine("", x, y, 2);
}
ImPlot::EndPlot();
}
if (++n % n_cols != 0)
ImGui::SameLine();
}
for (auto && [index, metrics]: utils::enumerate(decoder_metrics))
{
std::string title = fmt::format(_F("Decoder {}"), std::to_string(index));
if (ImPlot::BeginPlot(title.c_str(), plot_size, ImPlotFlags_NoTitle | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMouseText | ImPlotFlags_NoChild))
{
float min_v = 0;
float max_v = compute_plot_max_value(&(metrics.data()->displayed), metrics.size(), sizeof(decoder_metric));
// auto [ multiplier, prefix ] = compute_plot_unit(max_v);
if (axis_scale[n] == 0)
axis_scale[n] = max_v;
else
axis_scale[n] = 0.99 * axis_scale[n] + 0.01 * max_v;
std::string title_with_units = _("Timings [ms]");
ImPlot::SetupAxes(nullptr, title_with_units.c_str(), ImPlotAxisFlags_NoDecorations, 0);
ImPlot::SetupAxesLimits(0, metrics.size() - 1, min_v * 1e3f, axis_scale[n] * 1e3f, ImGuiCond_Always);
getter_data getter_encode_begin{
.data = (uintptr_t) & (metrics.data()->encode_begin),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_encode_end{
.data = (uintptr_t) & (metrics.data()->encode_end),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_send_begin{
.data = (uintptr_t) & (metrics.data()->send_begin),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_send_end{
.data = (uintptr_t) & (metrics.data()->send_end),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_received_first_packet{
.data = (uintptr_t) & (metrics.data()->received_first_packet),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_received_last_packet{
.data = (uintptr_t) & (metrics.data()->received_last_packet),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_sent_to_decoder{
.data = (uintptr_t) & (metrics.data()->sent_to_decoder),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_received_from_decoder{
.data = (uintptr_t) & (metrics.data()->received_from_decoder),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_blitted{
.data = (uintptr_t) & (metrics.data()->blitted),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_displayed{
.data = (uintptr_t) & (metrics.data()->displayed),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
getter_data getter_predicted{
.data = (uintptr_t) & (metrics.data()->predicted_display),
.stride = sizeof(decoder_metric),
.multiplier = 1e3f};
// clang-format off
ImPlot::PlotShadedG(_S("Encode"), getter, &getter_encode_begin, getter, &getter_encode_end, metrics.size());
ImPlot::PlotShadedG(_S("Send"), getter, &getter_send_begin, getter, &getter_send_end, metrics.size());
ImPlot::PlotShadedG(_S("Receive"), getter, &getter_received_first_packet, getter, &getter_received_last_packet, metrics.size());
ImPlot::PlotShadedG(_S("Decode"), getter, &getter_sent_to_decoder, getter, &getter_received_from_decoder, metrics.size());
ImPlot::PlotLineG(_S("Blitted"), getter, &getter_blitted, metrics.size());
ImPlot::PlotLineG(_S("Displayed"), getter, &getter_displayed, metrics.size());
ImPlot::PlotLineG(_S("Predicted"), getter, &getter_predicted, metrics.size());
// clang-format on
double x[] = {double(metrics_offset), double(metrics_offset)};
double y[] = {0, 1e9};
ImPlot::SetNextLineStyle(ImVec4(1, 1, 1, 1));
ImPlot::PlotLine("", x, y, 2);
ImPlot::EndPlot();
}
if (++n % n_cols != 0)
ImGui::SameLine();
}
ImPlot::PopStyleColor(5);
{
std::lock_guard lock(tracking_control_mutex);
ImGui::Text("%s", fmt::format(_F("Estimated motion to photons latency: {}ms"), std::chrono::duration_cast<std::chrono::milliseconds>(tracking_control.max_offset).count()).c_str());
}
ImGui::End();
std::vector<XrCompositionLayerQuad> layers;
for (auto & layer: imgui_ctx->end_frame())
layers.push_back(layer.second);
return layers;
}
+370 -219
View File
@@ -19,7 +19,13 @@
#include "application.h"
#include "stream.h"
#include "utils/overloaded.h"
#include "wivrn_packets.h"
#include "xr/body_tracker.h"
#include "xr/face_tracker.h"
#include "xr/fb_body_tracker.h"
#include "xr/to_string.h"
#include <magic_enum.hpp>
#include <ranges>
#include <spdlog/spdlog.h>
#include <thread>
@@ -33,46 +39,28 @@ using tid = to_headset::tracking_control::id;
static const XrDuration min_tracking_period = 2'000'000;
static const XrDuration max_tracking_period = 5'000'000;
static from_headset::tracking::pose locate_space(device_id device, XrSpace space, XrSpace reference, XrTime time)
static uint8_t cast_flags(XrSpaceLocationFlags location, XrSpaceVelocityFlags velocity)
{
XrSpaceVelocity velocity{
.type = XR_TYPE_SPACE_VELOCITY,
};
uint8_t flags = 0;
if (location & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
flags |= from_headset::tracking::orientation_valid;
XrSpaceLocation location{
.type = XR_TYPE_SPACE_LOCATION,
.next = &velocity,
};
if (location & XR_SPACE_LOCATION_POSITION_VALID_BIT)
flags |= from_headset::tracking::position_valid;
xrLocateSpace(space, reference, time, &location);
if (velocity & XR_SPACE_VELOCITY_LINEAR_VALID_BIT)
flags |= from_headset::tracking::linear_velocity_valid;
from_headset::tracking::pose res{
.pose = location.pose,
.linear_velocity = velocity.linearVelocity,
.angular_velocity = velocity.angularVelocity,
.device = device,
.flags = 0,
};
if (velocity & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT)
flags |= from_headset::tracking::angular_velocity_valid;
if (location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
res.flags |= from_headset::tracking::orientation_valid;
if (location & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)
flags |= from_headset::tracking::orientation_tracked;
if (location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT)
res.flags |= from_headset::tracking::position_valid;
if (location & XR_SPACE_LOCATION_POSITION_TRACKED_BIT)
flags |= from_headset::tracking::position_tracked;
if (velocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT)
res.flags |= from_headset::tracking::linear_velocity_valid;
if (velocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT)
res.flags |= from_headset::tracking::angular_velocity_valid;
if (location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)
res.flags |= from_headset::tracking::orientation_tracked;
if (location.locationFlags & XR_SPACE_LOCATION_POSITION_TRACKED_BIT)
res.flags |= from_headset::tracking::position_tracked;
return res;
return flags;
}
namespace
@@ -90,6 +78,123 @@ public:
return instance.now() - start;
}
};
from_headset::tracking::pose locate_space(device_id device, XrSpace space, XrSpace reference, XrTime time)
{
XrSpaceVelocity velocity{
.type = XR_TYPE_SPACE_VELOCITY,
};
XrSpaceLocation location{
.type = XR_TYPE_SPACE_LOCATION,
.next = &velocity,
};
auto res = xrLocateSpace(space, reference, time, &location);
if (XR_SUCCEEDED(res))
return {
.pose = location.pose,
.linear_velocity = velocity.linearVelocity,
.angular_velocity = velocity.angularVelocity,
.device = device,
.flags = cast_flags(location.locationFlags, velocity.velocityFlags),
};
spdlog::warn("xrLocateSpace failed for {}: {}", magic_enum::enum_name(device), xr::to_string(res));
return {};
}
class locate_spaces_functor
{
std::vector<XrSpaceLocationData> locations;
std::vector<XrSpaceVelocityData> velocities;
std::vector<wivrn::device_id> devices;
std::vector<XrSpace> spaces;
XrSpace reference;
PFN_xrLocateSpaces locate_spaces = nullptr;
public:
locate_spaces_functor(xr::instance & instance, XrSpace reference) :
reference(reference)
{
try
{
if (instance.get_api_version() >= XR_MAKE_VERSION(1, 1, 0))
locate_spaces = instance.get_proc<PFN_xrLocateSpaces>("xrLocateSpaces");
else
locate_spaces = instance.get_proc<PFN_xrLocateSpacesKHR>("xrLocateSpacesKHR");
}
catch (std::exception & e)
{
spdlog::warn("Failed to load xrLocateSpaces function, fallback to xrLocateSpace");
}
}
void add_space(wivrn::device_id device, XrSpace space, XrTime t, std::vector<from_headset::tracking::pose> & out)
{
if (locate_spaces)
{
// store, will be located later
devices.push_back(device);
spaces.push_back(space);
}
else
out.push_back(locate_space(device, space, reference, t));
}
void resolve(
xr::session & session,
XrTime t,
std::vector<from_headset::tracking::pose> & out)
{
assert(devices.size() == spaces.size());
if (locate_spaces)
{
locations.resize(spaces.size());
velocities.resize(spaces.size());
XrSpaceVelocities spc_velocities{
.type = XR_TYPE_SPACE_VELOCITIES,
.velocityCount = uint32_t(velocities.size()),
.velocities = velocities.data(),
};
XrSpaceLocations spc_locations{
.type = XR_TYPE_SPACE_LOCATIONS,
.next = &spc_velocities,
.locationCount = uint32_t(locations.size()),
.locations = locations.data(),
};
XrSpacesLocateInfo info{
.type = XR_TYPE_SPACES_LOCATE_INFO,
.baseSpace = reference,
.time = t,
.spaceCount = uint32_t(spaces.size()),
.spaces = spaces.data(),
};
auto res = locate_spaces(session, &info, &spc_locations);
if (XR_SUCCEEDED(res))
{
for (size_t i = 0; i < devices.size(); ++i)
{
const auto & location = locations[i];
const auto & velocity = velocities[i];
out.push_back({
.pose = location.pose,
.linear_velocity = velocity.linearVelocity,
.angular_velocity = velocity.angularVelocity,
.device = devices[i],
.flags = cast_flags(location.locationFlags, velocity.velocityFlags),
});
}
}
else
spdlog::warn("xrLocateSpaces failed: {}", xr::to_string(res));
devices.clear();
spaces.clear();
}
}
};
} // namespace
static std::optional<std::array<from_headset::hand_tracking::pose, XR_HAND_JOINT_COUNT_EXT>> locate_hands(xr::hand_tracker & hand, XrSpace space, XrTime time)
@@ -133,31 +238,6 @@ static std::optional<std::array<from_headset::hand_tracking::pose, XR_HAND_JOINT
return std::nullopt;
}
static bool enabled(const to_headset::tracking_control & control, device_id id)
{
switch (id)
{
case device_id::HEAD:
case device_id::EYE_GAZE:
return true;
case device_id::LEFT_AIM:
return control.enabled[size_t(tid::left_aim)];
case device_id::LEFT_GRIP:
return control.enabled[size_t(tid::left_grip)];
case device_id::LEFT_PALM:
return control.enabled[size_t(tid::left_palm)];
case device_id::RIGHT_AIM:
return control.enabled[size_t(tid::right_aim)];
case device_id::RIGHT_GRIP:
return control.enabled[size_t(tid::right_grip)];
case device_id::RIGHT_PALM:
return control.enabled[size_t(tid::right_palm)];
default:
break;
}
__builtin_unreachable();
}
template <typename T>
static T & from_pool(std::vector<T> & container, std::vector<T> & pool)
{
@@ -182,12 +262,20 @@ static xr::spaces device_to_space(device_id id)
return xr::spaces::grip_left;
case device_id::LEFT_PALM:
return xr::spaces::palm_left;
case device_id::LEFT_PINCH_POSE:
return xr::spaces::pinch_left;
case device_id::LEFT_POKE:
return xr::spaces::poke_left;
case device_id::RIGHT_AIM:
return xr::spaces::aim_right;
case device_id::RIGHT_GRIP:
return xr::spaces::grip_right;
case device_id::RIGHT_PALM:
return xr::spaces::palm_right;
case device_id::RIGHT_PINCH_POSE:
return xr::spaces::pinch_right;
case device_id::RIGHT_POKE:
return xr::spaces::poke_right;
default:
assert(false);
__builtin_unreachable();
@@ -205,20 +293,76 @@ void scenes::stream::tracking()
#endif
std::vector<std::pair<device_id, XrSpace>> spaces;
for (auto id: {
device_id::HEAD,
device_id::LEFT_AIM,
device_id::LEFT_GRIP,
device_id::LEFT_PALM,
device_id::RIGHT_AIM,
device_id::RIGHT_GRIP,
device_id::RIGHT_PALM,
})
{
if (XrSpace space = application::space(device_to_space(id)))
spaces.emplace_back(id, space);
std::vector ids{
device_id::HEAD,
device_id::LEFT_AIM,
device_id::LEFT_GRIP,
device_id::LEFT_PALM,
device_id::RIGHT_AIM,
device_id::RIGHT_GRIP,
device_id::RIGHT_PALM,
};
if (instance.has_extension("XR_EXT_hand_interaction"))
{
spdlog::info("Adding hand_interaction poses to device list");
ids.insert(ids.end(), {device_id::LEFT_PINCH_POSE, device_id::LEFT_POKE, device_id::RIGHT_PINCH_POSE, device_id::RIGHT_POKE});
}
for (auto id: ids)
{
if (XrSpace space = application::space(device_to_space(id)))
spaces.emplace_back(id, space);
else
spdlog::warn("Missing space for device {}", magic_enum::enum_name(id));
}
}
auto enabled = [&](const to_headset::tracking_control & control, device_id id) -> bool {
if (is_gui_interactable())
{
switch (id)
{
case device_id::HEAD:
case device_id::EYE_GAZE:
return true;
default:
return false;
}
}
switch (id)
{
case device_id::HEAD:
case device_id::EYE_GAZE:
return true;
case device_id::LEFT_AIM:
return control.enabled[size_t(tid::left_aim)];
case device_id::LEFT_GRIP:
return control.enabled[size_t(tid::left_grip)];
case device_id::LEFT_PALM:
return control.enabled[size_t(tid::left_palm)];
case device_id::LEFT_PINCH_POSE:
return control.enabled[size_t(tid::left_pinch)];
case device_id::LEFT_POKE:
return control.enabled[size_t(tid::left_poke)];
case device_id::RIGHT_AIM:
return control.enabled[size_t(tid::right_aim)];
case device_id::RIGHT_GRIP:
return control.enabled[size_t(tid::right_grip)];
case device_id::RIGHT_PALM:
return control.enabled[size_t(tid::right_palm)];
case device_id::RIGHT_PINCH_POSE:
return control.enabled[size_t(tid::right_pinch)];
case device_id::RIGHT_POKE:
return control.enabled[size_t(tid::right_poke)];
default:
break;
}
throw std::runtime_error("enabled called on unhandled device " + std::string(magic_enum::enum_name(id)));
};
const auto & config = application::get_config();
if (config.check_feature(feature::eye_gaze))
@@ -243,44 +387,16 @@ void scenes::stream::tracking()
std::vector<serialization_packet> packets;
const bool hand_tracking = config.check_feature(feature::hand_tracking);
from_headset::face_type face_tracking = from_headset::face_type::none;
if (config.check_feature(feature::face_tracking))
{
if (application::get_fb_face_tracking2_supported())
face_tracking = from_headset::face_type::fb2;
else if (application::get_htc_face_tracking_eye_supported() or application::get_htc_face_tracking_lip_supported())
face_tracking = from_headset::face_type::htc;
else if (application::get_pico_face_tracking_supported())
{
face_tracking = from_headset::face_type::pico;
// We can't start the face tracking on application initialisation like we do for
// other face trackers due to a Pico runtime bug where face tracking freezes when
// the headset is taken off or the application is quit.
application::get_pico_face_tracker().start();
}
}
std::optional<xr::hand_tracker> left_hand;
std::optional<xr::hand_tracker> right_hand;
enum
{
body_none,
body_fb,
body_pico,
} body_tracking = body_none;
const bool face_tracking = config.check_feature(feature::face_tracking);
xr::face_tracker face_tracker;
if (config.check_feature(feature::body_tracking))
{
if (application::get_fb_body_tracking_supported())
{
body_tracking = body_fb;
// TODO maybe handle reconnection better, if the settings are changed since
// last connection to running server, the tracker count will mismatch and
// stuff might break
application::get_fb_body_tracker().stop();
application::get_fb_body_tracker().start(config.fb_lower_body, config.fb_hip);
}
else if (application::get_pico_body_tracking_supported())
body_tracking = body_pico;
}
const bool body_tracking = config.check_feature(feature::body_tracking);
xr::body_tracker body_tracker;
locate_spaces_functor locate_spaces{instance, world_space};
on_interaction_profile_changed({});
@@ -302,11 +418,50 @@ void scenes::stream::tracking()
timer t(instance);
int samples = 0;
to_headset::tracking_control control;
auto control = *tracking_control.lock();
bool interaction_profile_changed = this->interaction_profile_changed.exchange(false);
if (control.enabled[size_t(tid::left_hand)])
{
std::lock_guard lock(tracking_control_mutex);
control = tracking_control;
if (not left_hand and system.hand_tracking_supported())
left_hand = session.create_hand_tracker(XR_HAND_LEFT_EXT);
}
else
left_hand.reset();
if (control.enabled[size_t(tid::right_hand)])
{
if (not right_hand and system.hand_tracking_supported())
right_hand = session.create_hand_tracker(XR_HAND_RIGHT_EXT);
}
else
right_hand.reset();
if (face_tracking and control.enabled[size_t(tid::face)])
{
if (std::holds_alternative<std::monostate>(face_tracker))
face_tracker = xr::make_face_tracker(instance, system, session);
}
else
face_tracker.emplace<std::monostate>();
if (body_tracking and control.enabled[size_t(tid::generic_tracker)])
{
if (std::holds_alternative<std::monostate>(body_tracker))
body_tracker = xr::make_body_tracker(
instance,
system,
session,
application::get_generic_trackers(),
config.fb_lower_body,
config.fb_hip);
}
else
body_tracker.emplace<std::monostate>();
if (interaction_profile_changed)
if (auto htc = std::get_if<xr::htc_body_tracker>(&body_tracker))
htc->update_active();
XrDuration prediction = std::clamp<XrDuration>(control.max_offset.count(), 0, 80'000'000);
auto period = std::max<XrDuration>(display_time_period.load(), 1'000'000);
@@ -333,81 +488,67 @@ void scenes::stream::tracking()
if (recenter_requested.exchange(false))
packet.state_flags = wivrn::from_headset::tracking::recentered;
packet.device_poses.clear();
for (auto [device, space]: spaces)
{
if (enabled(control, device))
packet.device_poses.emplace_back(locate_space(device, space, world_space, t0 + Δt));
}
// Hand tracking data are very large, send fewer samples than other items
if (hand_tracking and t0 >= last_hand_sample + period and
(Δt == 0 or Δt >= prediction - 2 * period))
{
last_hand_sample = t0;
if (control.enabled[size_t(tid::left_hand)])
if (left_hand)
{
auto joints = locate_hands(*left_hand, world_space, t0 + Δt);
hands.emplace_back(
t0,
t0 + Δt,
from_headset::hand_tracking::left,
locate_hands(application::get_left_hand(), world_space, t0 + Δt));
joints);
}
if (control.enabled[size_t(tid::right_hand)])
if (right_hand)
{
auto joints = locate_hands(*right_hand, world_space, t0 + Δt);
hands.emplace_back(
t0,
t0 + Δt,
from_headset::hand_tracking::right,
locate_hands(application::get_right_hand(), world_space, t0 + Δt));
}
if (body_tracking != body_none and t0 >= last_body_sample + period and
(Δt == 0 or Δt >= prediction - 2 * period))
{
last_body_sample = t0;
if (control.enabled[size_t(tid::generic_tracker)])
{
auto & body_packet = body.emplace_back(from_headset::body_tracking{
.production_timestamp = t0,
.timestamp = t0 + Δt,
});
switch (body_tracking)
{
case body_none:
__builtin_unreachable();
case body_fb:
body_packet.poses = application::get_fb_body_tracker().locate_spaces(t0 + Δt, world_space);
break;
case body_pico:
body_packet.poses = application::get_pico_body_tracker().locate_spaces(t0 + Δt, world_space);
break;
}
joints);
}
}
if (control.enabled[size_t(tid::face)])
packet.device_poses.clear();
for (auto [device, space]: spaces)
{
switch (face_tracking)
{
case wivrn::from_headset::face_type::none:
break;
case wivrn::from_headset::face_type::fb2:
application::get_fb_face_tracker2().get_weights(t0 + Δt, packet.face.emplace<wivrn::from_headset::tracking::fb_face2>());
break;
case wivrn::from_headset::face_type::htc: {
auto & face_htc = packet.face.emplace<wivrn::from_headset::tracking::htc_face>();
face_htc.eye_active = false;
face_htc.lip_active = false;
if (application::get_htc_face_tracking_eye_supported())
application::get_htc_face_tracker_eye().get_weights(t0 + Δt, face_htc);
if (application::get_htc_face_tracking_lip_supported())
application::get_htc_face_tracker_lip().get_weights(t0 + Δt, face_htc);
break;
}
case wivrn::from_headset::face_type::pico:
application::get_pico_face_tracker().get_weights(t0 + Δt, packet.face.emplace<wivrn::from_headset::tracking::fb_face2>());
break;
}
if (enabled(control, device))
locate_spaces.add_space(device, space, t0 + Δt, packet.device_poses);
}
locate_spaces.resolve(session, t0 + Δt, packet.device_poses);
std::visit(utils::overloaded{
[](std::monostate &) {},
[&](auto & b) {
if (t0 >= last_body_sample + period and
(Δt == 0 or Δt >= prediction - 2 * period))
{
last_body_sample = t0;
if (control.enabled[size_t(tid::generic_tracker)])
{
body.push_back(from_headset::body_tracking{
.production_timestamp = t0,
.timestamp = t0 + Δt,
.poses = b.locate_spaces(t0 + Δt, world_space),
});
}
}
},
},
body_tracker);
std::visit(utils::overloaded{
[](std::monostate &) {},
[&](auto & ft) {
ft.get_weights(t0 + Δt, packet.face.emplace<typename std::remove_reference_t<decltype(ft)>::packet_type>());
},
},
face_tracker);
}
catch (const std::system_error & e)
{
@@ -508,20 +649,17 @@ void scenes::stream::tracking()
exit();
}
}
if (face_tracking == from_headset::face_type::pico)
application::get_pico_face_tracker().stop();
}
void scenes::stream::operator()(to_headset::tracking_control && packet)
{
std::lock_guard lock(tracking_control_mutex);
auto locked = tracking_control.lock();
auto m = size_t(to_headset::tracking_control::id::microphone);
if (audio_handle)
audio_handle->set_mic_sate(packet.enabled[m]);
audio_handle->set_mic_state(packet.enabled[m]);
tracking_control = packet;
tracking_control.min_offset = std::min(tracking_control.min_offset, tracking_control.max_offset);
*locked = packet;
locked->min_offset = std::min(locked->min_offset, locked->max_offset);
}
static device_id derived_from(device_id target)
@@ -542,6 +680,56 @@ static device_id derived_from(device_id target)
void scenes::stream::on_interaction_profile_changed(const XrEventDataInteractionProfileChanged &)
{
interaction_profile_changed = true;
std::array path = {
"/user/hand/left",
"/user/hand/right",
};
#define DO_PROFILE(vendor, name) \
if (profile == "/interaction_profiles/" #vendor "/" #name) \
{ \
interaction_profiles[i] = interaction_profile::vendor##_##name; \
continue; \
}
for (size_t i = 0; i < 2; ++i)
{
try
{
auto profile = session.get_current_interaction_profile(path[i]);
spdlog::info("interaction profile for {}: {}", path[i], profile);
DO_PROFILE(khr, simple_controller)
DO_PROFILE(ext, hand_interaction_ext)
DO_PROFILE(bytedance, pico_neo3_controller)
DO_PROFILE(bytedance, pico4_controller)
DO_PROFILE(bytedance, pico4s_controller)
DO_PROFILE(bytedance, pico_g3_controller)
DO_PROFILE(google, daydream_controller)
DO_PROFILE(hp, mixed_reality_controller)
DO_PROFILE(htc, vive_controller)
DO_PROFILE(htc, vive_cosmos_controller)
DO_PROFILE(htc, vive_focus3_controller)
DO_PROFILE(htc, vive_pro)
DO_PROFILE(ml, ml2_controller)
DO_PROFILE(microsoft, motion_controller)
DO_PROFILE(microsoft, xbox_controller)
DO_PROFILE(oculus, go_controller)
DO_PROFILE(oculus, touch_controller)
DO_PROFILE(meta, touch_pro_controller)
DO_PROFILE(meta, touch_plus_controller)
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(samsung, odyssey_controller)
DO_PROFILE(valve, index_controller)
}
catch (std::exception & e)
{
spdlog::warn("Failed to get current interaction profile: {}", e.what());
}
interaction_profiles[i] = interaction_profile::none;
}
auto now = instance.now();
for (device_id target: {
device_id::LEFT_AIM,
@@ -550,6 +738,17 @@ void scenes::stream::on_interaction_profile_changed(const XrEventDataInteraction
device_id::RIGHT_PALM,
})
{
// don't do derived poses for hand interaction
const bool right = target >= device_id::RIGHT_GRIP && target <= device_id::RIGHT_PALM;
if (interaction_profiles[right].load() == interaction_profile::ext_hand_interaction_ext)
{
network_session->send_control(from_headset::derived_pose{
.source = target,
.target = target,
});
continue;
}
auto source = derived_from(target);
auto source_space = application::space(device_to_space(source));
auto target_space = application::space(device_to_space(target));
@@ -612,52 +811,4 @@ void scenes::stream::on_interaction_profile_changed(const XrEventDataInteraction
}
}
}
std::array path = {
"/user/hand/left",
"/user/hand/right",
};
#define DO_PROFILE(vendor, name) \
if (profile == "/interaction_profiles/" #vendor "/" #name) \
{ \
interaction_profiles[i] = interaction_profile::vendor##_##name; \
continue; \
}
for (size_t i = 0; i < 2; ++i)
{
try
{
auto profile = session.get_current_interaction_profile(path[i]);
spdlog::info("interaction profile for {}: {}", path[i], profile);
DO_PROFILE(khr, simple_controller)
DO_PROFILE(bytedance, pico_neo3_controller)
DO_PROFILE(bytedance, pico4_controller)
DO_PROFILE(bytedance, pico4s_controller)
DO_PROFILE(bytedance, pico_g3_controller)
DO_PROFILE(google, daydream_controller)
DO_PROFILE(hp, mixed_reality_controller)
DO_PROFILE(htc, vive_controller)
DO_PROFILE(htc, vive_cosmos_controller)
DO_PROFILE(htc, vive_focus3_controller)
DO_PROFILE(htc, vive_pro)
DO_PROFILE(ml, ml2_controller)
DO_PROFILE(microsoft, motion_controller)
DO_PROFILE(microsoft, xbox_controller)
DO_PROFILE(oculus, go_controller)
DO_PROFILE(oculus, touch_controller)
DO_PROFILE(meta, touch_pro_controller)
DO_PROFILE(meta, touch_plus_controller)
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(samsung, odyssey_controller)
DO_PROFILE(valve, index_controller)
}
catch (std::exception & e)
{
spdlog::warn("Failed to get current interation profile: {}", e.what());
}
interaction_profiles[i] = interaction_profile::none;
}
}
+2 -4
View File
@@ -114,6 +114,7 @@ out gl_PerVertex
void main()
{
// TODO: use base_color_texcoord et al instead of always using texcoord 0
for(int i = 0; i < nb_texcoords; i++)
texcoord[i] = in_texcoord[i];
@@ -149,7 +150,7 @@ void main()
const float dither_pattern[4][4] = {
{ 0.0f, 0.5f, 0.125f, 0.625f},
{ 0.75f, 0.22f, 0.875f, 0.375f},
{ 0.75f, 0.25f, 0.875f, 0.375f},
{ 0.1875f, 0.6875f, 0.0625f, 0.5625},
{ 0.9375f, 0.4375f, 0.8125f, 0.3125}
};
@@ -206,9 +207,6 @@ void main()
bc = mix(bc + ec, fog_color, fog);
// if (alpha_cutout && c.a <= 0.5)
// discard;
if (dithering)
{
ivec2 tmp = ivec2(gl_FragCoord.xy) % 4;
+41 -7
View File
@@ -16,34 +16,68 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#version 450
#ifdef VERT_SHADER
layout (location = 0) in vec2 vPosition;
layout (location = 1) in vec2 vUV;
layout (location = 1) in uvec2 vUV;
layout(location = 0) out vec2 outUV;
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);
outUV = vUV;
vec2 uv = vUV;
outUV.xy = (uv + rgb_rect.xy) / rgb_rect.zw;
outUV.zw = (uv + a_rect.xy) / a_rect.zw;
}
#endif
#ifdef FRAG_SHADER
layout(set = 0, binding = 0) uniform sampler2D texSampler;
layout(constant_id = 0) const int alpha = 1;
layout(constant_id = 1) const bool do_srgb = false;
layout(location = 0) in vec2 inUV;
layout(set = 0, binding = 0) uniform sampler2D rgb[alpha + 1];
layout(location = 0) in vec4 inUV;
layout(location = 0) out vec4 outColor;
float sRGB_to_linear(float x)
{
if (x <= 0.04045)
return x / 12.92;
return pow((x + 0.055) / 1.055, 2.4);
}
vec4 sRGB_to_linear_rgba(vec4 x)
{
return vec4(
sRGB_to_linear(x.r),
sRGB_to_linear(x.g),
sRGB_to_linear(x.b),
x.a);
}
void main()
{
outColor = texture(texSampler, inUV).rgba;
if (alpha == 1)
outColor = vec4(texture(rgb[0], inUV.xy).rgb, texture(rgb[1], inUV.zw).r);
else
outColor = texture(rgb[0], inUV.xy).rgba;
if (do_srgb)
{
outColor = sRGB_to_linear_rgba(outColor);
}
}
#endif
-179
View File
@@ -1,179 +0,0 @@
/*
* Snapdragon™ Game Super Resolution
* Copyright (c) 2023, Qualcomm Innovation Center, Inc. All rights reserved.
*
* https://github.com/SnapdragonStudios/snapdragon-gsr
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#version 450
precision mediump float;
precision highp int;
#define OperationMode 1
layout (constant_id = 0) const bool use_edge_direction = true;
layout (constant_id = 1) const float edge_threshold = 4.0/255.0;
layout (constant_id = 2) const float edge_sharpness = 2.0;
layout(set = 0, binding = 0) uniform mediump sampler2D texSampler;
layout(location = 0) in highp vec2 inUV;
layout(location = 0) out vec4 outColor;
float fastLanczos2(float x)
{
float wA = x-4.0;
float wB = x*wA-wA;
wA *= wA;
return wB*wA;
}
vec2 weightY(float dx, float dy, float c, vec3 data)
{
float std = data.x;
vec2 dir = data.yz;
float edgeDis = ((dx*dir.y)+(dy*dir.x));
float x = (((dx*dx)+(dy*dy))+((edgeDis*edgeDis)*((clamp(((c*c)*std),0.0,1.0)*0.7)+-1.0)));
float w = fastLanczos2(x);
return vec2(w, w * c);
}
vec2 weightYned(float dx, float dy, float c, float std)
{
float x = ((dx*dx)+(dy* dy))* 0.55 + clamp(abs(c)*std, 0.0, 1.0);
float w = fastLanczos2(x);
return vec2(w, w * c);
}
vec2 edgeDirection(vec4 left, vec4 right)
{
vec2 dir;
float RxLz = (right.x + (-left.z));
float RwLy = (right.w + (-left.y));
vec2 delta;
delta.x = (RxLz + RwLy);
delta.y = (RxLz + (-RwLy));
float lengthInv = inversesqrt((delta.x * delta.x+ 3.075740e-05) + (delta.y * delta.y));
dir.x = (delta.x * lengthInv);
dir.y = (delta.y * lengthInv);
return dir;
}
void main()
{
vec4 color = textureLod(texSampler,inUV,0.0).xyzw;
float alpha = color.a;
if (OperationMode == 1)
color.a = 0.0;
if (OperationMode != 4)
{
vec2 dim = textureSize(texSampler, 0);
vec4 viewportInfo = vec4(1/dim.x, 1/dim.y, dim.x, dim.y);
highp vec2 imgCoord = ((inUV.xy*viewportInfo.zw)+vec2(-0.5,0.5));
highp vec2 imgCoordPixel = floor(imgCoord);
highp vec2 coord = (imgCoordPixel*viewportInfo.xy);
vec2 pl = (imgCoord+(-imgCoordPixel));
vec4 left = textureGather(texSampler,coord, OperationMode);
float edgeVote = abs(left.z - left.y) + abs(color[OperationMode] - left.y) + abs(color[OperationMode] - left.z) ;
if(edgeVote > edge_threshold)
{
coord.x += viewportInfo.x;
vec4 right = textureGather(texSampler,coord + vec2(viewportInfo.x, 0.0), OperationMode);
vec4 upDown;
upDown.xy = textureGather(texSampler,coord + vec2(0.0, -viewportInfo.y),OperationMode).wz;
upDown.zw = textureGather(texSampler,coord + vec2(0.0, viewportInfo.y), OperationMode).yx;
float mean = (left.y+left.z+right.x+right.w)*0.25;
left = left - vec4(mean);
right = right - vec4(mean);
upDown = upDown - vec4(mean);
color.w =color[OperationMode] - mean;
float sum = (((((abs(left.x)+abs(left.y))+abs(left.z))+abs(left.w))+(((abs(right.x)+abs(right.y))+abs(right.z))+abs(right.w)))+(((abs(upDown.x)+abs(upDown.y))+abs(upDown.z))+abs(upDown.w)));
float sumMean = 1.014185e+01/sum;
float std = (sumMean*sumMean);
vec2 aWY;
if (use_edge_direction) {
vec3 data = vec3(std, edgeDirection(left, right));
aWY = weightY(pl.x, pl.y+1.0, upDown.x,data);
aWY += weightY(pl.x-1.0, pl.y+1.0, upDown.y,data);
aWY += weightY(pl.x-1.0, pl.y-2.0, upDown.z,data);
aWY += weightY(pl.x, pl.y-2.0, upDown.w,data);
aWY += weightY(pl.x+1.0, pl.y-1.0, left.x,data);
aWY += weightY(pl.x, pl.y-1.0, left.y,data);
aWY += weightY(pl.x, pl.y, left.z,data);
aWY += weightY(pl.x+1.0, pl.y, left.w,data);
aWY += weightY(pl.x-1.0, pl.y-1.0, right.x,data);
aWY += weightY(pl.x-2.0, pl.y-1.0, right.y,data);
aWY += weightY(pl.x-2.0, pl.y, right.z,data);
aWY += weightY(pl.x-1.0, pl.y, right.w,data);
} else {
aWY = weightYned(pl.x, pl.y+1.0, upDown.x,std);
aWY += weightYned(pl.x-1.0, pl.y+1.0, upDown.y,std);
aWY += weightYned(pl.x-1.0, pl.y-2.0, upDown.z,std);
aWY += weightYned(pl.x, pl.y-2.0, upDown.w,std);
aWY += weightYned(pl.x+1.0, pl.y-1.0, left.x,std);
aWY += weightYned(pl.x, pl.y-1.0, left.y,std);
aWY += weightYned(pl.x, pl.y, left.z,std);
aWY += weightYned(pl.x+1.0, pl.y, left.w,std);
aWY += weightYned(pl.x-1.0, pl.y-1.0, right.x,std);
aWY += weightYned(pl.x-2.0, pl.y-1.0, right.y,std);
aWY += weightYned(pl.x-2.0, pl.y, right.z,std);
aWY += weightYned(pl.x-1.0, pl.y, right.w,std);
}
float finalY = aWY.y/aWY.x;
float maxY = max(max(left.y,left.z),max(right.x,right.w));
float minY = min(min(left.y,left.z),min(right.x,right.w));
float deltaY = clamp(edge_sharpness*finalY, minY, maxY) -color.w;
//smooth high contrast input
deltaY = clamp(deltaY, -23.0 / 255.0, 23.0 / 255.0);
color.x = clamp((color.x+deltaY),0.0,1.0);
color.y = clamp((color.y+deltaY),0.0,1.0);
color.z = clamp((color.z+deltaY),0.0,1.0);
}
}
outColor = vec4(color.rgb, alpha);
}
+3 -27
View File
@@ -45,40 +45,16 @@ void main()
#ifdef FRAG_SHADER
layout(binding = 0) uniform sampler2D texSampler;
layout(constant_id = 0) const bool do_srgb = true;
layout(constant_id = 1) const bool is_alpha = false;
layout(constant_id = 0) const bool is_alpha = false;
layout(location = 0) in vec2 inUV;
layout(location = 0) out vec4 outColor;
float sRGB_to_linear(float x)
{
if (x <= 0.04045)
return x / 12.92;
return pow((x + 0.055) / 1.055, 2.4);
}
vec4 sRGB_to_linear_rgba(vec4 x)
{
return vec4(
sRGB_to_linear(x.r),
sRGB_to_linear(x.g),
sRGB_to_linear(x.b),
x.r);
}
void main()
{
if (do_srgb)
{
outColor = sRGB_to_linear_rgba(texture(texSampler, inUV));
}
else
{
outColor = texture(texSampler, inUV);
outColor.a = outColor.r;
}
outColor = texture(texSampler, inUV);
outColor.a = outColor.r;
if (!is_alpha)
{
outColor.a = 1;
+11 -3
View File
@@ -26,9 +26,17 @@ namespace utils
template <typename Rng, typename T>
bool contains(Rng && range, const T & value)
{
auto it = std::find(range.begin(), range.end(), value);
return it != range.end();
if constexpr (std::is_convertible_v<T, const char *> and
std::is_convertible_v<typename std::decay_t<Rng>::value_type, const char *>)
{
auto it = std::find_if(range.begin(), range.end(), [&](const char * i) { return strcmp(i, value) == 0; });
return it != range.end();
}
else
{
auto it = std::find(range.begin(), range.end(), value);
return it != range.end();
}
}
// Check if all values of range2 are in range1
+49 -5
View File
@@ -19,37 +19,81 @@
#pragma once
#include <spdlog/spdlog.h>
#include <type_traits>
#include <utility>
#include <variant>
#include <openxr/openxr.h>
namespace utils
{
template <typename T, XrResult deleter(T)>
template <typename T, auto Deleter = nullptr>
class handle
{
public:
// true if the deleter is provided when constructing the object
// typically if it's from an OpenXR extension
static constexpr bool runtime_deleter = Deleter == nullptr;
protected:
static const inline T null_value = 0;
T id = null_value;
[[no_unique_address]] std::conditional_t<runtime_deleter, XrResult (*)(T), std::monostate> deleter;
public:
handle() {}
template <typename = void>
requires(not runtime_deleter)
handle()
{}
template <typename = void>
requires(not runtime_deleter)
handle(T id) :
id(id) {}
id(id)
{}
template <typename = void>
requires(runtime_deleter)
handle(XrResult (*deleter)(T)) :
deleter(deleter)
{
assert(deleter);
}
template <typename = void>
requires(runtime_deleter)
handle(T id, XrResult (*deleter)(T)) :
id(id), deleter(deleter)
{
assert(deleter);
}
~handle()
{
if (id != null_value)
deleter(id);
{
XrResult res = XR_SUCCESS;
if constexpr (runtime_deleter)
res = deleter(id);
else
res = Deleter(id);
if (not XR_SUCCEEDED(res))
spdlog::warn("Failed to destroy {}", typeid(T).name());
}
}
handle(handle && other) noexcept :
id(other.id)
id(other.id), deleter(other.deleter)
{
other.id = null_value;
}
handle & operator=(handle && other) noexcept
{
if constexpr (runtime_deleter)
std::swap(deleter, other.deleter);
std::swap(id, other.id);
return *this;
}
+70
View File
@@ -0,0 +1,70 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2024 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 "i18n.h"
#include "asset.h"
#include <map>
#include <string>
#include <vector>
extern std::map<std::string, std::vector<int>> glyph_set_per_language;
std::vector<boost::locale::gnu_gettext::messages_info> get_locales()
{
boost::locale::gnu_gettext::messages_info messages_info;
messages_info.paths.push_back("locale");
messages_info.encoding = "UTF-8";
messages_info.domains.push_back(boost::locale::gnu_gettext::messages_info::domain("wivrn"));
messages_info.callback = open_locale_file;
std::vector<boost::locale::gnu_gettext::messages_info> res;
messages_info.language = "en";
messages_info.country = "US";
res.push_back(messages_info);
for (const auto & [code, glyphs]: glyph_set_per_language)
{
auto pos = code.find("_");
messages_info.language = code.substr(0, pos);
if (pos == std::string::npos)
messages_info.country = "";
else
messages_info.country = code.substr(pos + 1);
res.push_back(messages_info);
}
return res;
}
std::vector<char> open_locale_file(const std::string & file_name, const std::string & encoding)
{
std::vector<char> buffer;
try
{
asset file(file_name);
buffer.resize(file.size());
memcpy(buffer.data(), file.data(), file.size());
}
catch (...)
{
}
return buffer;
}
+3
View File
@@ -23,3 +23,6 @@
#define _F(x) fmt::runtime(boost::locale::gettext(x))
#define _S(x) boost::locale::gettext(x).c_str()
#define _cS(c, x) boost::locale::pgettext(c, x).c_str()
std::vector<boost::locale::gnu_gettext::messages_info> get_locales();
std::vector<char> open_locale_file(const std::string & file_name, const std::string & encoding);
+45
View File
@@ -0,0 +1,45 @@
#include "renderdoc.h"
#include "renderdoc_app.h"
#include <dlfcn.h>
#include <iostream>
static RENDERDOC_API_1_0_0 * renderdoc_init()
{
RENDERDOC_API_1_0_0 * renderdoc_api = nullptr;
auto renderdoc_module = dlopen("librenderdoc.so", RTLD_NOW | RTLD_NOLOAD);
if (not renderdoc_module)
return nullptr;
auto * func = reinterpret_cast<pRENDERDOC_GetAPI>(dlsym(renderdoc_module, "RENDERDOC_GetAPI"));
if (!func)
{
std::cerr << "Failed to load RENDERDOC_GetAPI function." << std::endl;
return nullptr;
}
if (!func(eRENDERDOC_API_Version_1_0_0, reinterpret_cast<void **>(&renderdoc_api)))
{
std::cerr << "Failed to obtain RenderDoc 1.0.0 API." << std::endl;
return nullptr;
}
int major, minor, patch;
renderdoc_api->GetAPIVersion(&major, &minor, &patch);
return renderdoc_api;
}
static RENDERDOC_API_1_0_0 * get_renderdoc()
{
static RENDERDOC_API_1_0_0 * renderdoc_api = renderdoc_init();
return renderdoc_api;
}
void wivrn::renderdoc_begin(VkInstance inst)
{
if (auto renderdoc_api = get_renderdoc())
renderdoc_api->StartFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(inst), nullptr);
}
void wivrn::renderdoc_end(VkInstance inst)
{
if (auto renderdoc_api = get_renderdoc())
renderdoc_api->EndFrameCapture(RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(inst), nullptr);
}
+6
View File
@@ -0,0 +1,6 @@
#include <vulkan/vulkan.h>
namespace wivrn
{
void renderdoc_begin(VkInstance);
void renderdoc_end(VkInstance);
} // namespace wivrn
+2 -1
View File
@@ -18,12 +18,13 @@
*/
#include "shader.h"
#include "wivrn_shaders.h"
vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::vector<uint32_t> & spirv)
{
vk::ShaderModuleCreateInfo create_info{
.codeSize = spirv.size() * sizeof(uint32_t),
.pCode = data(spirv),
.pCode = spirv.data(),
};
return vk::raii::ShaderModule{device, create_info};
-3
View File
@@ -19,12 +19,9 @@
#pragma once
#include <map>
#include <string>
#include <vector>
#include <vulkan/vulkan_raii.hpp>
extern const std::map<std::string, std::vector<uint32_t>> shaders;
vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::vector<uint32_t> & spirv);
vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::string & name);
+6
View File
@@ -19,6 +19,7 @@
#include "wivrn_client.h"
#include "hardware.h"
#include "protocol_version.h"
#include "secrets.h"
#include "smp.h"
#include "spdlog/common.h"
@@ -99,6 +100,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 = model_name(),
});
@@ -178,6 +180,10 @@ void wivrn_session::handshake(T address, bool tcp_only, crypto::key & headset_ke
case to_headset::crypto_handshake::crypto_state::pairing_disabled:
spdlog::info("Pairing is disabled on server");
throw std::runtime_error(_("Pairing is disabled on server"));
case to_headset::crypto_handshake::crypto_state::incompatible_version:
spdlog::error("Incompatible protocol versions");
throw std::runtime_error(_("Incompatible server version"));
}
// may be on control socket if forced TCP
+80
View File
@@ -0,0 +1,80 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "body_tracker.h"
#include "xr/htc_exts.h"
#include "xr/instance.h"
#include "xr/system.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) and
instance.has_extension(XR_META_BODY_TRACKING_FULL_BODY_EXTENSION_NAME) and
instance.has_extension(XR_META_BODY_TRACKING_FIDELITY_EXTENSION_NAME))
{
auto fb_body_properties = system.fb_body_tracking_properties();
if (fb_body_properties.supportsBodyTracking)
return body_tracker_type::fb;
}
if (instance.has_extension(XR_HTC_PATH_ENUMERATION_EXTENSION_NAME) and
instance.has_extension(XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME))
return body_tracker_type::htc;
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 body_tracker_type::pico;
}
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, bool full_body, bool hips)
{
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))
{
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,
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);
}
return std::monostate();
}
+43
View File
@@ -0,0 +1,43 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "fb_body_tracker.h"
#include "htc_body_tracker.h"
#include "pico_body_tracker.h"
#include "xr/system.h"
#include <utility>
#include <variant>
#include <vector>
#include <openxr/openxr.h>
namespace xr
{
class instance;
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, bool full_body, bool hips);
body_tracker_type body_tracker_supported(xr::instance &, xr::system &);
} // namespace xr
+1
View File
@@ -26,6 +26,7 @@
#include "utils/typename.h"
#include "xr/check.h"
#include <type_traits>
#include <vector>
#include <vulkan/vulkan.h>
#include <openxr/openxr.h>
#include <openxr/openxr_platform.h>
+1 -1
View File
@@ -17,8 +17,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "xr.h"
#include "xr/check.h"
#include "xr/to_string.h"
#include <system_error>
namespace
+94
View File
@@ -0,0 +1,94 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "face_tracker.h"
#include "hardware.h"
#include "xr/instance.h"
#include "xr/system.h"
xr::face_tracker_type xr::face_tracker_supported(xr::instance & instance, xr::system & system)
{
if (instance.has_extension(XR_FB_FACE_TRACKING2_EXTENSION_NAME))
{
auto properties = system.fb_face_tracking2_properties();
if (properties.supportsVisualFaceTracking)
return xr::face_tracker_type::fb;
}
if (instance.has_extension(XR_HTC_FACIAL_TRACKING_EXTENSION_NAME))
{
auto properties = system.htc_face_tracking_properties();
if (properties.supportEyeFacialTracking or properties.supportLipFacialTracking)
return xr::face_tracker_type::htc;
}
switch (guess_model())
{
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;
}
xr::face_tracker xr::make_face_tracker(xr::instance & instance, xr::system & system, xr::session & session)
{
if (instance.has_extension(XR_FB_FACE_TRACKING2_EXTENSION_NAME))
{
auto properties = system.fb_face_tracking2_properties();
if (properties.supportsVisualFaceTracking)
return xr::face_tracker(std::in_place_type_t<xr::fb_face_tracker2>(), instance, session);
}
if (instance.has_extension(XR_HTC_FACIAL_TRACKING_EXTENSION_NAME))
{
auto properties = system.htc_face_tracking_properties();
if (properties.supportEyeFacialTracking or properties.supportLipFacialTracking)
return xr::face_tracker(
std::in_place_type_t<xr::htc_face_tracker>(),
instance,
session,
properties.supportEyeFacialTracking,
properties.supportLipFacialTracking);
}
switch (guess_model())
{
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();
}
+40
View File
@@ -0,0 +1,40 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 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 "fb_face_tracker2.h"
#include "htc_face_tracker.h"
#include "pico_face_tracker.h"
#include "xr/system.h"
#include <variant>
namespace xr
{
class instance;
class session;
using face_tracker = std::variant<std::monostate, xr::fb_face_tracker2, xr::htc_face_tracker, xr::pico_face_tracker>;
face_tracker make_face_tracker(xr::instance &, xr::system &, xr::session &);
face_tracker_type face_tracker_supported(xr::instance &, xr::system &);
} // namespace xr
+17 -36
View File
@@ -18,8 +18,10 @@
#include "fb_body_tracker.h"
#include "spdlog/spdlog.h"
#include "xr/instance.h"
#include "xr/meta_body_tracking_fidelity.h"
#include "xr/xr.h"
#include "xr/session.h"
#include "xr/to_string.h"
#include <ranges>
#include <openxr/openxr.h>
@@ -38,54 +40,33 @@ std::vector<XrFullBodyJointMETA> xr::fb_body_tracker::get_whitelisted_joints(boo
return {whitelisted_joints.begin(), whitelisted_joints.end()};
}
xr::fb_body_tracker::fb_body_tracker(instance & inst, session & s) :
s(s)
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.get_proc<PFN_xrRequestBodyTrackingFidelityMETA>("xrRequestBodyTrackingFidelityMETA")),
xrLocateBodyJointsFB(inst.get_proc<PFN_xrLocateBodyJointsFB>("xrLocateBodyJointsFB")),
full_body(full_body),
hip(hip)
{
xrCreateBodyTrackerFB = inst.get_proc<PFN_xrCreateBodyTrackerFB>("xrCreateBodyTrackerFB");
xrRequestBodyTrackingFidelityMETA = inst.get_proc<PFN_xrRequestBodyTrackingFidelityMETA>("xrRequestBodyTrackingFidelityMETA");
xrLocateBodyJointsFB = inst.get_proc<PFN_xrLocateBodyJointsFB>("xrLocateBodyJointsFB");
xrDestroyBodyTrackerFB = inst.get_proc<PFN_xrDestroyBodyTrackerFB>("xrDestroyBodyTrackerFB");
}
xr::fb_body_tracker::~fb_body_tracker()
{
stop();
}
void xr::fb_body_tracker::start(bool full_body, bool hip)
{
assert(xrCreateBodyTrackerFB);
this->full_body = full_body;
this->hip = hip;
auto xrCreateBodyTrackerFB = inst.get_proc<PFN_xrCreateBodyTrackerFB>("xrCreateBodyTrackerFB");
XrBodyTrackerCreateInfoFB create_info{
.type = XR_TYPE_BODY_TRACKER_CREATE_INFO_FB,
.next = nullptr,
.bodyJointSet = full_body
? XR_BODY_JOINT_SET_FULL_BODY_META
: XR_BODY_JOINT_SET_DEFAULT_FB,
};
create_info.bodyJointSet = full_body
? XR_BODY_JOINT_SET_FULL_BODY_META
: XR_BODY_JOINT_SET_DEFAULT_FB;
CHECK_XR(xrCreateBodyTrackerFB(s, &create_info, &handle));
CHECK_XR(xrCreateBodyTrackerFB(s, &create_info, &id));
// Enable IOBT.
CHECK_XR(xrRequestBodyTrackingFidelityMETA(handle, XR_BODY_TRACKING_FIDELITY_HIGH_META));
CHECK_XR(xrRequestBodyTrackingFidelityMETA(id, XR_BODY_TRACKING_FIDELITY_HIGH_META));
whitelisted_joints = get_whitelisted_joints(full_body, hip);
}
void xr::fb_body_tracker::stop()
{
full_body = false;
hip = false;
if (handle)
{
assert(xrDestroyBodyTrackerFB);
CHECK_XR(xrDestroyBodyTrackerFB(std::exchange(handle, nullptr)));
}
}
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)
{
if (!handle)
if (!id)
return std::nullopt;
assert(xrLocateBodyJointsFB);
@@ -105,7 +86,7 @@ std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_h
.jointLocations = joints.data(),
};
if (auto res = xrLocateBodyJointsFB(handle, &locate_info, &joint_locations); !XR_SUCCEEDED(res))
if (auto res = xrLocateBodyJointsFB(id, &locate_info, &joint_locations); !XR_SUCCEEDED(res))
{
spdlog::warn("xrLocateBodyJointsFB returned {}", xr::to_string(res));
return std::nullopt;
+3 -12
View File
@@ -20,6 +20,7 @@
#include "wivrn_packets.h"
#include "utils/handle.h"
#include "xr/meta_body_tracking_fidelity.h"
#include <array>
#include <optional>
@@ -30,15 +31,10 @@ namespace xr
class instance;
class session;
class fb_body_tracker
class fb_body_tracker : public utils::handle<XrBodyTrackerFB>
{
XrSession s;
XrBodyTrackerFB handle{};
PFN_xrCreateBodyTrackerFB xrCreateBodyTrackerFB{};
PFN_xrRequestBodyTrackingFidelityMETA xrRequestBodyTrackingFidelityMETA{};
PFN_xrLocateBodyJointsFB xrLocateBodyJointsFB{};
PFN_xrDestroyBodyTrackerFB xrDestroyBodyTrackerFB{};
bool full_body{};
bool hip{};
@@ -59,12 +55,7 @@ public:
};
static std::vector<XrFullBodyJointMETA> get_whitelisted_joints(bool full_body, bool hip);
fb_body_tracker() = default;
fb_body_tracker(instance & inst, session & s);
~fb_body_tracker();
void start(bool lower_body, bool hip);
void stop();
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);
};
+18 -10
View File
@@ -19,21 +19,29 @@
#include "fb_face_tracker2.h"
#include "wivrn_packets.h"
#include "xr/instance.h"
#include "xr/session.h"
#include <cstdint>
#include <openxr/openxr.h>
static PFN_xrDestroyFaceTracker2FB xrDestroyFaceTracker2FB{};
XrResult xr::destroy_fb_face_tracker2(XrFaceTracker2FB id)
xr::fb_face_tracker2::fb_face_tracker2(instance & inst, session & s) :
handle(inst.get_proc<PFN_xrDestroyFaceTracker2FB>("xrDestroyFaceTracker2FB"))
{
return xrDestroyFaceTracker2FB(id);
}
xr::fb_face_tracker2::fb_face_tracker2(instance & inst, XrFaceTracker2FB h)
{
id = h;
auto xrCreateFaceTracker2FB = inst.get_proc<PFN_xrCreateFaceTracker2FB>("xrCreateFaceTracker2FB");
xrGetFaceExpressionWeights2FB = inst.get_proc<PFN_xrGetFaceExpressionWeights2FB>("xrGetFaceExpressionWeights2FB");
xrDestroyFaceTracker2FB = inst.get_proc<PFN_xrDestroyFaceTracker2FB>("xrDestroyFaceTracker2FB");
assert(xrCreateFaceTracker2FB);
XrFaceTrackingDataSource2FB data_sources[1];
data_sources[0] = XR_FACE_TRACKING_DATA_SOURCE2_VISUAL_FB;
XrFaceTrackerCreateInfo2FB create_info{
.type = XR_TYPE_FACE_TRACKER_CREATE_INFO2_FB,
.next = nullptr,
.faceExpressionSet = XR_FACE_EXPRESSION_SET2_DEFAULT_FB,
.requestedDataSourceCount = 1,
.requestedDataSources = data_sources,
};
CHECK_XR(xrCreateFaceTracker2FB(s, &create_info, &id));
}
void xr::fb_face_tracker2::get_weights(XrTime time, wivrn::from_headset::tracking::fb_face2 & out_expressions)
+5 -7
View File
@@ -25,18 +25,16 @@
namespace xr
{
class instance;
class session;
XrResult destroy_fb_face_tracker2(XrFaceTracker2FB);
class fb_face_tracker2 : public utils::handle<XrFaceTracker2FB, destroy_fb_face_tracker2>
class fb_face_tracker2 : public utils::handle<XrFaceTracker2FB>
{
PFN_xrGetFaceExpressionWeights2FB xrGetFaceExpressionWeights2FB{};
PFN_xrDestroyFaceTracker2FB xrDestroyFaceTracker2FB{};
public:
fb_face_tracker2() = default;
fb_face_tracker2(instance & inst, XrFaceTracker2FB h);
using packet_type = wivrn::from_headset::tracking::fb_face2;
fb_face_tracker2(instance & inst, session & s);
void get_weights(XrTime time, struct wivrn::from_headset::tracking::fb_face2 & out_expressions);
void get_weights(XrTime time, packet_type & out_expressions);
};
} // namespace xr
+5 -51
View File
@@ -18,28 +18,17 @@
*/
#include "hand_tracker.h"
#include "hardware.h"
#include "xr/check.h"
#include "xr/instance.h"
#include "xr/session.h"
#include <cassert>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
static PFN_xrDestroyHandTrackerEXT xrDestroyHandTrackerEXT{};
XrResult xr::destroy_hand_tracker(XrHandTrackerEXT id)
{
return xrDestroyHandTrackerEXT(id);
}
xr::hand_tracker::hand_tracker(instance & inst, session & session, const XrHandTrackerCreateInfoEXT & info) :
hand_id(info.hand)
handle(inst.get_proc<PFN_xrDestroyHandTrackerEXT>("xrDestroyHandTrackerEXT"))
{
static auto xrCreateHandTrackerEXT = inst.get_proc<PFN_xrCreateHandTrackerEXT>("xrCreateHandTrackerEXT");
auto xrCreateHandTrackerEXT = inst.get_proc<PFN_xrCreateHandTrackerEXT>("xrCreateHandTrackerEXT");
assert(xrCreateHandTrackerEXT);
xrLocateHandJointsEXT = inst.get_proc<PFN_xrLocateHandJointsEXT>("xrLocateHandJointsEXT");
xrDestroyHandTrackerEXT = inst.get_proc<PFN_xrDestroyHandTrackerEXT>("xrDestroyHandTrackerEXT");
CHECK_XR(xrCreateHandTrackerEXT(session, &info, &id));
}
@@ -77,48 +66,13 @@ std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> xr::
if (!locations.isActive)
return std::nullopt;
float offset_angle = 0;
// check if we have a device that needs a thumb offset
switch (guess_model())
{
case model::meta_quest_3:
case model::meta_quest_pro:
case model::meta_quest_3s:
case model::oculus_quest:
case model::oculus_quest_2:
if (hand_id == XR_HAND_LEFT_EXT)
offset_angle = glm::radians(-90.0f);
else if (hand_id == XR_HAND_RIGHT_EXT)
offset_angle = glm::radians(90.0f);
break;
default:
break;
}
// bail if none of the joints are valid/tracked
if (!std::ranges::any_of(joints_pos, [](const auto & loc) { return loc.locationFlags != 0; }))
return std::nullopt;
std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT> joints;
for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++)
{
if (i >= XR_HAND_JOINT_THUMB_METACARPAL_EXT && i <= XR_HAND_JOINT_THUMB_TIP_EXT)
{
// Need to convert the XrQuaternionf to a glm::quat to use glm::rotate
glm::quat q(
joints_pos[i].pose.orientation.w,
joints_pos[i].pose.orientation.x,
joints_pos[i].pose.orientation.y,
joints_pos[i].pose.orientation.z);
glm::quat offset_rotation = glm::rotate(q, offset_angle, glm::vec3(0, 0, 1));
joints_pos[i].pose.orientation = {
.x = offset_rotation.x,
.y = offset_rotation.y,
.z = offset_rotation.z,
.w = offset_rotation.w,
};
}
joints[i] = {joints_pos[i], joints_vel[i]};
}
+1 -6
View File
@@ -28,14 +28,12 @@ namespace xr
{
class instance;
class session;
XrResult destroy_hand_tracker(XrHandTrackerEXT);
class hand_tracker : public utils::handle<XrHandTrackerEXT, destroy_hand_tracker>
class hand_tracker : public utils::handle<XrHandTrackerEXT>
{
PFN_xrLocateHandJointsEXT xrLocateHandJointsEXT{};
public:
hand_tracker() = default;
hand_tracker(instance & inst, session & session, const XrHandTrackerCreateInfoEXT & info);
using joint = std::pair<XrHandJointLocationEXT, XrHandJointVelocityEXT>;
@@ -43,8 +41,5 @@ public:
std::optional<std::array<joint, XR_HAND_JOINT_COUNT_EXT>> locate(XrSpace space, XrTime time);
static bool check_flags(const std::array<joint, XR_HAND_JOINT_COUNT_EXT> & joints, XrSpaceLocationFlags position, XrSpaceVelocityFlags velocity);
private:
XrHandEXT hand_id;
};
} // namespace xr
+125
View File
@@ -0,0 +1,125 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Awzri <awzri@awzricat.com>
* Copyright (C) 2025 Sapphire <imsapphire0@gmail.com>
* Copyright (C) 2025 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 "htc_body_tracker.h"
#include "xr/details/enumerate.h"
#include "xr/session.h"
#include <openxr/openxr.h>
// Note: This utilizes extensions not present in the OpenXR spec!
// For more info see:
// https://hub.vive.com/apidoc/api/VIVE.OpenXR.Tracker.ViveXRTracker.html
// https://hub.vive.com/apidoc/api/VIVE.OpenXR.VivePathEnumerationHelper.xrEnumeratePathsForInteractionProfileHTCDelegate.html
xr::vive_xr_tracker::vive_xr_tracker(XrPath path, xr::space & space, XrSession session) :
path(path),
space(space)
{
update_active(session);
}
void xr::vive_xr_tracker::update_active(XrSession session)
{
XrInputSourceLocalizedNameGetInfo get_info{
.type = XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO,
.next = nullptr,
.sourcePath = path,
.whichComponents = XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT,
};
auto role = xr::details::enumerate<char>(xrGetInputSourceLocalizedName, session, &get_info);
is_active = not role.contains("_");
}
bool xr::vive_xr_tracker::get_active() const
{
return is_active;
}
XrSpace xr::vive_xr_tracker::get_space() const
{
return space;
}
static wivrn::from_headset::body_tracking::pose locate_space(XrSpace space, XrSpace reference, XrTime time)
{
XrSpaceVelocity velocity{
.type = XR_TYPE_SPACE_VELOCITY,
};
XrSpaceLocation location{
.type = XR_TYPE_SPACE_LOCATION,
.next = &velocity,
};
xrLocateSpace(space, reference, time, &location);
wivrn::from_headset::body_tracking::pose res{
.pose = location.pose,
.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;
}
xr::htc_body_tracker::htc_body_tracker(session & s, std::vector<std::pair<XrPath, xr::space>> & trackers) :
s(s)
{
this->trackers.reserve(trackers.size());
for (auto & [path, space]: trackers)
this->trackers.emplace_back(path, space, s);
}
void xr::htc_body_tracker::update_active()
{
for (auto & tracker: trackers)
tracker.update_active(s);
}
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)
{
std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses> poses{};
for (int i = 0; i < trackers.size(); i++)
{
auto & tracker = trackers[i];
wivrn::from_headset::body_tracking::pose pose{
.pose = {},
.flags = 0,
};
if (tracker.get_active())
pose = locate_space(tracker.get_space(), reference, time);
poses[i] = pose;
}
return poses;
}
+57
View File
@@ -0,0 +1,57 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Awzri <awzri@awzricat.com>
* Copyright (C) 2025 Sapphire <imsapphire0@gmail.com>
* Copyright (C) 2025 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 "wivrn_packets.h"
#include "xr/space.h"
#include <vector>
#include <openxr/openxr.h>
namespace xr
{
class instance;
class session;
class vive_xr_tracker
{
bool is_active = false;
XrPath path;
xr::space & space;
public:
vive_xr_tracker(XrPath path, xr::space & s, XrSession session);
void update_active(XrSession session);
bool get_active() const;
XrSpace get_space() const;
};
class htc_body_tracker
{
XrSession s;
std::vector<vive_xr_tracker> trackers;
public:
htc_body_tracker(session & s, std::vector<std::pair<XrPath, xr::space>> & trackers);
void update_active();
std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses> locate_spaces(XrTime time, XrSpace reference);
};
} // namespace xr

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