Compare commits

...
Author SHA1 Message Date
Vindicus999 4e433e3ecc Merge remote-tracking branch 'upstream/master' 2025-08-10 17:12:34 +00: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
Vindicus999 d310b2ab47 Merge remote-tracking branch 'upstream/master' 2025-08-10 11:12:30 +00: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
Vindicus999 492a88c839 Merge remote-tracking branch 'upstream/master' 2025-08-09 23:14:44 +00:00
Patrick Nicolas 5ccc725ef7 Hide Steam launch options in wizard if empty 2025-08-09 22:47:00 +02:00
Vindicus999 bd5d4882a4 Merge remote-tracking branch 'upstream/master' 2025-08-09 17:12:50 +00: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
Vindicus999 df389c60ab Merge remote-tracking branch 'upstream/master' 2025-08-08 23:15:07 +00: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
Vindicus999 78240f9be0 Merge remote-tracking branch 'upstream/master' 2025-08-08 17:12:50 +00: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
Vindicus999 80e31b642a Merge remote-tracking branch 'upstream/master' 2025-08-07 17:17:47 +00: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
Vindicus999 8a9d218e4f Merge remote-tracking branch 'upstream/master' 2025-08-06 23:16:38 +00: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
Vindicus999 6eaaf8b770 Merge remote-tracking branch 'upstream/master' 2025-08-06 17:19:05 +00: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
Vindicus999 617934e91f Merge remote-tracking branch 'upstream/master' 2025-08-06 11:14:52 +00:00
mitsuami-megane 5efc92efee update ja locale 2025-08-06 12:40:08 +02:00
Just some guy 06d5e00fe2 2025-08-05 23:15:59 +00:00
Vindicus999 377e218782 Use spaces instead of tabs 2025-08-05 18:45:44 -04:00
Vindicus999 5e81b4a14d Merge remote-tracking branch 'upstream/master' 2025-08-04 23:16:08 +00: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
Vindicus999 20b67a5a3c Merge remote-tracking branch 'upstream/master' 2025-08-04 11:15:24 +00: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
Vindicus999 c55fec84fe Merge remote-tracking branch 'upstream/master' 2025-08-03 17:14:21 +00: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
Vindicus999 acf6cc03d0 Merge remote-tracking branch 'upstream/master' 2025-08-03 11:13:42 +00: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
Vindicus999 0e2d46c152 Merge remote-tracking branch 'upstream/master' 2025-08-02 11:13:31 +00: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
Vindicus999 ea5d3b4185 Merge remote-tracking branch 'upstream/master' 2025-07-31 11:14:26 +00:00
mitsuami-megane d7d91cd84d update ja locale 2025-07-31 09:18:01 +02:00
Just some guy c0a8df2a60 2025-07-30 23:16:17 +00:00
Vindicus999 4bb40296fc Updated patches 2025-07-30 18:47:12 -04:00
Just some guy c34e8c6961 2025-07-30 22:24:12 +00:00
Vindicus999 1999e953dd Flipped the ray 2025-07-30 18:23:36 -04:00
Vindicus999 40f83a2b60 Fixed a line 2025-07-30 18:20:33 -04:00
Vindicus999 8af5b3eb29 feat: enable XR_FB_body_tracking
copied from commit 2b654c0
2025-07-30 18:14:51 -04:00
Vindicus999 3485593e56 Merge branch 'master' into sneed 2025-07-30 18:00:20 -04:00
Vindicus999 6c3563904c Update ray.png 2025-07-30 17:56:47 -04:00
Vindicus999 66435957bb Add a last improvement 2025-07-30 17:56:47 -04:00
Vindicus999 1550a346c3 Update patches 2025-07-30 17:56:47 -04:00
Vindicus999 4fd6d6d816 Update CMakeLists.txt 2025-07-30 17:56:47 -04:00
Tool Man be2027ce9a Adding solarxr patches
Remove potential statistics
2025-07-30 17:56:47 -04:00
Vindicus999 fa3313e293 Update Sync.yml 2025-07-30 17:56:47 -04:00
Vindicus999 7e0ea37b3c Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 b0d9bd2ab7 Update Sync.yml 2025-07-30 17:56:47 -04:00
Vindicus999 42755dbb7c Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 b9ff08d893 Update Sync.yml 2025-07-30 17:56:47 -04:00
Vindicus999 b997ff3a17 Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 63aa862a67 Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 52646de23e Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 6e8e78b912 Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 a7a56d0873 Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 59a241de63 Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 4740848ca5 Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 651c9d5a0f Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 bc5d80a13a Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 b1db340227 Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 8377d617cf Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 f94e46ed24 Update APK-Release.yml 2025-07-30 17:56:47 -04:00
Vindicus999 aa1f3b39bd Create pull.yml 2025-07-30 17:56:47 -04:00
Tool Man 680dd34529 Create pull.yml 2025-07-30 17:56:47 -04: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
Just some guy f301ba393a Merge branch 'WiVRn:master' into sneed 2025-06-20 22:13:36 +00: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
Just some guy 0ccc8b6239 Merge branch 'WiVRn:master' into sneed 2025-06-15 19:41:44 +00: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
Sapphire cc8092dd90 Cleanup body tracking 2025-06-10 09:38:49 +02:00
Patrick Nicolas 810d3e9af3 fix newline in ja translation 2025-06-09 19:46:13 +02:00
Patrick Nicolas 09ff9abba8 silence locale error 2025-06-09 19:26:55 +02:00
Patrick Nicolas 24c38e2a02 Move assert in body tracker destructor 2025-06-09 19:26:30 +02:00
mitsuami-megane fedd7917db update ja locale 2025-06-09 18:24:40 +02:00
Patrick Nicolas 18d1619d20 Don't crash on bigger than recommended image 2025-06-09 16:26:56 +02:00
galister b3f3c1c7fc fixed foveation: account for asymmetric v-fov 2025-06-09 16:19:12 +02:00
Vindicus999 adcf159916 Update ray.png 2025-05-26 18:36:33 -04:00
Vindicus999 4125cad44e Add a last improvement 2025-05-16 18:39:23 -04:00
Vindicus999 6969e5f972 Update patches 2025-05-16 18:29:29 -04:00
Vindicus999 d0250abbc9 Update CMakeLists.txt 2025-05-15 23:00:09 -04:00
Tool Man 7485cd0880 Adding solarxr patches
Remove potential statistics
2025-05-15 22:20:37 -04:00
211 changed files with 28551 additions and 7664 deletions
+6
View File
@@ -0,0 +1,6 @@
version: "1"
rules:
- base: master
upstream: WiVRn:master
mergeMethod: hardreset
+22 -8
View File
@@ -22,9 +22,14 @@ 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
#
# - uses: actions/checkout@v4
# with:
# repository: 'Vindicus999/WiVRn'
# ref: sneed
- name: set up JDK
uses: actions/setup-java@v4
@@ -68,7 +73,9 @@ jobs:
- name: Prepare before archiving artifacts
run: |
mkdir apk
ls build/outputs/apk/
mv $(find build/outputs/apk/ -name "*.apk") apk/
ls apk/
mkdir debug
mv build/intermediates/merged_native_libs/*/*/out/lib/* debug/
find debug -name libopenxr_loader.so -delete
@@ -102,13 +109,15 @@ 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
# ls
# for f in *.apk; do
# BASENAME=`echo ${f}|awk -F '-APK-' '{print $2}'`
# mv "${f}" "org.meumeu.wivrn-${BASENAME}"
# done
# ls
- name: Download APK debug artifacts
uses: actions/download-artifact@v4
@@ -122,6 +131,11 @@ jobs:
cd symbols
zip -r ../debug-symbols.zip .
- name: How the hell doesnt it work
run: |
ls apk
ls
- name: APK Release
uses: softprops/action-gh-release@v2
with:
+17 -8
View File
@@ -33,7 +33,7 @@ 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:
@@ -87,7 +87,7 @@ 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
# runtime: qml6-module-qtqml-workerscript qml6-module-qtquick-dialogs
- name: Prepare Vulkan SDK
uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944
@@ -124,7 +124,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,11 +153,13 @@ 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
@@ -190,7 +192,7 @@ 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: >
@@ -242,7 +244,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
@@ -465,7 +467,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 +489,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 +583,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
+34
View File
@@ -0,0 +1,34 @@
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 sneed -> master
uses: devmasx/merge-branch@master
with:
type: now
from_branch: sneed
target_branch: master
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. -->
+24 -12
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
@@ -31,6 +31,7 @@ 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_USE_NVENC "Enable nvenc (Nvidia) hardware encoder" ON)
@@ -41,12 +42,12 @@ auto_option(WIVRN_USE_X264 "Enable x264 software encoder" AUTO)
auto_option(WIVRN_USE_PIPEWIRE "Enable pipewire backend" AUTO)
auto_option(WIVRN_USE_PULSEAUDIO "Enable pulseaudio backend" AUTO)
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)
option(WIVRN_FEATURE_RENDERDOC "Support renderdoc" OFF)
set(WIVRN_FEATURE_SOLARXR OFF) # Will be added back when merged in upstream Monado
option(WIVRN_FEATURE_SOLARXR "Enable SolarXR driver" OFF)
option(WIVRN_FEATURE_STEAMVR_LIGHTHOUSE "Enable SteamVR Lighthouse driver" OFF)
option(WIVRN_CHECK_CAPSYSNICE "Check if CAP_SYS_NICE is available at startup" ON)
@@ -182,6 +183,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)
find_package(PNG)
endif()
if (WIVRN_BUILD_DASHBOARD)
find_package(Qt6 REQUIRED COMPONENTS Core Quick Test Gui QuickControls2 Widgets Network)
@@ -239,9 +246,9 @@ endif()
if (WIVRN_BUILD_DISSECTOR)
if (WIVRN_USE_SYSTEM_OPENXR STREQUAL "AUTO")
find_package(OpenXR 1.0.34)
find_package(OpenXR 1.1.48)
elseif(WIVRN_USE_SYSTEM_OPENXR STREQUAL "ON")
find_package(OpenXR 1.0.34 REQUIRED)
find_package(OpenXR 1.1.48 REQUIRED)
endif()
find_package(Wireshark REQUIRED)
endif()
@@ -273,21 +280,24 @@ FetchContent_Declare(stb EXCLUDE_FROM_ALL SYSTEM URL https://github.co
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(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 +305,9 @@ FetchContent_Declare(monado
)
add_subdirectory(external)
add_subdirectory(common)
if (WIVRN_BUILD_CLIENT OR WIVRN_BUILD_SERVER OR WIVRN_BUILD_DASHBOARD OR WIVRN_BUILD_DISSECTOR)
add_subdirectory(common)
endif()
if (WIVRN_BUILD_CLIENT)
add_subdirectory(client)
+1
View File
@@ -153,6 +153,7 @@ 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
- [qCoro](https://qcoro.dev/)
Binary file not shown.

After

Width:  |  Height:  |  Size: 930 B

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 581 B

After

Width:  |  Height:  |  Size: 292 B

+3 -1
View File
@@ -55,7 +55,7 @@ task "generatePngs"() {
android {
namespace "org.meumeu.wivrn"
ndkVersion "27.1.12297006"
ndkVersion "28.1.13356709"
lint {
disable += "ExpiredTargetSdkVersion"
@@ -72,6 +72,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"
@@ -90,6 +91,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"
}
+24 -19
View File
@@ -7,7 +7,7 @@ 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)
@@ -91,7 +91,22 @@ file(GLOB_RECURSE VULKAN_SHADERS CONFIGURE_DEPENDS "*.glsl")
target_sources(wivrn PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS})
wivrn_compile_glsl(wivrn ${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
#
@@ -225,14 +236,8 @@ add_custom_command(OUTPUT ${ASSETS_DIR}/wivrn.png
COMMAND ${RSVG_CONVERT} ${IMG_SRC_DIR}/wivrn.svg -w 540 -h 540 -o ${ASSETS_DIR}/wivrn.png ${RSVG_OPTS}
DEPENDS ${IMG_SRC_DIR}/wivrn.svg ${WIVRN_CSS_ABS})
add_custom_command(OUTPUT ${ASSETS_DIR}/wivrn-pride.png
COMMAND ${RSVG_CONVERT} ${IMG_SRC_DIR}/wivrn-pride.svg -w 540 -h 540 -o ${ASSETS_DIR}/wivrn-pride.png ${RSVG_OPTS}
DEPENDS ${IMG_SRC_DIR}/wivrn-pride.svg ${WIVRN_CSS_ABS})
add_custom_target(assets ALL DEPENDS
${ASSETS_DIR}/wivrn.png
${ASSETS_DIR}/wivrn-pride.png
)
${ASSETS_DIR}/wivrn.png)
add_dependencies(wivrn assets)
@@ -241,9 +246,10 @@ if(ANDROID)
add_custom_command(OUTPUT ${ASSETS_DIR}/wivrn.ktx2
COMMAND ${TOKTX} --encode astc --astc_blk_d 4x4 --astc_quality 100 --genmipmap ${ASSETS_DIR}/wivrn.ktx2 ${ASSETS_DIR}/wivrn.png
DEPENDS ${ASSETS_DIR}/wivrn.png)
add_custom_command(OUTPUT ${ASSETS_DIR}/wivrn-pride.ktx2
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
@@ -255,10 +261,9 @@ if(ANDROID)
add_custom_target(assets-android ALL DEPENDS
${ASSETS_DIR}/wivrn.ktx2
${ASSETS_DIR}/wivrn-pride.ktx2
${ASSETS_DIR}/WoodFloor051_1K-JPG_Color.ktx2
${ASSETS_DIR}/vr_splash.png
)
${ASSETS_DIR}/vr_splash.png)
add_dependencies(assets-android assets)
add_dependencies(wivrn assets-android)
endif()
+258 -146
View File
@@ -26,7 +26,6 @@
#include "spdlog/spdlog.h"
#include "utils/contains.h"
#include "utils/files.h"
#include "utils/named_thread.h"
#include "vk/check.h"
#include "wifi_lock.h"
#include "xr/actionset.h"
@@ -51,6 +50,7 @@
#endif
#ifdef __ANDROID__
#include "utils/named_thread.h"
#include <android/native_activity.h>
#include <sys/system_properties.h>
@@ -66,15 +66,16 @@ struct interaction_profile
{
std::string profile_name;
std::vector<std::string> required_extensions;
XrVersion min_version = XR_MAKE_VERSION(1, 0, 0);
XrVersion max_version = XR_MAKE_VERSION(2, 0, 0); // exclusive
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 +91,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 +130,13 @@ 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"},
.max_version = XR_MAKE_VERSION(1, 1, 0),
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/left/output/haptic_trigger_fb",
"/user/hand/left/output/haptic_thumb_fb",
@@ -171,6 +174,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 +187,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 +243,13 @@ 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"},
.max_version = XR_MAKE_VERSION(1, 1, 0),
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -287,11 +293,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 +344,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"},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -379,11 +387,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"},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -421,11 +430,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"},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -463,11 +473,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"},
.input_sources = {
"/user/hand/left/output/haptic",
"/user/hand/right/output/haptic",
@@ -504,13 +515,48 @@ 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"},
.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", "XR_HTC_path_enumeration"},
},
interaction_profile{
.profile_name = "/interaction_profiles/ext/eye_gaze_interaction",
.required_extensions = {"XR_EXT_eye_gaze_interaction"},
.input_sources = {
"/user/eyes_ext/input/gaze_ext/pose",
}},
},
},
};
static const std::pair<std::string_view, XrActionType> action_suffixes[] =
@@ -539,6 +585,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},
@@ -678,9 +727,10 @@ void application::initialize_vulkan()
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))
@@ -690,6 +740,9 @@ void application::initialize_vulkan()
debug_utils_found = true;
#endif
}
std::ranges::sort(extensions);
for (const auto & [extension_name, spec_version]: extensions)
spdlog::info(" {} (version {})", extension_name, spec_version);
#ifndef NDEBUG
if (debug_utils_found && debug_report_found)
@@ -768,11 +821,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());
}
@@ -824,8 +882,7 @@ void application::initialize_vulkan()
};
vk_device = xr_system_id.create_device(vk_physical_device, device_create_info.get());
vk_queue = vk_device.getQueue(vk_queue_family_index, 0);
*vk_queue.lock() = vk_device.getQueue(vk_queue_family_index, 0);
vk::PipelineCacheCreateInfo pipeline_cache_info;
std::vector<std::byte> pipeline_cache_bytes;
@@ -895,6 +952,8 @@ void application::initialize_actions()
{
spdlog::debug("Initializing actions");
auto * htc_body = std::get_if<xr::htc_body_tracker>(&body_tracker);
// Build an action set with all possible input sources
std::vector<XrActionSet> action_sets;
xr_actionset = xr::actionset(xr_instance, "all_actions", "All actions");
@@ -902,23 +961,81 @@ 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 = utils::contains_all(xr_extensions, profile.required_extensions) and profile.min_version <= api_version and profile.max_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 utils::contains(xr_extensions, 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 (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"))
{
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 (htc_body && utils::contains(profile.required_extensions, XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME))
{
for (const auto & user_path: htc_body->get_paths())
{
for (const auto & input_path: htc_body->get_paths(user_path))
{
profile.input_sources.push_back(path_to_string(user_path) + path_to_string(input_path));
}
}
}
suggested_bindings.emplace(profile.profile_name, std::vector<XrActionSuggestedBinding>{});
@@ -947,16 +1064,26 @@ 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") && htc_body)
htc_body->add(xr_session.create_action_space(a));
}
// Build an action set for each scene
@@ -978,20 +1105,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 = string_to_path(k.input_source)});
}
}
}
}
@@ -1034,12 +1164,17 @@ void application::initialize()
// 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 +1184,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 +1210,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));
@@ -1109,54 +1242,6 @@ void application::initialize()
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))
@@ -1203,36 +1288,57 @@ void application::initialize()
right_hand = xr_session.create_hand_tracker(XR_HAND_RIGHT_EXT);
}
if (fb_face_tracking2_supported)
if (utils::contains(xr_extensions, XR_FB_FACE_TRACKING2_EXTENSION_NAME))
{
fb_face_tracker2 = xr_session.create_fb_face_tracker2();
XrSystemFaceTrackingProperties2FB fb_face2_properties = xr_system_id.fb_face_tracking2_properties();
spdlog::info(" FB face tracking support: {}", (bool)fb_face2_properties.supportsVisualFaceTracking);
if (fb_face2_properties.supportsVisualFaceTracking)
face_tracker.emplace<xr::fb_face_tracker2>(xr_instance, xr_session);
}
if (htc_face_tracking_eye_supported)
if (std::holds_alternative<std::monostate>(face_tracker) && utils::contains(xr_extensions, XR_HTC_FACIAL_TRACKING_EXTENSION_NAME))
{
htc_face_tracker_eye = xr_session.create_htc_face_tracker(XR_FACIAL_TRACKING_TYPE_EYE_DEFAULT_HTC);
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);
if (htc_face_properties.supportEyeFacialTracking || htc_face_properties.supportLipFacialTracking)
face_tracker.emplace<xr::htc_face_tracker>(xr_instance, xr_session, htc_face_properties.supportEyeFacialTracking, htc_face_properties.supportLipFacialTracking);
}
if (htc_face_tracking_lip_supported)
if (std::holds_alternative<std::monostate>(face_tracker) && eye_gaze_supported)
{
htc_face_tracker_lip = xr_session.create_htc_face_tracker(XR_FACIAL_TRACKING_TYPE_LIP_DEFAULT_HTC);
switch (guess_model())
{
case model::pico_4_pro:
case model::pico_4_enterprise:
spdlog::info(" PICO face tracking support: true");
face_tracker.emplace<xr::pico_face_tracker>(xr_instance, xr_session);
break;
default:
break;
}
}
if (pico_face_tracking_supported)
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}))
{
pico_face_tracker = xr_session.create_pico_face_tracker();
XrSystemBodyTrackingPropertiesFB fb_body_properties = xr_system_id.fb_body_tracking_properties();
spdlog::info(" FB body tracking support: {}", (bool)fb_body_properties.supportsBodyTracking);
if (fb_body_properties.supportsBodyTracking)
body_tracker.emplace<xr::fb_body_tracker>(xr_instance, xr_session);
}
if (fb_body_tracking_supported)
if (std::holds_alternative<std::monostate>(body_tracker) && utils::contains_all(xr_extensions, std::array{XR_HTC_PATH_ENUMERATION_EXTENSION_NAME, XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME}))
{
fb_body_tracker = xr_session.create_fb_body_tracker();
// HACK: always have an active body tracker so the quest runtime doesn't blow up (crash in random functions, controllers not working)
fb_body_tracker.start(false, false);
spdlog::info(" HTC body tracking support: true");
body_tracker.emplace<xr::htc_body_tracker>(xr_instance, xr_session);
}
if (pico_body_tracking_supported)
if (std::holds_alternative<std::monostate>(body_tracker) && utils::contains(xr_extensions, XR_BD_BODY_TRACKING_EXTENSION_NAME))
{
pico_body_tracker = xr_session.create_pico_body_tracker();
XrSystemBodyTrackingPropertiesBD bd_body_properties = xr_system_id.bd_body_tracking_properties();
spdlog::info(" PICO body tracking support: {}", (bool)bd_body_properties.supportsBodyTracking);
if (bd_body_properties.supportsBodyTracking)
body_tracker.emplace<xr::pico_body_tracker>(xr_instance, xr_session);
}
vk::CommandPoolCreateInfo cmdpool_create_info;
@@ -1769,7 +1875,13 @@ void application::poll_events()
exit_requested = true;
}
break;
case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED:
case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: {
if (auto * htc_body = std::get_if<xr::htc_body_tracker>(&body_tracker))
{
htc_body->update_active();
}
}
break;
case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING:
break;
case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
+27 -72
View File
@@ -19,19 +19,22 @@
#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 "wifi_lock.h"
#include "xr/fb_body_tracker.h"
#include "xr/fb_face_tracker2.h"
#include "xr/hand_tracker.h"
#include "xr/htc_body_tracker.h"
#include "xr/htc_face_tracker.h"
#include "xr/pico_body_tracker.h"
#include "xr/pico_face_tracker.h"
#include "xr/xr.h"
#include <atomic>
#include <boost/locale/generator.hpp>
@@ -103,7 +106,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;
@@ -127,21 +130,8 @@ class application : public singleton<application>
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::variant<std::monostate, xr::fb_face_tracker2, xr::htc_face_tracker, xr::pico_face_tracker> face_tracker;
std::variant<std::monostate, xr::fb_body_tracker, xr::htc_body_tracker, xr::pico_body_tracker> body_tracker;
bool eye_gaze_supported = false;
@@ -371,7 +361,7 @@ public:
return instance().vk_queue_family_index;
}
static vk::raii::Queue & get_queue()
static thread_safe<vk::raii::Queue> & get_queue()
{
return instance().vk_queue;
}
@@ -431,34 +421,14 @@ public:
return instance().hand_tracking_supported;
}
static bool get_fb_face_tracking2_supported()
static bool get_face_tracking_supported()
{
return instance().fb_face_tracking2_supported;
return !std::holds_alternative<std::monostate>(instance().face_tracker);
}
static bool get_htc_face_tracking_eye_supported()
static bool get_body_tracking_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;
return !std::holds_alternative<std::monostate>(instance().body_tracker);
}
static bool get_eye_gaze_supported()
@@ -481,34 +451,14 @@ public:
return instance().right_hand;
}
static xr::fb_face_tracker2 & get_fb_face_tracker2()
static auto & get_face_tracker()
{
return instance().fb_face_tracker2;
return instance().face_tracker;
}
static xr::htc_face_tracker & get_htc_face_tracker_eye()
static auto & get_body_tracker()
{
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;
return instance().body_tracker;
}
static const std::vector<std::string> & get_xr_extensions()
@@ -527,6 +477,11 @@ 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;
+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) {}
};
+28 -12
View File
@@ -106,18 +106,17 @@ bool configuration::check_feature(feature f) const
{
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()))
if (not std::holds_alternative<xr::htc_face_tracker>(application::get_face_tracker()))
return false;
break;
case model::pico_4_pro:
case model::pico_4_enterprise:
if (not application::get_pico_face_tracking_supported())
if (not std::holds_alternative<xr::pico_face_tracker>(application::get_face_tracker()))
return false;
break;
default:
if (not application::get_fb_face_tracking2_supported())
if (not std::holds_alternative<xr::fb_face_tracker2>(application::get_face_tracker()))
return false;
break;
}
@@ -127,7 +126,13 @@ bool configuration::check_feature(feature f) const
{
case model::meta_quest_3:
case model::meta_quest_3s:
if (not application::get_fb_body_tracking_supported())
if (not std::holds_alternative<xr::fb_body_tracker>(application::get_body_tracker()))
return false;
break;
case model::htc_vive_focus_3:
case model::htc_vive_xr_elite:
case model::htc_vive_focus_vision:
if (not std::holds_alternative<xr::htc_body_tracker>(application::get_body_tracker()))
return false;
break;
case model::pico_neo_3:
@@ -135,7 +140,7 @@ bool configuration::check_feature(feature f) const
case model::pico_4s:
case model::pico_4_pro:
case model::pico_4_enterprise:
if (not application::get_pico_body_tracking_supported())
if (not std::holds_alternative<xr::pico_body_tracker>(application::get_body_tracker()))
return false;
break;
default:
@@ -200,9 +205,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();
@@ -240,6 +242,18 @@ configuration::configuration(xr::system & system)
if (system.passthrough_supported() == xr::system::passthrough_type::no_passthrough)
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();
}
catch (std::exception & e)
{
@@ -252,7 +266,6 @@ configuration::configuration(xr::system & system)
resolution_scale = 1.4;
sgsr = {};
openxr_post_processing = {};
show_performance_metrics = false;
passthrough_enabled = system.passthrough_supported() == xr::system::passthrough_type::color;
}
}
@@ -338,8 +351,7 @@ 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)
@@ -356,5 +368,9 @@ void configuration::save()
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 << "}";
}
+7 -1
View File
@@ -50,7 +50,6 @@ 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;
@@ -78,6 +77,12 @@ 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;
bool check_feature(feature f) const;
void set_feature(feature f, bool state);
@@ -90,6 +95,7 @@ private:
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};
+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;
+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;
+178 -177
View File
@@ -289,32 +289,28 @@ 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 std::array layout_bindings = {
vk::DescriptorSetLayoutBinding{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
}};
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) :
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) :
physical_device(physical_device),
device(device),
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}),
ds_layout(device, vk::DescriptorSetLayoutCreateInfo{.bindingCount = layout_bindings.size(), .pBindings = layout_bindings.data()}),
descriptor_pool(device, ds_layout, layout_bindings),
renderpass(create_renderpass(device, swapchain.format(), true)),
command_pool(device,
vk::CommandPoolCreateInfo{
@@ -352,14 +348,14 @@ imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii:
.PhysicalDevice = *application::get_physical_device(),
.Device = *application::get_device(),
.QueueFamily = application::queue_family_index(),
.Queue = *application::get_queue(),
.DescriptorPool = *descriptor_pool,
.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 +378,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 +391,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 +410,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 +429,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 +459,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,29 +490,19 @@ static std::vector<std::string> find_font(ImFontGlyphRangesBuilder glyph_range_b
void imgui_context::initialize_fonts()
{
glyph_ranges.clear();
std::u16string sample_text = u"Hello world";
// 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);
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);
{
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);
if (it != glyph_set_per_language.end())
{
for (ImWchar c: it->second)
glyph_range_builder.AddChar(c);
}
}
glyph_range_builder.BuildRanges(&glyph_ranges);
if (it != glyph_set_per_language.end())
for (char16_t c: it->second)
sample_text += c;
// Load Fonts
auto fonts = find_font(glyph_range_builder, application::get_messages_info().language);
auto fonts = find_font(sample_text, application::get_messages_info().language);
for (auto & i: fonts)
{
spdlog::info("Font {}", i);
@@ -577,40 +511,20 @@ void imgui_context::initialize_fonts()
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 +541,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 +718,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::min((display_time - last_display_time) * 1e-9f, 0.0166f);
last_display_time = display_time;
// Uses the window list from last frame
@@ -831,7 +748,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 +761,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 +778,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 +908,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 +986,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);
@@ -1094,16 +1021,17 @@ imgui_context::~imgui_context()
}
ImTextureID imgui_context::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_context::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 +1040,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,6 +1061,24 @@ ImTextureID imgui_context::load_texture(const std::string & filename, vk::raii::
return id;
}
ImTextureID imgui_context::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_context::load_texture(const std::string & filename)
{
return load_texture(
@@ -1143,6 +1089,9 @@ 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,
},
});
@@ -1159,6 +1108,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 +1128,50 @@ 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;
}
+18 -9
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"
@@ -46,7 +48,7 @@ class imgui_context
{
vk::raii::Sampler sampler;
std::shared_ptr<vk::raii::ImageView> image_view;
vk::raii::DescriptorSet descriptor_set;
std::shared_ptr<vk::raii::DescriptorSet> descriptor_set;
};
public:
@@ -67,6 +69,8 @@ public:
XrAction scroll; // XR_ACTION_TYPE_VECTOR2F_INPUT
// TODO: thresholds?
XrAction haptic_output;
xr::hand_tracker * hand = nullptr;
};
@@ -116,11 +120,11 @@ private:
vk::raii::PhysicalDevice physical_device;
vk::raii::Device & device;
uint32_t queue_family_index;
vk::raii::Queue & queue;
thread_safe<vk::raii::Queue> & queue;
vk::raii::Pipeline pipeline = nullptr;
vk::raii::DescriptorPool descriptor_pool;
vk::raii::DescriptorSetLayout ds_layout;
growable_descriptor_pool descriptor_pool;
vk::raii::RenderPass renderpass;
vk::raii::CommandPool command_pool;
@@ -153,13 +157,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 +179,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 +196,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;
@@ -206,9 +209,15 @@ public:
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);
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);
};
+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());
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);
};
+361 -249
View File
@@ -21,7 +21,7 @@
#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"
@@ -29,6 +29,8 @@
#include "vk/pipeline.h"
#include "vk/shader.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>
@@ -37,6 +39,8 @@
#include <ranges>
#include <spdlog/spdlog.h>
#include <vk_mem_alloc.h>
#include <vulkan/vulkan_enums.hpp>
#include <vulkan/vulkan_structs.hpp>
extern const std::map<std::string, std::vector<uint32_t>> shaders;
@@ -74,7 +78,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 +103,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 +202,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 +238,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 +257,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 +299,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 +321,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 +361,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 +417,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,7 +528,7 @@ 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");
@@ -580,18 +590,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 +599,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 +619,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 +706,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 +719,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 +745,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 +797,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)
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 +880,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 +934,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 +960,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 +1014,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 +1024,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;
}
+398 -1
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),
@@ -40,7 +51,46 @@ scene::scene(key, const meta & current_meta) :
queue_family_index(application::instance().vk_queue_family_index),
current_meta(current_meta)
{
passthrough_supported = system.passthrough_supported();
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 +103,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, application::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 &) {}
+103 -5
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;
};
@@ -80,12 +89,24 @@ protected:
vk::raii::Instance & vk_instance;
vk::raii::Device & device;
vk::raii::PhysicalDevice & physical_device;
vk::raii::Queue & queue;
thread_safe<vk::raii::Queue> & queue;
vk::raii::CommandPool & commandpool;
uint32_t queue_family_index;
const meta & current_meta;
std::optional<scene_renderer> renderer;
public:
std::optional<scene_loader> loader;
protected:
vk::Format swapchain_format;
vk::Format depth_format;
xr::system::passthrough_type passthrough_supported;
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 +117,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 +222,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;
}
+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);
};
+287 -578
View File
File diff suppressed because it is too large Load Diff
+25 -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 "wivrn_packets.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,27 @@ 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::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 +95,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,12 +113,17 @@ 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;
ImTextureID default_icon;
std::unordered_map<std::string, ImTextureID> app_icons;
XrTime timestamp_start_application{};
virtual_keyboard keyboard;
@@ -146,6 +140,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 +149,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);
};
+415 -147
View File
@@ -16,8 +16,17 @@
* 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 "constants.h"
#include "utils/overloaded.h"
#include "xr/fb_body_tracker.h"
#include "xr/fb_face_tracker2.h"
#include "xr/htc_body_tracker.h"
#include "xr/pico_body_tracker.h"
#include "xr/space.h"
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/quaternion.hpp>
#include <magic_enum.hpp>
#include <openxr/openxr.h>
#define GLM_FORCE_RADIANS
#include "stream.h"
@@ -113,14 +122,39 @@ static const std::unordered_map<std::string, device_id> device_ids = {
{"/user/hand/right/input/trackpad/force", device_id::RIGHT_TRACKPAD_FORCE},
{"/user/hand/right/input/stylus/force", device_id::RIGHT_STYLUS_FORCE},
{"/user/hand/right/input/stylus_fb/force", device_id::RIGHT_STYLUS_FORCE},
// XR_EXT_hand_interaction
{"/user/hand/left/input/pinch_ext/value", device_id::LEFT_PINCH_VALUE},
{"/user/hand/left/input/pinch_ext/ready_ext", device_id::LEFT_PINCH_READY},
{"/user/hand/left/input/aim_activate_ext/value",device_id::LEFT_AIM_ACTIVATE_VALUE},
{"/user/hand/left/input/aim_activate_ext/ready_ext",device_id::LEFT_AIM_ACTIVATE_READY},
{"/user/hand/left/input/grasp_ext/value", device_id::LEFT_GRASP_VALUE},
{"/user/hand/left/input/grasp_ext/ready_ext", device_id::LEFT_GRASP_READY},
{"/user/hand/right/input/pinch_ext/value", device_id::RIGHT_PINCH_VALUE},
{"/user/hand/right/input/pinch_ext/ready_ext", device_id::RIGHT_PINCH_READY},
{"/user/hand/right/input/aim_activate_ext/value",device_id::RIGHT_AIM_ACTIVATE_VALUE},
{"/user/hand/right/input/aim_activate_ext/ready_ext",device_id::RIGHT_AIM_ACTIVATE_READY},
{"/user/hand/right/input/grasp_ext/value", device_id::RIGHT_GRASP_VALUE},
{"/user/hand/right/input/grasp_ext/ready_ext", device_id::RIGHT_GRASP_READY},
};
// clang-format on
static const std::array supported_formats = {
static const std::array supported_color_formats = {
vk::Format::eR8G8B8A8Srgb,
vk::Format::eB8G8R8A8Srgb,
};
static const std::array supported_depth_formats{
vk::Format::eD32Sfloat,
vk::Format::eX8D24UnormPack32,
};
scenes::stream::stream() :
scene_impl<stream>(supported_color_formats, supported_depth_formats)
{
}
static from_headset::visibility_mask_changed::masks get_visibility_mask(xr::instance & inst, xr::session & session, int view)
{
assert(inst.has_extension(XR_KHR_VISIBILITY_MASK_EXTENSION_NAME));
@@ -155,7 +189,11 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
self->network_session = std::move(network_session);
self->network_session->send_control([&]() {
from_headset::headset_info_packet info{};
from_headset::headset_info_packet info{
.language = application::get_messages_info().language,
.country = application::get_messages_info().country,
.variant = application::get_messages_info().variant,
};
auto view = self->system.view_configuration_views(self->viewconfig)[0];
view = override_view(view, guess_model());
@@ -217,30 +255,35 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
if (config.check_feature(feature::face_tracking))
{
if (application::get_fb_face_tracking2_supported())
info.face_tracking = from_headset::face_type::fb2;
else if (application::get_htc_face_tracking_eye_supported() or application::get_htc_face_tracking_lip_supported())
info.face_tracking = from_headset::face_type::htc;
else if (application::get_pico_face_tracking_supported())
info.face_tracking = from_headset::face_type::pico;
info.face_tracking = std::visit(utils::overloaded{
[](std::monostate &) {
return from_headset::face_type::none;
},
[](xr::fb_face_tracker2 &) {
return from_headset::face_type::fb2;
},
[](xr::htc_face_tracker &) {
return from_headset::face_type::htc;
},
[](xr::pico_face_tracker &) {
return from_headset::face_type::fb2;
},
},
application::get_face_tracker());
}
info.num_generic_trackers = 0;
if (config.check_feature(feature::body_tracking))
{
if (application::get_fb_body_tracking_supported())
{
auto num_trackers = config.fb_lower_body
? std::ranges::count_if(xr::fb_body_tracker::joint_whitelist, [&config](auto joint) {
return config.fb_hip || joint != XR_FULL_BODY_JOINT_HIPS_META;
})
: std::ranges::count_if(xr::fb_body_tracker::joint_whitelist, [](auto joint) {
return joint != XR_FULL_BODY_JOINT_HIPS_META && joint < XR_FULL_BODY_JOINT_LEFT_UPPER_LEG_META;
});
info.num_generic_trackers = num_trackers;
}
else if (application::get_pico_body_tracking_supported())
info.num_generic_trackers = xr::pico_body_tracker::joint_whitelist.size();
info.num_generic_trackers = std::visit(utils::overloaded{
[&](std::monostate &) {
return size_t(0);
},
[&](auto & b) {
return b.count();
},
},
application::get_body_tracker());
}
info.palm_pose = application::space(xr::spaces::palm_left) or application::space(xr::spaces::palm_right);
@@ -259,12 +302,33 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
{
for (uint8_t view = 0; view < view_count; ++view)
{
self->network_session->send_control(from_headset::visibility_mask_changed{
.data = get_visibility_mask(self->instance, self->session, view),
.view_index = view});
try
{
self->network_session->send_control(from_headset::visibility_mask_changed{
.data = get_visibility_mask(self->instance, self->session, view),
.view_index = view});
}
catch (std::exception & e)
{
spdlog::warn("Failed to get visibility mask: ", e.what());
}
}
}
{
const auto & config = application::get_config();
self->override_foveation_enable = config.override_foveation_enable;
self->override_foveation_pitch = config.override_foveation_pitch;
self->override_foveation_distance = config.override_foveation_distance;
if (self->override_foveation_enable)
self->network_session->send_control(from_headset::override_foveation_center{
.enabled = self->override_foveation_enable,
.pitch = self->override_foveation_pitch,
.distance = self->override_foveation_distance,
});
}
self->network_thread = utils::named_thread("network_thread", &stream::process_packets, self.get());
self->command_buffer = std::move(self->device.allocateCommandBuffers({
@@ -310,25 +374,6 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
self->input_actions.emplace_back(it->second, action, action_type);
}
self->swapchain_format = vk::Format::eUndefined;
spdlog::info("Supported swapchain formats:");
for (auto format: self->session.get_swapchain_formats())
{
spdlog::info(" {}", vk::to_string(format));
}
for (auto format: self->session.get_swapchain_formats())
{
if (std::find(supported_formats.begin(), supported_formats.end(), format) != supported_formats.end())
{
self->swapchain_format = format;
break;
}
}
if (self->swapchain_format == vk::Format::eUndefined)
throw std::runtime_error("No supported swapchain format");
spdlog::info("Using format {}", vk::to_string(self->swapchain_format));
self->query_pool = vk::raii::QueryPool(
@@ -344,42 +389,107 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
void scenes::stream::on_focused()
{
if (application::get_config().show_performance_metrics)
gui_status_last_change = application::now();
auto views = system.view_configuration_views(viewconfig);
// stream_view = override_view(views[0], guess_model());
width = views[0].recommendedImageRectWidth;
height = views[0].recommendedImageRectHeight;
renderer.emplace(device, physical_device, queue, commandpool);
loader.emplace(device, physical_device, queue, application::queue_family_index(), renderer->get_default_material());
std::string profile = controller_name();
input.emplace(
*this,
"controllers/" + profile + "/profile.json",
layer_controllers,
layer_rays);
spdlog::info("Loaded input profile {}", input->id);
for (auto i: {xr::spaces::aim_left, xr::spaces::aim_right, xr::spaces::grip_left, xr::spaces::grip_right})
{
swapchain_imgui = xr::swapchain(
session,
device,
swapchain_format,
1500,
1000);
auto [p, q] = input->offset[i] = controller_offset(controller_name(), i);
imgui_context::viewport vp{
.space = xr::spaces::view,
.position = {0, 0, -1},
.orientation = {1, 0, 0, 0},
.size = {1.0, 0.6666},
.vp_origin = {0, 0},
.vp_size = {1500, 1000},
};
imgui_ctx.emplace(physical_device,
device,
queue_family_index,
queue,
std::span<imgui_context::controller>{},
swapchain_imgui,
std::vector{vp});
plots_toggle_1 = get_action("plots_toggle_1").first;
plots_toggle_2 = get_action("plots_toggle_2").first;
auto rot = glm::degrees(glm::eulerAngles(q));
spdlog::info("Initializing offset of space {} to ({}, {}, {}) mm, ({}, {}, {})°",
magic_enum::enum_name(i),
1000 * p.x,
1000 * p.y,
1000 * p.z,
rot.x,
rot.y,
rot.z);
}
std::array imgui_inputs{
imgui_context::controller{
.aim = get_action_space("left_aim"),
.offset = input->offset[xr::spaces::aim_left],
.trigger = get_action("left_trigger").first,
.squeeze = get_action("left_squeeze").first,
.scroll = get_action("left_scroll").first,
.haptic_output = get_action("left_haptic").first,
},
imgui_context::controller{
.aim = get_action_space("right_aim"),
.offset = input->offset[xr::spaces::aim_right],
.trigger = get_action("right_trigger").first,
.squeeze = get_action("right_squeeze").first,
.scroll = get_action("right_scroll").first,
.haptic_output = get_action("right_haptic").first,
},
};
swapchain_imgui = xr::swapchain(
session,
device,
swapchain_format,
1800,
1000);
imgui_context::viewport vp{
.space = xr::spaces::world,
// Position and orientation are set at each frame
.size = {1.2, 0.6666},
.vp_origin = {0, 0},
.vp_size = {1800, 1000},
};
imgui_ctx.emplace(physical_device,
device,
queue_family_index,
queue,
imgui_inputs,
swapchain_imgui,
std::vector{vp});
plots_toggle_1 = get_action("plots_toggle_1").first;
plots_toggle_2 = get_action("plots_toggle_2").first;
recenter_left = get_action("recenter_left").first;
recenter_right = get_action("recenter_right").first;
foveation_pitch = get_action("foveation_pitch").first;
foveation_distance = get_action("foveation_distance").first;
foveation_ok = get_action("foveation_ok").first;
foveation_cancel = get_action("foveation_cancel").first;
assert(video_stream_description);
setup_reprojection_swapchain();
std::unique_lock lock(decoder_mutex);
setup_reprojection_swapchain(
video_stream_description->defoveated_width / view_count,
video_stream_description->defoveated_height);
}
void scenes::stream::on_unfocused()
{
renderer->wait_idle(); // Must be before the scene data because the renderer uses its descriptor sets
world.clear(); // Must be cleared before the renderer so that the descriptor sets are freed before their pools
input.reset();
loader.reset();
renderer.reset();
clear_swapchains();
imgui_ctx.reset();
swapchain_imgui = xr::swapchain();
}
@@ -551,6 +661,78 @@ std::shared_ptr<shard_accumulator::blit_handle> scenes::stream::accumulator_imag
return nullptr;
}
void scenes::stream::update_gui_position(xr::spaces controller)
{
auto aim = application::locate_controller(
application::space(controller),
application::space(xr::spaces::view),
predicted_display_time);
if (not aim)
return;
auto [offset_position, offset_orientation] = input->offset[controller];
auto head_controller_position = aim->first + glm::mat3_cast(aim->second * offset_orientation) * offset_position;
auto head_controller_orientation = aim->second * offset_orientation;
auto head_controller_direction = -glm::column(glm::mat3_cast(head_controller_orientation), 2);
if (not recentering_context)
{
// First frame of recentering: get the GUI position relative to the controller
// Compute the intersection of the ray with the GUI
auto gui_controller_direction = glm::conjugate(head_gui_orientation) * head_controller_direction;
auto gui_controller_position = glm::conjugate(head_gui_orientation) * (head_controller_position - head_gui_position);
float lambda = -gui_controller_position.z / gui_controller_direction.z;
auto gui_intersection = gui_controller_position + lambda * gui_controller_direction;
auto viewport_size = imgui_ctx->layers()[0].size;
if (std::isnan(lambda) or lambda < 0 or
std::abs(gui_intersection.x) > viewport_size.x / 2 or
std::abs(gui_intersection.y) > viewport_size.y / 2)
{
// Reset the relative GUI position if the ray does not intersect
recentering_context.emplace(controller, glm::vec3{0, 0, -1}, glm::quat{1, 0, 0, 0});
}
else
{
glm::vec3 controller_gui_position = glm::conjugate(head_controller_orientation) * (head_gui_position - head_controller_position);
glm::quat controller_gui_orientation = glm::conjugate(head_controller_orientation) * head_gui_orientation;
recentering_context.emplace(controller, controller_gui_position, controller_gui_orientation);
}
}
else
{
// Subsequent frames of recentering: keep the GUI locked to the controller
auto [_, controller_gui_position, controller_gui_orientation] = *recentering_context;
head_gui_position = head_controller_position + head_controller_orientation * controller_gui_position;
head_gui_orientation = head_controller_orientation * controller_gui_orientation;
}
}
bool scenes::stream::is_gui_interactable() const
{
switch (gui_status)
{
case gui_status::stats:
case gui_status::settings:
case gui_status::foveation_settings:
return true;
case gui_status::hidden:
case gui_status::overlay_only:
case gui_status::compact:
return false;
}
assert(false);
__builtin_unreachable();
}
void scenes::stream::render(const XrFrameState & frame_state)
{
if (exiting)
@@ -579,7 +761,15 @@ void scenes::stream::render(const XrFrameState & frame_state)
}
if (state_ == state::stalled)
{
network_session->send_control(from_headset::get_application_list{
.language = application::get_messages_info().language,
.country = application::get_messages_info().country,
.variant = application::get_messages_info().variant,
});
application::pop_scene();
}
assert(swapchain);
for (auto & i: decoders)
@@ -739,8 +929,6 @@ void scenes::stream::render(const XrFrameState & frame_state)
session.begin_frame();
int image_index = swapchain.acquire();
swapchain.wait();
std::array<int, view_count> image_indices;
command_buffer.reset();
@@ -880,40 +1068,62 @@ void scenes::stream::render(const XrFrameState & frame_state)
command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1);
XrExtent2Di extents[view_count];
{
int32_t max_width = 0;
int32_t max_height = 0;
for (size_t i = 0; i < view_count; ++i)
{
extents[i] = reprojector->defoveated_size(foveation[i]);
max_width = std::max(max_width, extents[i].width);
max_height = std::max(max_height, extents[i].height);
}
// If the defoveated image is larger than the swapchain, try to reallocate one
if (swapchain.width() < max_width or swapchain.height() < max_height)
{
try
{
spdlog::info("Recreating swapchain, from {}x{} to {}x{}",
swapchain.width(),
swapchain.height(),
max_width,
max_height);
setup_reprojection_swapchain(max_width, max_height);
}
catch (std::exception & e)
{
spdlog::warn("failed to increase swapchain size");
for (size_t i = 0; i < view_count; ++i)
{
extents[i].width = std::min(extents[i].width, swapchain.width());
extents[i].height = std::min(extents[i].height, swapchain.height());
}
}
}
}
// defoveate the image
auto extents = reprojector->reproject(command_buffer, foveation, image_index);
int image_index = swapchain.acquire();
swapchain.wait();
reprojector->reproject(command_buffer, foveation, image_index);
command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 2);
command_buffer.end();
vk::SubmitInfo submit_info;
submit_info.setCommandBuffers(*command_buffer);
queue.submit(submit_info, *fence);
queue.lock()->submit(submit_info, *fence);
swapchain.release();
XrEnvironmentBlendMode blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
std::vector<XrCompositionLayerBaseHeader *> layers_base;
std::vector<XrCompositionLayerProjectionView> layer_view(view_count);
if (use_alpha)
{
session.enable_passthrough(system);
std::visit(
utils::overloaded{
[&](std::monostate &) {
assert(false);
},
[&](xr::passthrough_alpha_blend & p) {
blend_mode = XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND;
},
[&](auto & p) {
layers_base.push_back(p.layer());
}},
session.get_passthrough());
}
else
session.disable_passthrough();
swapchain.release();
render_start(use_alpha, frame_state.predictedDisplayTime);
// Add the layer with the streamed content
for (uint32_t view = 0; view < view_count; view++)
{
layer_view[view] =
@@ -932,45 +1142,47 @@ void scenes::stream::render(const XrFrameState & frame_state)
},
};
}
add_projection_layer(
XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT,
application::space(xr::spaces::world),
std::move(layer_view));
XrCompositionLayerProjection layer{
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION,
.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT,
.space = application::space(xr::spaces::world),
.viewCount = (uint32_t)layer_view.size(),
.views = layer_view.data(),
};
XrCompositionLayerSettingsFB settings;
const configuration::openxr_post_processing_settings openxr_post_processing = application::get_config().openxr_post_processing;
if ((openxr_post_processing.sharpening | openxr_post_processing.super_sampling) > 0)
if (composition_layer_color_scale_bias_supported)
{
settings = {
.type = XR_TYPE_COMPOSITION_LAYER_SETTINGS_FB,
.layerFlags = openxr_post_processing.sharpening | openxr_post_processing.super_sampling,
};
layer.next = &settings;
switch (gui_status)
{
case gui_status::hidden:
case gui_status::foveation_settings:
case gui_status::compact:
case gui_status::overlay_only:
dimming = dimming - frame_state.predictedDisplayPeriod / (1e9 * constants::stream::fade_duration);
break;
case gui_status::stats:
case gui_status::settings:
dimming = dimming + frame_state.predictedDisplayPeriod / (1e9 * constants::stream::fade_duration);
break;
}
dimming = std::clamp<float>(dimming, 0, 1);
float x = dimming * dimming * (3 - 2 * dimming); // Easing function
float scale = std::lerp(1, constants::stream::dimming_scale, x);
float bias = std::lerp(0, constants::stream::dimming_bias, x);
set_color_scale_bias({scale, scale, scale, 1}, {bias, bias, bias, 0});
}
std::vector<XrCompositionLayerQuad> imgui_layers;
if (imgui_ctx)
{
accumulate_metrics(frame_state.predictedDisplayTime, current_blit_handles, timestamps);
if (plots_visible)
imgui_layers = plot_performance_metrics(frame_state.predictedDisplayTime);
}
if (const configuration::openxr_post_processing_settings openxr_post_processing = application::get_config().openxr_post_processing;
(openxr_post_processing.sharpening | openxr_post_processing.super_sampling) > 0)
set_layer_settings(openxr_post_processing.sharpening | openxr_post_processing.super_sampling);
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
accumulate_metrics(frame_state.predictedDisplayTime, current_blit_handles, timestamps);
if (imgui_ctx and plots_visible)
{
for (auto & layer: imgui_layers)
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
}
draw_gui(frame_state.predictedDisplayTime, frame_state.predictedDisplayPeriod);
try
{
session.end_frame(frame_state.predictedDisplayTime, layers_base, blend_mode);
render_end();
}
catch (std::system_error & e)
{
@@ -1026,7 +1238,22 @@ void scenes::stream::render(const XrFrameState & frame_state)
CHECK_XR(xrGetActionStateBoolean(session, &get_info, &state_2));
if (state_1.currentState and state_2.currentState and (state_1.changedSinceLastSync or state_2.changedSinceLastSync))
plots_visible = not plots_visible;
{
switch (gui_status)
{
case gui_status::hidden:
case gui_status::compact:
case gui_status::overlay_only:
gui_status = gui_status::stats;
break;
case gui_status::stats:
case gui_status::settings:
case gui_status::foveation_settings:
gui_status = gui_status::hidden;
break;
}
}
}
query_pool_filled = true;
@@ -1168,16 +1395,13 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript
}
}
void scenes::stream::setup_reprojection_swapchain()
void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint32_t swapchain_height)
{
std::unique_lock lock(decoder_mutex);
device.waitIdle();
session.set_refresh_rate(video_stream_description->fps);
const uint32_t video_width = video_stream_description->width / view_count;
const uint32_t video_height = video_stream_description->height;
uint32_t swapchain_width = video_stream_description->defoveated_width / view_count;
uint32_t swapchain_height = video_stream_description->defoveated_height;
const configuration::sgsr_settings sgsr = application::get_config().sgsr;
if (sgsr.enabled)
@@ -1220,40 +1444,68 @@ scene::meta & scenes::stream::get_meta_scene()
static meta m{
.name = "Stream",
.actions = {
{"left_aim", XR_ACTION_TYPE_POSE_INPUT},
{"left_trigger", XR_ACTION_TYPE_FLOAT_INPUT},
{"left_squeeze", XR_ACTION_TYPE_FLOAT_INPUT},
{"left_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT},
{"left_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"right_aim", XR_ACTION_TYPE_POSE_INPUT},
{"right_trigger", XR_ACTION_TYPE_FLOAT_INPUT},
{"right_squeeze", XR_ACTION_TYPE_FLOAT_INPUT},
{"right_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT},
{"right_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"plots_toggle_1", XR_ACTION_TYPE_BOOLEAN_INPUT},
{"plots_toggle_2", XR_ACTION_TYPE_BOOLEAN_INPUT},
{"recenter_left", XR_ACTION_TYPE_BOOLEAN_INPUT},
{"recenter_right", XR_ACTION_TYPE_BOOLEAN_INPUT},
{"foveation_pitch", XR_ACTION_TYPE_FLOAT_INPUT},
{"foveation_distance", XR_ACTION_TYPE_FLOAT_INPUT},
{"foveation_ok", XR_ACTION_TYPE_BOOLEAN_INPUT},
{"foveation_cancel", XR_ACTION_TYPE_BOOLEAN_INPUT},
},
.bindings = {
suggested_binding{
"/interaction_profiles/oculus/touch_controller",
{
"/interaction_profiles/oculus/touch_controller",
"/interaction_profiles/facebook/touch_controller_pro",
"/interaction_profiles/meta/touch_pro_controller",
"/interaction_profiles/meta/touch_controller_plus",
"/interaction_profiles/meta/touch_plus_controller",
"/interaction_profiles/bytedance/pico_neo3_controller",
"/interaction_profiles/bytedance/pico4_controller",
"/interaction_profiles/bytedance/pico4s_controller",
"/interaction_profiles/htc/vive_focus3_controller",
},
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/trigger/value"},
{"left_squeeze", "/user/hand/left/input/squeeze/value"},
{"left_scroll", "/user/hand/left/input/thumbstick"},
{"left_haptic", "/user/hand/left/output/haptic"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/trigger/value"},
{"right_squeeze", "/user/hand/right/input/squeeze/value"},
{"right_scroll", "/user/hand/right/input/thumbstick"},
{"right_haptic", "/user/hand/right/output/haptic"},
{"recenter_left", "/user/hand/left/input/squeeze/value"},
{"recenter_right", "/user/hand/right/input/squeeze/value"},
{"foveation_pitch", "/user/hand/right/input/thumbstick/y"},
{"foveation_distance", "/user/hand/left/input/thumbstick/y"},
{"foveation_ok", "/user/hand/right/input/a/click"},
{"foveation_cancel", "/user/hand/right/input/b/click"},
{"plots_toggle_1", "/user/hand/left/input/thumbstick/click"},
{"plots_toggle_2", "/user/hand/right/input/thumbstick/click"},
},
},
suggested_binding{
"/interaction_profiles/bytedance/pico_neo3_controller",
{
{"plots_toggle_1", "/user/hand/left/input/thumbstick/click"},
{"plots_toggle_2", "/user/hand/right/input/thumbstick/click"},
"/interaction_profiles/khr/simple_controller",
},
},
suggested_binding{
"/interaction_profiles/bytedance/pico4_controller",
{
{"plots_toggle_1", "/user/hand/left/input/thumbstick/click"},
{"plots_toggle_2", "/user/hand/right/input/thumbstick/click"},
},
},
suggested_binding{
"/interaction_profiles/htc/vive_focus3_controller",
{
{"plots_toggle_1", "/user/hand/left/input/thumbstick/click"},
{"plots_toggle_2", "/user/hand/right/input/thumbstick/click"},
},
},
suggested_binding{
"/interaction_profiles/khr/simple_controller",
{},
},
},
@@ -1282,6 +1534,22 @@ void scenes::stream::on_xr_event(const xr::event & event)
.view_index = uint8_t(event.visibility_mask_changed.viewIndex),
});
break;
case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED:
// Override session state if the GUI is interactable
if (event.state_changed.state == XR_SESSION_STATE_FOCUSED and is_gui_interactable())
network_session->send_control(from_headset::session_state_changed{
.state = XR_SESSION_STATE_VISIBLE,
});
else
network_session->send_control(from_headset::session_state_changed{
.state = event.state_changed.state,
});
break;
case XR_TYPE_EVENT_DATA_USER_PRESENCE_CHANGED_EXT:
network_session->send_control(from_headset::user_presence_changed{
.present = (bool)event.user_presence_changed.isUserPresent,
});
break;
case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED:
on_interaction_profile_changed(event.interaction_profile_changed);
break;
+81 -9
View File
@@ -21,13 +21,16 @@
#include "audio/audio.h"
#include "decoder/shard_accumulator.h"
#include "imgui.h"
#include "render/imgui_impl.h"
#include "scene.h"
#include "scenes/input_profile.h"
#include "stream_reprojection.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 +49,13 @@ public:
};
static const size_t image_buffer_size = 3;
struct app
{
std::string id;
std::string name;
std::vector<std::byte> image;
};
private:
static const size_t view_count = 2;
@@ -104,8 +114,6 @@ private:
std::optional<stream_reprojection> reprojector;
std::optional<xr::passthrough> passthrough;
vk::raii::Fence fence = nullptr;
vk::raii::CommandBuffer command_buffer = nullptr;
@@ -122,19 +130,63 @@ private:
xr::swapchain swapchain;
xr::swapchain swapchain_imgui;
vk::Format swapchain_format;
std::optional<audio> audio_handle;
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
};
bool is_gui_interactable() const;
std::atomic<gui_status> gui_status = gui_status::hidden;
enum gui_status last_gui_status = gui_status::hidden;
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;
// Last application list received from server
thread_safe<std::vector<app>> applications;
stream();
public:
~stream();
@@ -157,6 +209,8 @@ 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()(audio_data &&);
void push_blit_handle(wivrn::shard_accumulator * decoder, std::shared_ptr<wivrn::shard_accumulator::blit_handle> handle);
@@ -173,6 +227,13 @@ public:
return !exiting;
}
auto get_applications()
{
return applications.lock();
}
void start_application(std::string appid);
static meta & get_meta_scene();
private:
@@ -183,14 +244,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 +307,17 @@ 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 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));
+919
View File
@@ -0,0 +1,919 @@
/*
* 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 "constants.h"
#include "imgui.h"
#include "imgui_internal.h"
#include "implot.h"
#include "utils/i18n.h"
#include "utils/ranges.h"
#include <IconsFontAwesome6.h>
#include <chrono>
#include <cmath>
#include <glm/gtc/matrix_access.hpp>
#include <limits>
#include <ranges>
#include <spdlog/spdlog.h>
#include <openxr/openxr.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;
// Sometimes the render function can be called with almost the same predicted_display_time,
// which can cause issues with the bandwidth estimation.
if (dt < 0.001f)
return;
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;
// Filter more aggressively for the compact view
compact_bandwidth_rx = 0.99 * compact_bandwidth_rx + 0.01 * float(rx - bytes_received) / dt;
compact_bandwidth_tx = 0.99 * compact_bandwidth_tx + 0.01 * float(tx - bytes_sent) / dt;
compact_cpu_time = 0.99 * compact_cpu_time + 0.01 * application::get_cpu_time().count() * 1e-9f;
compact_gpu_time = 0.99 * compact_gpu_time + 0.01 * timestamps.gpu_time;
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();
}
// TODO move in separate file, factorize with lobby_gui.cpp
static bool RadioButtonWithoutCheckBox(const std::string & label, bool active, ImVec2 size_arg)
{
ImGuiWindow * window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext & g = *GImGui;
const ImGuiStyle & style = g.Style;
const ImGuiID id = window->GetID(label.c_str());
const ImVec2 label_size = ImGui::CalcTextSize(label.c_str(), NULL, true);
const ImVec2 pos = window->DC.CursorPos;
ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
const ImRect bb(pos, pos + size);
ImGui::ItemSize(bb, style.FramePadding.y);
if (!ImGui::ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held);
ImGuiCol_ col;
if ((held && hovered) || active)
col = ImGuiCol_ButtonActive;
else if (hovered)
col = ImGuiCol_ButtonHovered;
else
col = ImGuiCol_Button;
ImGui::RenderNavHighlight(bb, id);
ImGui::RenderFrame(bb.Min, bb.Max, ImGui::GetColorU32(col), true, style.FrameRounding);
ImVec2 TextAlign{0, 0.5f};
ImGui::RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label.c_str(), NULL, &label_size, TextAlign, &bb);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label.c_str(), g.LastItemData.StatusFlags);
return pressed;
}
template <typename T, typename U>
static bool RadioButtonWithoutCheckBox(const std::string & label, T & v, U v_button, ImVec2 size_arg)
{
const bool pressed = RadioButtonWithoutCheckBox(label, v == v_button, size_arg);
if (pressed)
v = v_button;
return pressed;
}
void scenes::stream::gui_performance_metrics()
{
const ImGuiStyle & style = ImGui::GetStyle();
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 - 2 * ImGui::GetCurrentContext()->FontSize - 2 * 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))
{
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))
{
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());
if (is_gui_interactable())
ImGui::Text("%s", _S("Press the grip button to move the window"));
else
ImGui::Text("%s", _S("Press both thumbsticks to display the WiVRn window"));
}
}
void scenes::stream::gui_compact_view()
{
const auto & metrics = global_metrics[(metrics_offset + global_metrics.size() - 1) % global_metrics.size()];
if (ImGui::BeginTable("metrics", 2))
{
auto f = [&](const char * label, float value, const char * unit) {
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::Text("%s", label);
ImGui::TableNextColumn();
ImGui::Text("%.1f %s", value, unit);
};
f(_S("Download"), 8 * compact_bandwidth_rx * 1e-6, "Mbit/s");
f(_S("Upload"), 8 * compact_bandwidth_tx * 1e-6, "Mbit/s");
f(_S("CPU time"), compact_cpu_time * 1000, "ms");
f(_S("GPU time"), compact_gpu_time * 1000, "ms");
f(_S("Motion to photon latency"), std::chrono::duration_cast<std::chrono::microseconds>(tracking_control.max_offset).count() * 1e-3f, "ms");
ImGui::EndTable();
}
}
std::string openxr_post_processing_flag_name(XrCompositionLayerSettingsFlagsFB flag); // TODO declaration in a .h file
void scenes::stream::gui_settings()
{
auto & config = application::get_config();
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(20, 20));
if (application::get_openxr_post_processing_supported())
{
ImGui::Text("%s", _S("OpenXR post-processing"));
ImGui::Indent();
{
XrCompositionLayerSettingsFlagsFB current = config.openxr_post_processing.super_sampling;
if (ImGui::BeginCombo(_S("Supersampling"), openxr_post_processing_flag_name(current).c_str()))
{
const XrCompositionLayerSettingsFlagsFB selectable_options[]{
0,
XR_COMPOSITION_LAYER_SETTINGS_NORMAL_SUPER_SAMPLING_BIT_FB,
XR_COMPOSITION_LAYER_SETTINGS_QUALITY_SUPER_SAMPLING_BIT_FB};
for (XrCompositionLayerSettingsFlagsFB option: selectable_options)
{
if (ImGui::Selectable(openxr_post_processing_flag_name(option).c_str(), current == option, ImGuiSelectableFlags_SelectOnRelease))
{
spdlog::info("Setting OpenXR super sampling to {}", openxr_post_processing_flag_name(option));
config.openxr_post_processing.super_sampling = option;
config.save();
}
imgui_ctx->vibrate_on_hover();
}
ImGui::EndCombo();
}
imgui_ctx->vibrate_on_hover();
if (ImGui::IsItemHovered())
{
imgui_ctx->tooltip(_("Reduce flicker for high contrast edges.\nUseful when the input resolution is high compared to the headset display"));
}
}
{
XrCompositionLayerSettingsFlagsFB current = config.openxr_post_processing.sharpening;
if (ImGui::BeginCombo(_S("Sharpening"), openxr_post_processing_flag_name(current).c_str()))
{
const XrCompositionLayerSettingsFlagsFB selectable_options[]{
0,
XR_COMPOSITION_LAYER_SETTINGS_NORMAL_SHARPENING_BIT_FB,
XR_COMPOSITION_LAYER_SETTINGS_QUALITY_SHARPENING_BIT_FB};
for (XrCompositionLayerSettingsFlagsFB option: selectable_options)
{
if (ImGui::Selectable(openxr_post_processing_flag_name(option).c_str(), current == option, ImGuiSelectableFlags_SelectOnRelease))
{
spdlog::info("Setting OpenXR sharpening to {}", openxr_post_processing_flag_name(option));
config.openxr_post_processing.sharpening = option;
config.save();
}
imgui_ctx->vibrate_on_hover();
}
ImGui::EndCombo();
}
imgui_ctx->vibrate_on_hover();
if (ImGui::IsItemHovered())
{
imgui_ctx->tooltip(_("Improve clarity of high contrast edges and counteract blur.\nUseful when the input resolution is low compared to the headset display"));
}
}
ImGui::Unindent();
bool send_packet = false;
bool save_config = false;
ImGui::Text("%s", _S("Foveation center override"));
ImGui::Indent();
{
if (ImGui::Checkbox(_S("Enable"), &override_foveation_enable))
{
send_packet = true;
save_config = true;
}
imgui_ctx->vibrate_on_hover();
ImGui::BeginDisabled(!override_foveation_enable);
ImGui::Text("%s", fmt::format(_F("Height {:.1f} deg"), -override_foveation_pitch * 180 / M_PI).c_str());
ImGui::Text("%s", fmt::format(_F("Distance {:.2f} m"), override_foveation_distance).c_str());
if (ImGui::Button(_S("Default")))
{
override_foveation_distance = configuration{}.override_foveation_distance;
override_foveation_pitch = configuration{}.override_foveation_pitch;
send_packet = true;
save_config = true;
}
imgui_ctx->vibrate_on_hover();
ImGui::SameLine();
if (ImGui::Button(_S("Change")))
gui_status = gui_status::foveation_settings;
imgui_ctx->vibrate_on_hover();
ImGui::EndDisabled();
}
ImGui::Unindent();
if (send_packet)
{
network_session->send_control(from_headset::override_foveation_center{
.enabled = override_foveation_enable,
.pitch = override_foveation_pitch,
.distance = override_foveation_distance,
});
}
if (save_config)
{
auto & config = application::get_config();
config.override_foveation_enable = override_foveation_enable;
config.override_foveation_pitch = override_foveation_pitch;
config.override_foveation_distance = override_foveation_distance;
config.save();
}
}
ImGui::PopStyleVar();
}
void scenes::stream::gui_foveation_settings(float predicted_display_period)
{
ImGui::PushFont(nullptr, constants::gui::font_size_large);
ImGui::Text("%s", _S("Use the thumbsticks to move the foveation center"));
ImGui::Text("%s", _S("Press A to save or B to cancel"));
ImGui::Text("%s", fmt::format(_F("Height {:.1f} deg"), -override_foveation_pitch * 180 / M_PI).c_str());
ImGui::Text("%s", fmt::format(_F("Distance {:.2f} m"), override_foveation_distance).c_str());
ImGui::PopFont();
// Maximum speed 1 rad/s
float delta_pitch = application::read_action_float(foveation_pitch).value_or(std::pair{0, 0}).second * predicted_display_period;
// Maximum speed 2m/s @ 1m
float delta_distance = std::exp(std::log(2) * application::read_action_float(foveation_distance).value_or(std::pair{0, 0}).second * predicted_display_period);
override_foveation_pitch = std::clamp<float>(override_foveation_pitch + delta_pitch, -M_PI / 3, M_PI / 3);
override_foveation_distance = std::clamp<float>(override_foveation_distance * delta_distance, 0.5, 100);
bool ok = application::read_action_bool(foveation_ok).value_or(std::pair{0, false}).second;
bool cancel = application::read_action_bool(foveation_cancel).value_or(std::pair{0, false}).second;
if (ok)
{
gui_status = gui_status::settings;
// Save settings
auto & config = application::get_config();
config.override_foveation_enable = true;
config.override_foveation_pitch = override_foveation_pitch;
config.override_foveation_distance = override_foveation_distance;
config.save();
}
else if (cancel)
{
gui_status = gui_status::settings;
// Restore settings
const auto & config = application::get_config();
override_foveation_enable = config.override_foveation_enable;
override_foveation_pitch = config.override_foveation_pitch;
override_foveation_distance = config.override_foveation_distance;
}
network_session->send_control(from_headset::override_foveation_center{
.enabled = override_foveation_enable,
.pitch = override_foveation_pitch,
.distance = override_foveation_distance,
});
}
// Return the vector v such that dot(v, x) > 0 iff x is on the side where the composition layer is visible
static glm::vec4 compute_ray_limits(const XrPosef & pose, float margin = 0)
{
glm::quat q{
pose.orientation.w,
pose.orientation.x,
pose.orientation.y,
pose.orientation.z,
};
glm::vec3 p{
pose.position.x,
pose.position.y,
pose.position.z,
};
glm::vec3 normal = glm::column(glm::mat3_cast(q), 2);
return glm::vec4(normal, -glm::dot(p, normal) - margin);
}
void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicted_display_period)
{
bool interactable = true;
XrSpace world_space = application::space(xr::spaces::world);
auto views = session.locate_views(viewconfig, predicted_display_time, world_space).second;
switch (gui_status)
{
case gui_status::hidden:
case gui_status::foveation_settings:
case gui_status::overlay_only:
case gui_status::compact:
interactable = false;
break;
case gui_status::stats:
case gui_status::settings:
break;
}
imgui_ctx->set_controllers_enabled(interactable);
if (gui_status != last_gui_status)
{
last_gui_status = gui_status;
gui_status_last_change = predicted_display_time;
// Override session state if the GUI is interactable
if (not is_gui_interactable())
network_session->send_control(from_headset::session_state_changed{
.state = application::get_session_state(),
});
else if (application::get_session_state() == XR_SESSION_STATE_FOCUSED)
network_session->send_control(from_headset::session_state_changed{
.state = XR_SESSION_STATE_VISIBLE,
});
}
float alpha = 1;
if (gui_status == gui_status::hidden)
{
float t = (predicted_display_time - gui_status_last_change) * 1.e-9f;
alpha = std::clamp<float>(1 - (t - constants::stream::fade_delay) / constants::stream::fade_duration, 0, 1);
if (alpha == 0)
return;
}
// Lock the GUI position to the head, do it before displaying the GUI to avoid being off by one frame when gui_status changes
std::optional<std::pair<glm::vec3, glm::quat>> head_position = application::locate_controller(application::space(xr::spaces::view), world_space, predicted_display_time);
if (head_position)
{
glm::mat3 M = glm::mat3_cast(head_position->second);
switch (gui_status)
{
case gui_status::foveation_settings:
imgui_ctx->layers()[0].orientation = head_position->second;
imgui_ctx->layers()[0].position = head_position->first + M * glm::vec3{0, -override_foveation_distance * sin(override_foveation_pitch), -override_foveation_distance};
break;
case gui_status::hidden:
// Always use the same position for the GUI shortcut tip
imgui_ctx->layers()[0].orientation = head_position->second;
imgui_ctx->layers()[0].position = head_position->first + M * glm::vec3{0.0, -0.4, -1.0};
break;
case gui_status::overlay_only:
case gui_status::compact:
case gui_status::stats:
case gui_status::settings:
imgui_ctx->layers()[0].orientation = head_position->second * head_gui_orientation;
imgui_ctx->layers()[0].position = head_position->first + M * head_gui_position;
break;
}
}
const float tab_width = 300;
const ImVec2 margin_around_window{50, 50};
const ImGuiStyle & style = ImGui::GetStyle();
imgui_ctx->new_frame(predicted_display_time);
ImVec2 content_size{ImGui::GetMainViewport()->Size - ImVec2{tab_width, 0} - margin_around_window * 2};
ImVec2 content_center = margin_around_window + content_size / 2 + ImVec2{tab_width, 0};
bool display_tabs, always_auto_resize;
switch (gui_status)
{
case gui_status::overlay_only:
ImGui::SetNextWindowPos(content_center, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::SetNextWindowSize(content_size);
always_auto_resize = false;
display_tabs = false;
break;
case gui_status::hidden:
case gui_status::foveation_settings:
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->Size / 2, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
always_auto_resize = true;
display_tabs = false;
break;
case gui_status::compact:
ImGui::SetNextWindowPos(content_center, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
always_auto_resize = true;
display_tabs = false;
break;
case gui_status::stats:
case gui_status::settings:
ImGui::SetNextWindowPos(margin_around_window);
ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size - margin_around_window * 2);
always_auto_resize = false;
display_tabs = true;
break;
}
ImGui::PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0);
if (always_auto_resize)
{
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8});
ImGui::Begin("Compact view", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize);
}
else
{
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {0, 0});
ImGui::Begin("Stream settings", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
}
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {8, 8});
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10);
switch (gui_status)
{
case gui_status::hidden:
ImGui::Text("%s", _S("Press both thumbsticks to display the WiVRn window"));
break;
case gui_status::overlay_only:
ImGui::SetCursorPos({20, 20});
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0));
gui_performance_metrics();
ImGui::EndChild();
break;
case gui_status::compact:
gui_compact_view();
break;
case gui_status::stats:
ImGui::SetCursorPos({tab_width + 20, 20});
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0));
gui_performance_metrics();
ImGui::EndChild();
break;
case gui_status::settings:
ImGui::SetCursorPos({tab_width + 20, 20});
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0));
gui_settings();
ImGui::EndChild();
break;
case gui_status::foveation_settings:
gui_foveation_settings(predicted_display_period * 1.e-9f);
break;
}
ImGui::PopStyleVar(2); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_FrameRounding
if (display_tabs)
{
ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 255));
ImGui::SetCursorPos(style.WindowPadding);
{
ImGui::BeginChild("Tabs", {tab_width, ImGui::GetContentRegionMax().y - ImGui::GetWindowContentRegionMin().y});
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 10));
RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " " + _("Stats"), gui_status, gui_status::stats, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
RadioButtonWithoutCheckBox(ICON_FA_GEARS " " + _("Settings"), gui_status, gui_status::settings, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
int n_items_at_end = 4;
ImGui::SetCursorPosY(ImGui::GetContentRegionMax().y - n_items_at_end * ImGui::GetCurrentContext()->FontSize - (n_items_at_end * 2) * style.FramePadding.y - (n_items_at_end - 1) * style.ItemSpacing.y - style.WindowPadding.y);
RadioButtonWithoutCheckBox(ICON_FA_CHART_LINE " " + _("Statistics overlay"), gui_status, gui_status::overlay_only, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
RadioButtonWithoutCheckBox(ICON_FA_MINIMIZE " " + _("Compact view"), gui_status, gui_status::compact, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
RadioButtonWithoutCheckBox(ICON_FA_XMARK " " + _("Close"), gui_status, gui_status::hidden, {tab_width, 0});
imgui_ctx->vibrate_on_hover();
bool dummy = false;
if (RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " " + _("Disconnect"), dummy, true, {tab_width, 0}))
exit();
imgui_ctx->vibrate_on_hover();
ImGui::PopStyleVar(); // ImGuiStyleVar_FramePadding
ImGui::EndChild();
}
ImGui::PopStyleColor(); // ImGuiCol_ChildBg
}
ImGui::End();
ImGui::PopStyleVar(2); // ImGuiStyleVar_ChildBorderSize, ImGuiStyleVar_WindowPadding
auto layers = imgui_ctx->end_frame();
// Display controllers and handle recentering
if (interactable)
{
if (recentering_context)
{
xr::spaces controller = std::get<0>(*recentering_context);
bool state;
switch (controller)
{
case xr::spaces::aim_left:
state = application::read_action_bool(recenter_left).value_or(std::pair{0, false}).second;
break;
case xr::spaces::aim_right:
state = application::read_action_bool(recenter_right).value_or(std::pair{0, false}).second;
break;
default:
state = false;
break;
}
if (state)
update_gui_position(controller);
else
recentering_context.reset();
}
else if (auto state = application::read_action_bool(recenter_left); state and state->second)
update_gui_position(xr::spaces::aim_left);
else if (auto state = application::read_action_bool(recenter_right); state and state->second)
update_gui_position(xr::spaces::aim_right);
else
recentering_context.reset();
std::vector<glm::vec4> ray_limits;
for (auto [_, layer]: layers)
ray_limits.push_back(compute_ray_limits(layer.pose));
bool hide_left_controller = false;
bool hide_right_controller = false;
if (application::get_hand_tracking_supported())
{
auto left = application::get_left_hand().locate(world_space, predicted_display_time);
auto right = application::get_right_hand().locate(world_space, predicted_display_time);
if (left and xr::hand_tracker::check_flags(*left, XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT, 0))
hide_left_controller = true;
if (right and xr::hand_tracker::check_flags(*right, XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT, 0))
hide_right_controller = true;
}
input->apply(world, world_space, predicted_display_time, hide_left_controller, hide_right_controller, ray_limits);
// Add the layer with the controllers
if (composition_layer_depth_test_supported)
{
render_world(XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT,
world_space,
views,
width,
height,
true,
layer_controllers,
{});
set_depth_test(true, XR_COMPARE_OP_ALWAYS_FB);
}
}
// Add the layer with the GUI
for (auto [_, layer]: layers)
{
add_quad_layer(layer.layerFlags, layer.space, layer.eyeVisibility, layer.subImage, layer.pose, layer.size);
if (composition_layer_depth_test_supported)
set_depth_test(true, XR_COMPARE_OP_LESS_FB);
if (alpha < 1 and composition_layer_color_scale_bias_supported)
set_color_scale_bias({alpha, alpha, alpha, alpha}, {});
}
// Display the controller rays
if (interactable)
{
render_world(XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT,
world_space,
views,
width,
height,
composition_layer_depth_test_supported,
composition_layer_depth_test_supported ? layer_rays : layer_controllers | layer_rays,
{});
if (composition_layer_depth_test_supported)
set_depth_test(true, XR_COMPARE_OP_LESS_FB);
}
}
+40
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,37 @@ 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 && 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 scenes::stream::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);
}
void scenes::stream::start_application(std::string appid)
{
network_session->send_control(wivrn::from_headset::start_app{
.app_id = std::move(appid),
});
}
+32 -21
View File
@@ -390,15 +390,14 @@ static size_t required_vertices(const wivrn::to_headset::foveation_parameter & p
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)
void 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)
{
@@ -409,13 +408,6 @@ std::vector<XrExtent2Di> stream_reprojection::reproject(vk::raii::CommandBuffer
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);
@@ -425,7 +417,6 @@ std::vector<XrExtent2Di> stream_reprojection::reproject(vk::raii::CommandBuffer
{
// 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))
@@ -446,16 +437,16 @@ std::vector<XrExtent2Di> stream_reprojection::reproject(vk::raii::CommandBuffer
.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;
*vertices++ = {
.position = out * out_pixel_size - glm::vec2(1),
.uv = in * in_pixel_size,
};
*vertices++ = {
.position = out * out_pixel_size - glm::vec2(1),
.uv = in * in_pixel_size,
};
}
}
@@ -496,5 +487,25 @@ std::vector<XrExtent2Di> stream_reprojection::reproject(vk::raii::CommandBuffer
command_buffer.draw(required_vertices(foveation[view]), 1, 0, 0);
command_buffer.endRenderPass();
}
return out_extents;
}
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_reprojection::defoveated_size(const wivrn::to_headset::foveation_parameter & view) const
{
return {
count_pixels(view.x),
count_pixels(view.y),
};
}
+3 -1
View File
@@ -70,8 +70,10 @@ public:
stream_reprojection(const stream_reprojection &) = delete;
std::vector<XrExtent2Di> reproject(
void reproject(
vk::raii::CommandBuffer & command_buffer,
const std::array<wivrn::to_headset::foveation_parameter, 2> & foveation,
int destination);
XrExtent2Di defoveated_size(const wivrn::to_headset::foveation_parameter &) const;
};
-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;
}
+340 -206
View File
@@ -19,7 +19,10 @@
#include "application.h"
#include "stream.h"
#include "utils/overloaded.h"
#include "wivrn_packets.h"
#include "xr/fb_body_tracker.h"
#include <magic_enum.hpp>
#include <ranges>
#include <spdlog/spdlog.h>
#include <thread>
@@ -33,46 +36,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 +75,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 +235,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 +259,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 +290,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))
@@ -236,6 +377,7 @@ void scenes::stream::tracking()
std::vector<from_headset::tracking> tracking;
std::vector<from_headset::tracking> tracking_pool; // pre-allocated objects
std::vector<from_headset::hand_tracking> hands;
std::array<bool, 2> should_skip_simple_controllers{};
std::vector<from_headset::body_tracking> body;
std::vector<XrView> views;
@@ -243,43 +385,33 @@ 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))
const bool face_tracking = config.check_feature(feature::face_tracking);
auto & face_tracker = application::get_face_tracker();
if (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())
// 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.
if (auto * face_pico = std::get_if<xr::pico_face_tracker>(&face_tracker))
face_pico->start();
}
const bool body_tracking = config.check_feature(feature::body_tracking);
auto & body_tracker = application::get_body_tracker();
if (body_tracking)
{
if (auto * body_fb = std::get_if<xr::fb_body_tracker>(&body_tracker))
{
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();
// 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
body_fb->stop();
body_fb->start(config.fb_lower_body, config.fb_hip);
}
}
enum
{
body_none,
body_fb,
body_pico,
} body_tracking = body_none;
if (config.check_feature(feature::body_tracking))
{
if (application::get_fb_body_tracking_supported())
{
body_tracking = body_fb;
// We start the tracker on connection because there are toggleable settings.
// TODO maybe handle reconnection better, if the settings are changed 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;
}
locate_spaces_functor locate_spaces{instance, world_space};
on_interaction_profile_changed({});
@@ -332,80 +464,70 @@ 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)])
{
auto joints = locate_hands(application::get_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)])
{
auto joints = locate_hands(application::get_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);
if (body_tracking)
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);
if (face_tracking && control.enabled[size_t(tid::face)])
{
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,8 +630,8 @@ void scenes::stream::tracking()
}
}
if (face_tracking == from_headset::face_type::pico)
application::get_pico_face_tracker().stop();
if (auto * face_pico = std::get_if<xr::pico_face_tracker>(&face_tracker))
face_pico->stop();
}
void scenes::stream::operator()(to_headset::tracking_control && packet)
@@ -517,7 +639,7 @@ void scenes::stream::operator()(to_headset::tracking_control && packet)
std::lock_guard lock(tracking_control_mutex);
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);
@@ -541,6 +663,55 @@ static device_id derived_from(device_id target)
void scenes::stream::on_interaction_profile_changed(const XrEventDataInteractionProfileChanged &)
{
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,
@@ -549,6 +720,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));
@@ -611,52 +793,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;
+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
+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>
+28 -9
View File
@@ -17,12 +17,27 @@
*/
#include "fb_body_tracker.h"
#include "application.h"
#include "spdlog/spdlog.h"
#include "xr/meta_body_tracking_fidelity.h"
#include "xr/xr.h"
#include <ranges>
#include <openxr/openxr.h>
static_assert(xr::pico_body_tracker::joint_whitelist.size() <= wivrn::from_headset::body_tracking::max_tracked_poses);
static_assert(xr::fb_body_tracker::joint_whitelist.size() <= wivrn::from_headset::body_tracking::max_tracked_poses);
std::vector<XrFullBodyJointMETA> xr::fb_body_tracker::get_whitelisted_joints(bool full_body, bool hip)
{
auto whitelisted_joints = std::ranges::filter_view(xr::fb_body_tracker::joint_whitelist, [=](auto joint) {
if (!full_body && (joint == XR_FULL_BODY_JOINT_HIPS_META || joint >= XR_FULL_BODY_JOINT_LEFT_UPPER_LEG_META))
return false;
if (!hip && joint == XR_FULL_BODY_JOINT_HIPS_META)
return false;
return true;
});
return {whitelisted_joints.begin(), whitelisted_joints.end()};
}
xr::fb_body_tracker::fb_body_tracker(instance & inst, session & s) :
s(s)
@@ -55,13 +70,23 @@ void xr::fb_body_tracker::start(bool full_body, bool hip)
// Enable IOBT.
CHECK_XR(xrRequestBodyTrackingFidelityMETA(handle, XR_BODY_TRACKING_FIDELITY_HIGH_META));
whitelisted_joints = get_whitelisted_joints(full_body, hip);
}
void xr::fb_body_tracker::stop()
{
assert(xrDestroyBodyTrackerFB);
full_body = false;
hip = false;
if (handle)
{
assert(xrDestroyBodyTrackerFB);
CHECK_XR(xrDestroyBodyTrackerFB(std::exchange(handle, nullptr)));
}
}
size_t xr::fb_body_tracker::count() const
{
const auto & config = application::get_config();
return get_whitelisted_joints(config.fb_lower_body, config.fb_hip).size();
}
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)
@@ -100,14 +125,8 @@ std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_h
std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses> poses{};
int num_poses = 0;
for (int i = 0; i < joint_whitelist.size(); i++)
for (auto joint: whitelisted_joints)
{
auto joint = joint_whitelist[i];
if (!full_body && (joint == XR_FULL_BODY_JOINT_HIPS_META || joint >= XR_FULL_BODY_JOINT_LEFT_UPPER_LEG_META))
continue;
if (!hip && joint == XR_FULL_BODY_JOINT_HIPS_META)
continue;
const auto & joint_loc = joints[joint];
wivrn::from_headset::body_tracking::pose pose{
.pose = joint_loc.pose,
+3
View File
@@ -42,6 +42,7 @@ class fb_body_tracker
bool full_body{};
bool hip{};
std::vector<XrFullBodyJointMETA> whitelisted_joints{};
public:
static constexpr std::array joint_whitelist{
@@ -56,6 +57,7 @@ public:
XR_FULL_BODY_JOINT_LEFT_FOOT_TRANSVERSE_META,
XR_FULL_BODY_JOINT_RIGHT_FOOT_TRANSVERSE_META,
};
static std::vector<XrFullBodyJointMETA> get_whitelisted_joints(bool full_body, bool hip);
fb_body_tracker() = default;
fb_body_tracker(instance & inst, session & s);
@@ -63,6 +65,7 @@ public:
void start(bool lower_body, bool hip);
void stop();
size_t count() const;
std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses>> locate_spaces(XrTime time, XrSpace reference);
};
+17 -2
View File
@@ -19,6 +19,7 @@
#include "fb_face_tracker2.h"
#include "wivrn_packets.h"
#include "xr/instance.h"
#include "xr/session.h"
#include <cstdint>
#include <openxr/openxr.h>
@@ -29,11 +30,25 @@ XrResult xr::destroy_fb_face_tracker2(XrFaceTracker2FB id)
return xrDestroyFaceTracker2FB(id);
}
xr::fb_face_tracker2::fb_face_tracker2(instance & inst, XrFaceTracker2FB h)
xr::fb_face_tracker2::fb_face_tracker2(instance & inst, session & s)
{
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)
+4 -2
View File
@@ -25,6 +25,7 @@
namespace xr
{
class instance;
class session;
XrResult destroy_fb_face_tracker2(XrFaceTracker2FB);
@@ -34,9 +35,10 @@ class fb_face_tracker2 : public utils::handle<XrFaceTracker2FB, destroy_fb_face_
PFN_xrDestroyFaceTracker2FB xrDestroyFaceTracker2FB{};
public:
using packet_type = wivrn::from_headset::tracking::fb_face2;
fb_face_tracker2() = default;
fb_face_tracker2(instance & inst, XrFaceTracker2FB h);
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
+4 -43
View File
@@ -18,13 +18,10 @@
*/
#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{};
@@ -33,8 +30,7 @@ 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)
xr::hand_tracker::hand_tracker(instance & inst, session & session, const XrHandTrackerCreateInfoEXT & info)
{
static auto xrCreateHandTrackerEXT = inst.get_proc<PFN_xrCreateHandTrackerEXT>("xrCreateHandTrackerEXT");
assert(xrCreateHandTrackerEXT);
@@ -77,48 +73,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]};
}
-3
View File
@@ -43,8 +43,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
+156
View File
@@ -0,0 +1,156 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Awzri <awzri@awzricat.com>
* Copyright (C) 2025 Sapphire <imsapphire0@gmail.com>
*
* 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/htc_exts.h"
#include "xr/xr.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(xr::space && space) :
space(std::move(space)) {}
void xr::vive_xr_tracker::set_active(bool active)
{
is_active = active;
}
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;
}
std::vector<std::string> xr::htc_body_tracker::get_roles()
{
auto paths = get_paths();
std::vector<std::string> roles{};
roles.reserve(paths.size());
for (auto & path: paths)
{
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,
};
roles.emplace_back(xr::details::enumerate<char>(xrGetInputSourceLocalizedName, s, &get_info));
}
return roles;
}
xr::htc_body_tracker::htc_body_tracker(instance & inst, session & s) :
inst(&inst),
s(s)
{
xrEnumeratePathsForInteractionProfileHTC = inst.get_proc<PFN_xrEnumeratePathsForInteractionProfileHTC>("xrEnumeratePathsForInteractionProfileHTC");
}
std::vector<XrPath> xr::htc_body_tracker::get_paths(XrPath user_path)
{
assert(xrEnumeratePathsForInteractionProfileHTC);
XrPath tracker_profile = inst->string_to_path("/interaction_profiles/htc/vive_xr_tracker");
XrPathsForInteractionProfileEnumerateInfoHTC profile_info{
.type = XR_TYPE_UNKNOWN,
.next = nullptr,
.interactionProfile = tracker_profile,
.userPath = user_path,
};
return xr::details::enumerate<XrPath>(xrEnumeratePathsForInteractionProfileHTC, *inst, profile_info);
}
void xr::htc_body_tracker::add(xr::space && space)
{
trackers.emplace_back(std::move(space));
}
size_t xr::htc_body_tracker::count() const
{
return trackers.size();
}
void xr::htc_body_tracker::update_active()
{
auto roles = get_roles();
assert(roles.size() >= trackers.size());
for (int i = 0; i < trackers.size(); i++)
trackers[i].set_active(!roles[i].contains('_'));
}
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.at(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;
}
+66
View File
@@ -0,0 +1,66 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Awzri <awzri@awzricat.com>
* Copyright (C) 2025 Sapphire <imsapphire0@gmail.com>
*
* 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/htc_exts.h"
#include "xr/space.h"
#include <string>
#include <vector>
#include <openxr/openxr.h>
namespace xr
{
class instance;
class session;
class vive_xr_tracker
{
bool is_active = false;
xr::space space;
public:
vive_xr_tracker(xr::space && s);
void set_active(bool active);
bool get_active() const;
XrSpace get_space() const;
};
class htc_body_tracker
{
instance * inst;
XrSession s;
std::vector<vive_xr_tracker> trackers;
PFN_xrEnumeratePathsForInteractionProfileHTC xrEnumeratePathsForInteractionProfileHTC{};
std::vector<std::string> get_roles();
public:
htc_body_tracker() = default;
htc_body_tracker(instance & inst, session & s);
std::vector<XrPath> get_paths(XrPath user_path = XR_NULL_PATH);
void add(xr::space && space);
size_t count() const;
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
+48 -30
View File
@@ -1,6 +1,7 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 galister <galister@librevr.org>
* Copyright (C) 2025 Sapphire <imsapphire0@gmail.com>
*
* 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
@@ -19,26 +20,50 @@
#include "htc_face_tracker.h"
#include "wivrn_packets.h"
#include "xr/instance.h"
#include "xr/session.h"
#include <openxr/openxr.h>
static PFN_xrDestroyFacialTrackerHTC xrDestroyFacialTrackerHTC{};
XrResult xr::destroy_htc_face_tracker(XrFacialTrackerHTC id)
xr::htc_face_tracker::htc_face_tracker(instance & inst, session & s, bool eye, bool lip) :
s(s)
{
return xrDestroyFacialTrackerHTC(id);
}
if (!eye && !lip)
return;
xr::htc_face_tracker::htc_face_tracker(instance & inst, XrFacialTrackerHTC h, XrFacialTrackingTypeHTC facialTrackingTypeHTC)
{
id = h;
xrCreateFacialTrackerHTC = inst.get_proc<PFN_xrCreateFacialTrackerHTC>("xrCreateFacialTrackerHTC");
xrGetFacialExpressionsHTC = inst.get_proc<PFN_xrGetFacialExpressionsHTC>("xrGetFacialExpressionsHTC");
xrDestroyFacialTrackerHTC = inst.get_proc<PFN_xrDestroyFacialTrackerHTC>("xrDestroyFacialTrackerHTC");
trackerType = facialTrackingTypeHTC;
XrFacialTrackerCreateInfoHTC create_info{
.type = XR_TYPE_FACIAL_TRACKER_CREATE_INFO_HTC,
.next = nullptr,
};
if (eye)
{
create_info.facialTrackingType = XR_FACIAL_TRACKING_TYPE_EYE_DEFAULT_HTC;
xrCreateFacialTrackerHTC(s, &create_info, &this->eye);
}
if (lip)
{
create_info.facialTrackingType = XR_FACIAL_TRACKING_TYPE_LIP_DEFAULT_HTC;
xrCreateFacialTrackerHTC(s, &create_info, &this->lip);
}
}
void xr::htc_face_tracker::get_weights(XrTime time, wivrn::from_headset::tracking::htc_face & out_expressions)
xr::htc_face_tracker::~htc_face_tracker()
{
if (!id || !xrGetFacialExpressionsHTC)
if (!xrDestroyFacialTrackerHTC)
return;
if (eye)
CHECK_XR(xrDestroyFacialTrackerHTC(std::exchange(eye, nullptr)));
if (lip)
CHECK_XR(xrDestroyFacialTrackerHTC(std::exchange(lip, nullptr)));
}
void xr::htc_face_tracker::get_weights(XrTime time, packet_type & out_expressions)
{
if (!(eye || lip) || !xrGetFacialExpressionsHTC)
return;
XrFacialExpressionsHTC expressions{
@@ -47,25 +72,18 @@ void xr::htc_face_tracker::get_weights(XrTime time, wivrn::from_headset::trackin
.sampleTime = time,
};
bool * is_active;
switch (trackerType)
if (eye)
{
case XR_FACIAL_TRACKING_TYPE_EYE_DEFAULT_HTC:
expressions.expressionCount = out_expressions.eye.size();
expressions.expressionWeightings = out_expressions.eye.data();
is_active = &out_expressions.eye_active;
break;
case XR_FACIAL_TRACKING_TYPE_LIP_DEFAULT_HTC:
expressions.expressionCount = out_expressions.lip.size();
expressions.expressionWeightings = out_expressions.lip.data();
is_active = &out_expressions.lip_active;
break;
default:
throw std::system_error(1, std::generic_category(), "htc_face_tracker with unknown trackerType");
expressions.expressionCount = out_expressions.eye.size();
expressions.expressionWeightings = out_expressions.eye.data();
CHECK_XR(xrGetFacialExpressionsHTC(eye, &expressions));
out_expressions.eye_active = expressions.isActive;
}
if (lip)
{
expressions.expressionCount = out_expressions.lip.size();
expressions.expressionWeightings = out_expressions.lip.data();
CHECK_XR(xrGetFacialExpressionsHTC(lip, &expressions));
out_expressions.lip_active = expressions.isActive;
}
CHECK_XR(xrGetFacialExpressionsHTC(id, &expressions));
*is_active = expressions.isActive;
}
+11 -6
View File
@@ -1,6 +1,7 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 galister <galister@librevr.org>
* Copyright (C) 2025 Sapphire <imsapphire0@gmail.com>
*
* 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
@@ -25,19 +26,23 @@
namespace xr
{
class instance;
class session;
XrResult destroy_htc_face_tracker(XrFacialTrackerHTC);
class htc_face_tracker : public utils::handle<XrFacialTrackerHTC, destroy_htc_face_tracker>
class htc_face_tracker
{
XrSession s;
XrFacialTrackerHTC eye{};
XrFacialTrackerHTC lip{};
PFN_xrCreateFacialTrackerHTC xrCreateFacialTrackerHTC{};
PFN_xrGetFacialExpressionsHTC xrGetFacialExpressionsHTC{};
PFN_xrDestroyFacialTrackerHTC xrDestroyFacialTrackerHTC{};
XrFacialTrackingTypeHTC trackerType{};
public:
using packet_type = wivrn::from_headset::tracking::htc_face;
htc_face_tracker() = default;
htc_face_tracker(instance & inst, XrFacialTrackerHTC h, XrFacialTrackingTypeHTC facialTrackingTypeHTC);
htc_face_tracker(instance & inst, session & s, bool eye, bool lip);
~htc_face_tracker();
void get_weights(XrTime time, struct wivrn::from_headset::tracking::htc_face & out_expressions);
void get_weights(XrTime time, packet_type & out_expressions);
};
} // namespace xr
+23 -3
View File
@@ -21,6 +21,7 @@
#include "xr.h"
#include "xr/details/enumerate.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <spdlog/spdlog.h>
@@ -40,6 +41,26 @@ static XrBool32 debug_callback(
return XR_FALSE;
}
static std::pair<XrVersion, XrInstance> create_instance(XrInstanceCreateInfo & info)
{
XrResult res;
for (XrVersion version: {
XR_API_VERSION_1_1,
XR_API_VERSION_1_0,
})
{
info.applicationInfo.apiVersion = version;
XrInstance inst;
res = xrCreateInstance(&info, &inst);
if (XR_SUCCEEDED(res))
return {version, inst};
spdlog::info("Failed to create OpenXR instance version {}: {}",
xr::to_string(version),
xr::to_string(res));
}
throw std::system_error(res, xr::error_category(), "Failed to create OpenXR instance");
}
#if defined(XR_USE_PLATFORM_ANDROID)
xr::instance::instance(std::string_view application_name, void * applicationVM, void * applicationActivity, std::vector<const char *> extensions)
#else
@@ -94,6 +115,7 @@ xr::instance::instance(std::string_view application_name, std::vector<const char
spdlog::info("Available OpenXR extensions:");
bool debug_utils_found = false;
auto all_extensions = xr::instance::extensions();
std::ranges::sort(all_extensions, [](const char * a, const char * b) { return strcmp(a, b) < 0; }, &XrExtensionProperties::extensionName);
for (XrExtensionProperties & i: all_extensions)
{
spdlog::info(" {} (version {})", i.extensionName, i.extensionVersion);
@@ -122,7 +144,6 @@ xr::instance::instance(std::string_view application_name, std::vector<const char
XrInstanceCreateInfo create_info{
.type = XR_TYPE_INSTANCE_CREATE_INFO,
.applicationInfo = {.apiVersion = XR_MAKE_VERSION(1, 0, 0)},
.enabledApiLayerCount = (uint32_t)layers.size(),
.enabledApiLayerNames = layers.data(),
.enabledExtensionCount = (uint32_t)extensions.size(),
@@ -139,8 +160,7 @@ xr::instance::instance(std::string_view application_name, std::vector<const char
create_info.next = &instanceCreateInfoAndroid;
#endif
CHECK_XR(xrCreateInstance(&create_info, &id));
assert(id != XR_NULL_HANDLE);
std::tie(api_version, id) = create_instance(create_info);
if (debug_utils_found)
{
+7
View File
@@ -43,12 +43,14 @@ union event
XrEventDataDisplayRefreshRateChangedFB refresh_rate_changed;
XrEventDataPassthroughStateChangedFB passthrough_state_changed;
XrEventDataVisibilityMaskChangedKHR visibility_mask_changed;
XrEventDataUserPresenceChangedEXT user_presence_changed;
};
class instance : public utils::handle<XrInstance, xrDestroyInstance>
{
std::string runtime_version;
std::string runtime_name;
std::unordered_map<std::string, uint32_t> loaded_extensions;
XrVersion api_version;
public:
#if defined(XR_USE_PLATFORM_ANDROID)
@@ -70,6 +72,11 @@ public:
return runtime_name;
}
XrVersion get_api_version() const
{
return api_version;
}
template <typename F>
F get_proc(const char * name)
{
+1 -1
View File
@@ -51,6 +51,7 @@ xr::passthrough_layer_fb::passthrough_layer_fb(instance & inst, session & s, con
static XrPassthroughFB create_passthrough_fb(xr::instance & inst, xr::session & s)
{
PFN_xrCreatePassthroughFB xrCreatePassthroughFB = inst.get_proc<PFN_xrCreatePassthroughFB>("xrCreatePassthroughFB");
xrDestroyPassthroughFB = inst.get_proc<PFN_xrDestroyPassthroughFB>("xrDestroyPassthroughFB");
XrPassthroughFB id;
XrPassthroughCreateInfoFB info{
@@ -71,7 +72,6 @@ xr::passthrough_fb::passthrough_fb(instance & inst, session & s) :
.purpose = XR_PASSTHROUGH_LAYER_PURPOSE_RECONSTRUCTION_FB,
})
{
xrDestroyPassthroughFB = inst.get_proc<PFN_xrDestroyPassthroughFB>("xrDestroyPassthroughFB");
xrPassthroughStartFB = inst.get_proc<PFN_xrPassthroughStartFB>("xrPassthroughStartFB");
xrPassthroughPauseFB = inst.get_proc<PFN_xrPassthroughPauseFB>("xrPassthroughPauseFB");
xrPassthroughLayerPauseFB = inst.get_proc<PFN_xrPassthroughLayerPauseFB>("xrPassthroughLayerPauseFB");
+19 -5
View File
@@ -30,12 +30,25 @@ XrResult xr::destroy_pico_body_tracker(XrBodyTrackerBD id)
return xrDestroyBodyTrackerBD(id);
}
xr::pico_body_tracker::pico_body_tracker(instance & inst, XrBodyTrackerBD h)
xr::pico_body_tracker::pico_body_tracker(instance & inst, session & s)
{
id = h;
auto xrCreateBodyTrackerBD = inst.get_proc<PFN_xrCreateBodyTrackerBD>("xrCreateBodyTrackerBD");
xrLocateBodyJointsBD = inst.get_proc<PFN_xrLocateBodyJointsBD>("xrLocateBodyJointsBD");
assert(xrCreateBodyTrackerBD);
XrBodyTrackerCreateInfoBD create_info{
.type = XR_TYPE_BODY_TRACKER_CREATE_INFO_BD,
.next = nullptr,
.jointSet = XR_BODY_JOINT_SET_FULL_BODY_JOINTS_BD,
};
CHECK_XR(xrCreateBodyTrackerBD(s, &create_info, &id));
}
size_t xr::pico_body_tracker::count() const
{
return joint_whitelist.size();
}
std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses>> xr::pico_body_tracker::locate_spaces(XrTime time, XrSpace reference)
{
if (!xrLocateBodyJointsBD)
@@ -63,9 +76,10 @@ std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_h
}
std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses> poses{};
for (int i = 0; i < joint_whitelist.size(); i++)
int num_poses = 0;
for (auto joint: joint_whitelist)
{
const auto & joint_loc = joints[joint_whitelist[i]];
const auto & joint_loc = joints[joint];
wivrn::from_headset::body_tracking::pose pose{
.pose = joint_loc.pose,
.flags = 0,
@@ -80,7 +94,7 @@ std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_h
if (joint_loc.locationFlags & XR_SPACE_LOCATION_POSITION_TRACKED_BIT)
pose.flags |= wivrn::from_headset::body_tracking::position_tracked;
poses[i] = pose;
poses[num_poses++] = pose;
}
return poses;
}
+3 -1
View File
@@ -28,6 +28,7 @@
namespace xr
{
class instance;
class session;
XrResult destroy_pico_body_tracker(XrBodyTrackerBD);
@@ -48,8 +49,9 @@ public:
};
pico_body_tracker() = default;
pico_body_tracker(instance & inst, XrBodyTrackerBD h);
pico_body_tracker(instance & inst, session & s);
size_t count() const;
std::optional<std::array<wivrn::from_headset::body_tracking::pose, wivrn::from_headset::body_tracking::max_tracked_poses>> locate_spaces(XrTime time, XrSpace reference);
};
} // namespace xr
+2 -1
View File
@@ -40,12 +40,13 @@ class pico_face_tracker
bool started{};
public:
using packet_type = wivrn::from_headset::tracking::fb_face2;
pico_face_tracker() = default;
pico_face_tracker(instance & inst, session & s);
~pico_face_tracker();
void start();
void stop();
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
+2 -68
View File
@@ -23,9 +23,7 @@
#include "details/enumerate.h"
#include "openxr/openxr.h"
#include "utils/contains.h"
#include "xr/fb_body_tracker.h"
#include "xr/instance.h"
#include "xr/pico_body_tracker.h"
#include "xr/system.h"
#include <ranges>
#include <vulkan/vulkan.h>
@@ -100,72 +98,6 @@ xr::hand_tracker xr::session::create_hand_tracker(XrHandEXT hand, XrHandJointSet
}};
}
xr::fb_face_tracker2 xr::session::create_fb_face_tracker2()
{
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,
};
XrFaceTracker2FB ft;
auto xrCreateFaceTracker2FB = inst->get_proc<PFN_xrCreateFaceTracker2FB>("xrCreateFaceTracker2FB");
assert(xrCreateFaceTracker2FB);
CHECK_XR(xrCreateFaceTracker2FB(id, &create_info, &ft));
return {*inst, ft};
}
xr::htc_face_tracker xr::session::create_htc_face_tracker(XrFacialTrackingTypeHTC facialTrackingType)
{
XrFacialTrackerCreateInfoHTC create_info{
.type = XR_TYPE_FACIAL_TRACKER_CREATE_INFO_HTC,
.next = nullptr,
.facialTrackingType = facialTrackingType,
};
XrFacialTrackerHTC ft;
auto xrCreateFacialTrackerHTC = inst->get_proc<PFN_xrCreateFacialTrackerHTC>("xrCreateFacialTrackerHTC");
assert(xrCreateFacialTrackerHTC);
CHECK_XR(xrCreateFacialTrackerHTC(id, &create_info, &ft));
return {*inst, ft, facialTrackingType};
}
xr::pico_face_tracker xr::session::create_pico_face_tracker()
{
return {*inst, *this};
}
xr::fb_body_tracker xr::session::create_fb_body_tracker()
{
return {*inst, *this};
}
xr::pico_body_tracker xr::session::create_pico_body_tracker()
{
XrBodyTrackerCreateInfoBD create_info{
.type = XR_TYPE_BODY_TRACKER_CREATE_INFO_BD,
.next = nullptr,
.jointSet = XR_BODY_JOINT_SET_FULL_BODY_JOINTS_BD,
};
XrBodyTrackerBD bt;
auto xrCreateBodyTrackerBD = inst->get_proc<PFN_xrCreateBodyTrackerBD>("xrCreateBodyTrackerBD");
assert(xrCreateBodyTrackerBD);
CHECK_XR(xrCreateBodyTrackerBD(id, &create_info, &bt));
return {*inst, bt};
}
std::vector<vk::Format> xr::session::get_swapchain_formats() const
{
std::vector<vk::Format> formats;
@@ -195,6 +127,7 @@ void xr::session::begin_frame()
.type = XR_TYPE_FRAME_BEGIN_INFO,
};
auto lock = application::get_queue().lock();
CHECK_XR(xrBeginFrame(id, &begin_info));
}
@@ -208,6 +141,7 @@ void xr::session::end_frame(XrTime display_time, const std::vector<XrComposition
.layers = layers.data(),
};
auto lock = application::get_queue().lock();
CHECK_XR(xrEndFrame(id, &end_info));
}
-10
View File
@@ -26,13 +26,8 @@
#include <vulkan/vulkan_raii.hpp>
#include <openxr/openxr.h>
#include "fb_body_tracker.h"
#include "fb_face_tracker2.h"
#include "hand_tracker.h"
#include "htc_face_tracker.h"
#include "passthrough.h"
#include "pico_body_tracker.h"
#include "pico_face_tracker.h"
#include "space.h"
namespace xr
@@ -53,11 +48,6 @@ public:
space create_reference_space(XrReferenceSpaceType ref, const XrPosef & pose = {{0, 0, 0, 1}, {0, 0, 0}});
space create_action_space(XrAction action, const XrPosef & pose = {{0, 0, 0, 1}, {0, 0, 0}});
hand_tracker create_hand_tracker(XrHandEXT hand, XrHandJointSetEXT hand_joint_set = XR_HAND_JOINT_SET_DEFAULT_EXT);
fb_face_tracker2 create_fb_face_tracker2();
htc_face_tracker create_htc_face_tracker(XrFacialTrackingTypeHTC);
pico_face_tracker create_pico_face_tracker();
fb_body_tracker create_fb_body_tracker();
pico_body_tracker create_pico_body_tracker();
std::vector<vk::Format> get_swapchain_formats() const;
+5
View File
@@ -37,6 +37,11 @@ enum class spaces
aim_right,
palm_left,
palm_right,
// hand_interaction_ext
pinch_left,
pinch_right,
poke_left,
poke_right,
count
};
+3
View File
@@ -18,6 +18,7 @@
*/
#include "swapchain.h"
#include "application.h"
#include "details/enumerate.h"
#include "session.h"
@@ -95,6 +96,7 @@ int xr::swapchain::acquire()
.type = XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO,
};
auto lock = application::get_queue().lock();
CHECK_XR(xrAcquireSwapchainImage(id, &acquire_info, &index));
return index;
@@ -118,5 +120,6 @@ void xr::swapchain::release()
.type = XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO,
};
auto lock = application::get_queue().lock();
CHECK_XR(xrReleaseSwapchainImage(id, &release_info));
}
+18
View File
@@ -105,6 +105,24 @@ XrSystemEyeGazeInteractionPropertiesEXT xr::system::eye_gaze_interaction_propert
return eye_gaze_prop;
}
XrSystemUserPresencePropertiesEXT xr::system::user_presence_properties() const
{
if (!id)
throw std::invalid_argument("this");
XrSystemUserPresencePropertiesEXT presence_prop{
.type = XR_TYPE_SYSTEM_USER_PRESENCE_PROPERTIES_EXT,
};
XrSystemProperties prop{
.type = XR_TYPE_SYSTEM_PROPERTIES,
.next = &presence_prop,
};
CHECK_XR(xrGetSystemProperties(*inst, id, &prop));
return presence_prop;
}
XrSystemFaceTrackingProperties2FB xr::system::fb_face_tracking2_properties() const
{
if (!id)
+1
View File
@@ -62,6 +62,7 @@ public:
XrSystemProperties properties() const;
XrSystemHandTrackingPropertiesEXT hand_tracking_properties() const;
XrSystemEyeGazeInteractionPropertiesEXT eye_gaze_interaction_properties() const;
XrSystemUserPresencePropertiesEXT user_presence_properties() const;
XrSystemFaceTrackingProperties2FB fb_face_tracking2_properties() const;
XrSystemFacialTrackingPropertiesHTC htc_face_tracking_properties() const;
XrSystemBodyTrackingPropertiesFB fb_body_tracking_properties() const;
+23 -6
View File
@@ -23,19 +23,17 @@ endif()
configure_file(wivrn_config.h.in wivrn_config.h)
add_library(wivrn-common-base STATIC
utils/xdg_base_directory.cpp
utils/flatpak.cpp
add_library(wivrn-common-base STATIC EXCLUDE_FROM_ALL
utils/strings.cpp
utils/xdg_base_directory.cpp
${CMAKE_CURRENT_BINARY_DIR}/version.cpp
)
add_library(wivrn-common STATIC
add_library(wivrn-common STATIC EXCLUDE_FROM_ALL
crypto.cpp
smp.cpp
secrets.cpp
wivrn_sockets.cpp
utils/xdg_base_directory.cpp
utils/strings.cpp
vk/allocation.cpp
vk/error_category.cpp
@@ -43,6 +41,26 @@ add_library(wivrn-common STATIC
vk/vk_mem_alloc.cpp
)
if (WIVRN_BUILD_DASHBOARD OR WIVRN_BUILD_SERVER)
add_library(wivrn-common-server STATIC EXCLUDE_FROM_ALL
utils/flatpak.cpp
utils/xdg_icon_lookup.cpp
utils/steam_app_info.cpp
utils/load_icon.cpp
utils/ini.cpp
application.cpp
)
target_link_libraries(wivrn-common-server PRIVATE nlohmann_json::nlohmann_json PNG::PNG PkgConfig::librsvg-2.0 LibArchive::LibArchive PUBLIC wivrn-common-base)
if (WIVRN_BUILD_TEST)
add_executable(list-apps
test_application.cpp
)
target_link_libraries(list-apps wivrn-common-server)
endif()
endif()
if(ANDROID)
# The Vulkan headers in Android do not include the C++ headers, download them
# Minimum version is 1.3.256
@@ -113,5 +131,4 @@ endif()
target_include_directories(wivrn-common-base PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
target_link_libraries(wivrn-common PUBLIC Boost::pfr OpenSSL::Crypto wivrn-external wivrn-common-base)
target_compile_features(wivrn-common PRIVATE cxx_std_20)
target_compile_definitions(wivrn-common PUBLIC VULKAN_HPP_NO_STRUCT_CONSTRUCTORS)
+390
View File
@@ -0,0 +1,390 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 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/>.
*/
#include "application.h"
#include "utils/flatpak.h"
#include "utils/steam_app_info.h"
#include "utils/xdg_base_directory.h"
#include "utils/xdg_icon_lookup.h"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
namespace wivrn
{
namespace
{
std::string read_file(const std::filesystem::path & path)
{
std::ifstream f(path);
std::istreambuf_iterator<char> begin{f}, end;
return {begin, end};
}
std::filesystem::path home()
{
auto home = std::getenv("HOME");
return home ? home : "";
}
std::pair<std::string, std::optional<std::filesystem::path>> find_steam()
{
// system Steam
if (std::filesystem::exists(xdg_data_home() / "Steam"))
return {"steam", xdg_data_home() / "Steam"};
auto h = home();
// system Steam (accessed from flatpak)
if (std::filesystem::exists(h / ".local/share/Steam"))
return {"steam", h / ".local/share/Steam"};
// Flatpak Steam
if (std::filesystem::exists(h / ".var/app/com.valvesoftware.Steam/.steam/steam"))
return {"flatpak run com.valvesoftware.Steam", h / ".var/app/com.valvesoftware.Steam/.steam/steam"};
return {};
}
std::string read_vr_manifest(const std::filesystem::path & root)
{
return read_file(root / "config/steamapps.vrmanifest");
}
steam_app_info read_steam_app_info(const std::filesystem::path & root)
{
try
{
return steam_app_info{root / "appcache/appinfo.vdf"};
}
catch (...)
{}
return {};
}
std::optional<std::filesystem::path> find_steam_icon(const std::filesystem::path & root, int app_id, const steam_app_info & info)
{
const auto & app_info = info.get(app_id);
try
{
std::string icon{std::get<std::string_view>(app_info.at("common.clienticon"))};
auto icon_path = root / "steam/games" / (icon + ".ico");
if (std::filesystem::exists(icon_path))
return icon_path;
}
catch (...)
{
}
try
{
std::string icon{std::get<std::string_view>(app_info.at("common.linuxclienticon"))};
auto icon_path = root / "steam/games" / (icon + ".zip");
if (std::filesystem::exists(icon_path))
return icon_path;
}
catch (...)
{
}
return std::nullopt;
}
void read_steam_vr_apps(std::unordered_map<std::string, application> & res)
{
auto [command, root] = find_steam();
if (not root)
return;
auto manifest = read_vr_manifest(*root);
auto info = read_steam_app_info(*root);
if (manifest.empty())
return;
nlohmann::json json = nlohmann::json::parse(manifest);
for (auto & i: json["applications"])
{
try
{
application app;
std::string app_key = i["app_key"];
for (auto [locale, items]: i["strings"].items())
{
if (auto it = items.find("name"); it != items.end())
app.name[locale] = *it;
}
if (not app.name.contains(""))
{
auto it = app.name.find("en_us");
if (it == app.name.end())
it = app.name.begin();
if (it != app.name.end())
app.name[""] = it->second;
}
if (i["launch_type"] == "url")
{
app.exec = command + " " + (std::string)i["url"];
}
else if (i["launch_type"] == "binary")
{
const char prefix[] = "steam.app.";
if (app_key.starts_with(prefix))
{
// ¯\_(ツ)_/¯
uint64_t appkey = stoll(app_key.substr(strlen(prefix)));
app.exec = command + " steam://rungameid/" + std::to_string((appkey << 32) + 0x2000000);
}
}
try
{
const char prefix[] = "steam.app.";
if (app_key.starts_with(prefix))
{
uint32_t app_id = stoll(app_key.substr(strlen(prefix)));
app.icon_path = find_steam_icon(*root, app_id, info);
}
}
catch (...)
{
}
if (not app.exec.empty())
res[app_key] = std::move(app);
}
catch (std::exception & e)
{
std::cerr << "Failed to parse Steam VR manifest: " << e.what() << std::endl;
}
}
}
std::string unescape(std::string_view in)
{
std::string out;
out.reserve(in.size());
for (auto c = in.begin(); c != in.end(); ++c)
{
if (*c == '\\')
{
++c;
if (c == in.end())
break;
switch (*c)
{
case 's':
out += ' ';
break;
case 'n':
out += '\n';
break;
case 't':
out += '\t';
break;
case 'r':
out += '\r';
break;
default:
out += *c;
}
}
else
{
out += *c;
}
}
return out;
}
struct key_value
{
std::string_view key;
std::string_view locale;
std::string_view value;
key_value(std::string_view l)
{
auto pos = l.find_first_of("[ =");
if (pos == std::string_view::npos)
return;
key = l.substr(0, pos);
l = l.substr(pos);
if (l[0] == '[')
{
pos = l.find(']');
if (pos == std::string_view::npos)
{
key = std::string_view();
return;
}
locale = l.substr(1, pos - 1);
l = l.substr(pos + 1);
}
pos = l.find('=');
if (pos == std::string_view::npos)
{
key = std::string_view();
locale = std::string_view();
return;
}
l = l.substr(pos + 1);
pos = l.find_first_not_of(" ");
if (pos == std::string_view::npos)
{
key = std::string_view();
locale = std::string_view();
return;
}
value = l.substr(pos);
}
};
bool contains(std::string_view entries, std::string_view val, char sep = ';')
{
for (auto bounds: entries | std::views::split(sep))
{
if (std::string_view(bounds.begin(), bounds.end()) == val)
return true;
}
return false;
}
std::optional<application> do_desktop_entry(const std::filesystem::path & filename)
{
auto data = read_file(filename);
std::optional<application> res;
// Most apps are not VR, don't bother parsing the rest
bool vr = false;
for (auto bounds: data | std::views::split('\n'))
{
std::string_view line(bounds.begin(), bounds.end());
key_value item(line);
if (item.key == "Categories")
vr = contains(item.value, "X-WiVRn-VR");
}
if (not vr)
return res;
res.emplace();
for (auto bounds: data | std::views::split('\n'))
{
std::string_view line(bounds.begin(), bounds.end());
if (line.empty())
continue;
if (line.starts_with("#"))
continue;
// Only process the main section
if (line.starts_with("[") and line != "[Desktop Entry]")
break;
key_value item(line);
if (item.key == "Type" and item.value != "Application")
{
res.reset();
return res;
}
if (item.key == "Name")
res->name.emplace(item.locale, unescape(item.value));
if (item.key == "Exec")
res->exec = unescape(item.value);
if (item.key == "Path")
res->path = unescape(item.value);
if (item.key == "Icon")
{
try
{
res->icon_path = xdg_icon_lookup(std::string{item.value}, 256);
}
catch (...)
{}
}
}
if (res->exec.empty() or not res->name.contains(""))
res.reset();
return res;
}
void do_data_dir(std::filesystem::path dir, std::unordered_map<std::string, application> & res)
{
dir = dir / "applications";
if (not std::filesystem::is_directory(dir))
return;
for (const auto & entry: std::filesystem::recursive_directory_iterator(dir))
{
if (entry.is_directory())
continue;
if (entry.path().extension() != ".desktop")
continue;
// https://specifications.freedesktop.org/desktop-entry-spec/latest/file-naming.html#desktop-file-id
auto file_id = entry.path()
.lexically_relative(dir)
.replace_extension("")
.string();
std::ranges::replace(file_id, '/', '-');
if (res.contains(file_id))
continue;
auto app = do_desktop_entry(entry.path());
if (app)
res.emplace(std::move(file_id), std::move(*app));
}
}
} // namespace
std::unordered_map<std::string, application> list_applications()
{
std::unordered_map<std::string, application> res;
read_steam_vr_apps(res);
do_data_dir(xdg_data_home(), res);
for (auto && dir: xdg_data_dirs())
do_data_dir(std::move(dir), res);
if (wivrn::is_flatpak())
{
// Try to guess host data dirs
do_data_dir("/run/host/usr/share", res);
}
return res;
}
} // namespace wivrn
+39
View File
@@ -0,0 +1,39 @@
/*
* 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 <filesystem>
#include <optional>
#include <string>
#include <unordered_map>
namespace wivrn
{
struct application
{
// localised names, with empty locale for default
std::unordered_map<std::string, std::string> name;
std::string exec;
std::optional<std::filesystem::path> icon_path;
std::optional<std::string> path;
};
std::unordered_map<std::string, application> list_applications();
} // namespace wivrn
+42
View File
@@ -0,0 +1,42 @@
/*
* 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 "application.h"
#include <iostream>
int main()
{
auto apps = wivrn::list_applications();
std::cout << "Parsed " << apps.size() << " applications" << std::endl;
for (const auto & [k, app]: apps)
{
std::cout << "======================" << std::endl;
std::cout << k << std::endl;
for (const auto & [locale, name]: app.name)
{
std::cout << "Name";
if (not locale.empty())
std::cout << "[" << locale << "]";
std::cout << "=" << name << std::endl;
}
std::cout << "Exec=" << app.exec << std::endl;
if (app.path)
std::cout << "Path=" << *app.path << std::endl;
}
}
+2 -1
View File
@@ -23,10 +23,11 @@
#include <fstream>
static const std::filesystem::path info_path = "/.flatpak-info";
static const bool is_flatpak_v = std::filesystem::exists(info_path);
bool wivrn::is_flatpak()
{
return std::filesystem::exists(info_path);
return is_flatpak_v;
}
std::optional<std::string> wivrn::flatpak_key(std::string section, std::string key)
+92
View File
@@ -0,0 +1,92 @@
/*
* 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 "ini.h"
#include <ranges>
static constexpr std::string_view strip(std::string_view sv)
{
size_t prefix_size = sv.find_first_not_of(' ');
if (prefix_size == std::string_view::npos)
return {};
sv.remove_prefix(prefix_size);
size_t suffix_size = sv.find_last_not_of(' ');
if (suffix_size == std::string_view::npos)
return {};
sv.remove_suffix(sv.size() - suffix_size - 1);
return sv;
}
static constexpr std::optional<wivrn::ini::key_value> parse_key_value(std::string_view section, std::string_view line)
{
size_t equal_sign = line.find('=');
if (equal_sign == std::string_view::npos)
return {};
auto key = strip(line.substr(0, equal_sign)); // TODO locale
auto value = strip(line.substr(equal_sign + 1));
return wivrn::ini::key_value{
.section = section,
.key = key,
.locale = "",
.value = value,
};
}
std::optional<std::string_view> wivrn::ini::get_optional(std::string_view section, std::string_view key) const
{
for (const auto & line: lines)
{
if (line.section == section and line.key == key)
return line.value;
}
return std::nullopt;
}
wivrn::ini::ini(std::istream & file)
{
contents = {std::istreambuf_iterator<char>{file}, {}};
std::string_view current_section;
for (auto bounds: contents | std::views::split('\n'))
{
auto line = strip({bounds.begin(), bounds.end()});
if (line.starts_with('#'))
continue;
if (line.starts_with('[') and line.ends_with(']'))
{
current_section = line.substr(1, line.size() - 2);
continue;
}
auto kv = parse_key_value(current_section, line);
if (kv)
lines.push_back(*kv);
}
}
+82
View File
@@ -0,0 +1,82 @@
/*
* 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 <charconv>
#include <istream>
#include <optional>
#include <string>
#include <type_traits>
#include <vector>
namespace wivrn
{
class ini
{
public:
struct key_value
{
std::string_view section;
std::string_view key;
std::string_view locale;
std::string_view value;
};
private:
std::string contents;
std::vector<key_value> lines;
public:
ini() = default;
ini(ini &&) = default;
ini(const ini &) = delete;
ini & operator=(ini &&) = default;
ini & operator=(const ini &) = delete;
ini(std::istream & file);
std::optional<std::string_view> get_optional(std::string_view section, std::string_view key) const;
template <typename T>
T get(std::string_view section, std::string_view key, const T & default_value = T{}) const
{
using return_type = std::decay_t<T>;
auto value = get_optional(section, key);
if (not value)
return default_value;
if constexpr (std::is_same_v<return_type, std::string_view>)
return *value;
if constexpr (std::is_same_v<return_type, std::string>)
return std::string{*value};
if constexpr (std::is_integral_v<return_type>)
{
return_type v;
if (std::from_chars(value->data(), value->data() + value->size(), v).ec != std::errc{})
return default_value;
return v;
}
}
};
} // namespace wivrn
+636
View File
@@ -0,0 +1,636 @@
/*
* 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 "load_icon.h"
#include <archive.h>
#include <archive_entry.h>
#include <cairo.h>
#include <fstream>
#include <librsvg/rsvg.h>
#include <limits>
#include <png.h>
#include <span>
#include <unordered_map>
namespace
{
std::vector<std::byte> load_file(const std::filesystem::path & filename)
{
std::ifstream file(filename, std::ios::binary | std::ios::ate);
file.exceptions(std::ios_base::badbit | std::ios_base::failbit);
size_t size = file.tellg();
file.seekg(0);
std::vector<std::byte> bytes(size);
file.read(reinterpret_cast<char *>(bytes.data()), size);
return bytes;
}
template <typename T>
requires std::is_integral_v<T>
T read(std::span<std::byte> & buffer)
{
if (sizeof(T) > buffer.size())
throw std::runtime_error{"File truncated"};
T value;
memcpy(&value, buffer.data(), sizeof(T));
buffer = buffer.subspan(sizeof(T));
static_assert(std::endian::native == std::endian::big or std::endian::native == std::endian::little);
if constexpr (std::endian::native == std::endian::big)
return std::byteswap(value);
else
return value;
}
template <typename T>
requires std::is_integral_v<T>
std::span<T> read(std::span<std::byte> & buffer, size_t count)
{
if (count * sizeof(T) > buffer.size())
throw std::runtime_error{"File truncated"};
std::span<T> value{reinterpret_cast<T *>(buffer.data()), count};
buffer = buffer.subspan(count * sizeof(T));
return value;
}
std::vector<std::byte> load_svg(const std::filesystem::path & filename, int size)
{
// TODO check if aspect ratio needs to be handled, dpi
struct deleter
{
void operator()(GFile * ptr)
{
g_object_unref(ptr);
}
void operator()(RsvgHandle * ptr)
{
g_object_unref(ptr);
}
void operator()(cairo_surface_t * ptr)
{
cairo_surface_destroy(ptr);
}
void operator()(cairo_t * ptr)
{
cairo_destroy(ptr);
}
};
using GFile_ptr = std::unique_ptr<GFile, deleter>;
using RsvgHandle_ptr = std::unique_ptr<RsvgHandle, deleter>;
using cairo_surface_t_ptr = std::unique_ptr<cairo_surface_t, deleter>;
using cairo_t_ptr = std::unique_ptr<cairo_t, deleter>;
GError * error{};
GFile_ptr file{g_file_new_for_path(filename.c_str())};
RsvgHandle_ptr handle{rsvg_handle_new_from_gfile_sync(file.get(), RSVG_HANDLE_FLAGS_NONE, nullptr, &error)};
// Create a Cairo image surface and a rendering context for it
cairo_surface_t_ptr surface{cairo_image_surface_create(CAIRO_FORMAT_ARGB32, size, size)};
cairo_t_ptr cr{cairo_create(surface.get())};
// Set the dots-per-inch
rsvg_handle_set_dpi(handle.get(), 96.0);
// Render the handle scaled proportionally into that whole surface
RsvgRectangle viewport = {
.x = 0.0,
.y = 0.0,
.width = (double)size,
.height = (double)size,
};
if (!rsvg_handle_render_document(handle.get(), cr.get(), &viewport, &error))
throw std::runtime_error{std::string{"Could not render: "} + error->message};
// Write a PNG file
std::vector<std::byte> png;
auto cb = [](void * closure, const unsigned char * data, unsigned int length) -> cairo_status_t {
std::vector<std::byte> & png = *reinterpret_cast<std::vector<std::byte> *>(closure);
size_t old_size = png.size();
png.resize(old_size + length);
memcpy(&png[old_size], data, length);
return CAIRO_STATUS_SUCCESS;
};
if (auto status = cairo_surface_write_to_png_stream(surface.get(), cb, &png); status != CAIRO_STATUS_SUCCESS)
throw std::runtime_error{std::string{"Could not write output: "} + cairo_status_to_string(status)};
return png;
}
// See https://gitlab.gnome.org/GNOME/gimp/-/tree/master/plug-ins/file-ico?ref_type=heads
struct ico_file_entry
{
int width; // Width of icon in pixels
int height; // Height of icon in pixels
int bpp; // 1, 4, 8, 16, 24 or 32 bits per pixel
std::span<std::byte> data;
};
constexpr int rowstride(int width, int bpp)
{
int words_per_line = (width * bpp + 31) / 32;
return words_per_line * 4;
}
static_assert(rowstride(1, 1) == 4);
static_assert(rowstride(8, 1) == 4);
static_assert(rowstride(16, 1) == 4);
static_assert(rowstride(32, 1) == 4);
static_assert(rowstride(33, 1) == 8);
static_assert(rowstride(1, 4) == 4);
static_assert(rowstride(8, 4) == 4);
static_assert(rowstride(16, 4) == 8);
static_assert(rowstride(32, 4) == 16);
static_assert(rowstride(33, 4) == 20);
static_assert(rowstride(1, 8) == 4);
static_assert(rowstride(8, 8) == 8);
static_assert(rowstride(16, 8) == 16);
static_assert(rowstride(32, 8) == 32);
static_assert(rowstride(33, 8) == 36);
static_assert(rowstride(1, 24) == 4);
static_assert(rowstride(8, 24) == 24);
static_assert(rowstride(16, 24) == 48);
static_assert(rowstride(32, 24) == 96);
static_assert(rowstride(33, 24) == 100);
static_assert(rowstride(1, 32) == 4);
static_assert(rowstride(8, 32) == 32);
static_assert(rowstride(16, 32) == 64);
static_assert(rowstride(32, 32) == 128);
static_assert(rowstride(33, 32) == 132);
std::vector<std::byte> load_ico(const std::filesystem::path & filename, int size, int index = -1)
{
const uint32_t ICO_PNG_MAGIC = 0x474e5089;
auto ico = load_file(filename);
std::span header{ico};
auto reserved = read<uint16_t>(header);
auto resource_type = read<uint16_t>(header);
auto icon_count = read<uint16_t>(header);
if (reserved != 0 or resource_type != 1)
throw std::runtime_error{"Cannot read icon: " + filename.native()};
std::vector<ico_file_entry> entries;
int max_bpp = 0;
for (int i = 0; i < icon_count; i++)
{
ico_file_entry entry;
entry.width = read<uint8_t>(header);
entry.height = read<uint8_t>(header);
auto num_colors = read<uint8_t>(header);
auto reserved = read<uint8_t>(header); // reserved
auto planes = read<uint16_t>(header);
entry.bpp = read<uint16_t>(header);
auto size = read<uint32_t>(header);
auto offset = read<uint32_t>(header);
if (offset + size > ico.size())
throw std::runtime_error{"Cannot read icon: " + filename.native()};
entry.data = std::span{ico}.subspan(offset, size);
if (entry.width == 0)
entry.width = 256;
if (entry.height == 0)
entry.height = 256;
if (reserved != 0)
throw std::runtime_error{"Cannot read icon: " + filename.native()};
if (planes != 0 and planes != 1)
throw std::runtime_error{"Cannot read icon: " + filename.native()};
entries.push_back(entry);
max_bpp = std::max(max_bpp, entry.bpp);
}
const ico_file_entry * best_entry = index >= 0 ? &entries.at(index) : [&]() {
const ico_file_entry * best_entry = nullptr;
// Look for the smallest multiple of the requested size
int criterion = std::numeric_limits<int>::max();
for (const auto & entry: entries)
{
if (entry.bpp != max_bpp)
continue;
if (entry.width % size != 0 or entry.height % size != 0)
continue;
if (std::min(entry.width, entry.height) / size < criterion)
{
criterion = std::min(entry.width, entry.height);
best_entry = &entry;
}
}
if (best_entry)
return best_entry;
// No multiple found: pick the largest icon
criterion = 0;
for (const auto & entry: entries)
{
if (entry.bpp != max_bpp)
continue;
if (entry.width * entry.height > criterion)
{
criterion = entry.width * entry.height;
best_entry = &entry;
}
}
return best_entry;
}();
if (not best_entry)
return {};
auto data = best_entry->data;
auto magic = read<uint32_t>(data);
if (magic == ICO_PNG_MAGIC)
{
// PNG file
std::vector<std::byte> png_data;
// The PNG magic has already been consumed, put it back
png_data.insert(png_data.end(), data.begin() - 4, data.end());
// Check if the PNG is valid
std::vector<uint8_t> pixels;
png_image png_ref{
.version = PNG_IMAGE_VERSION,
.format = PNG_FORMAT_BGRA,
};
if (not png_image_begin_read_from_memory(&png_ref, png_data.data(), png_data.size()))
throw std::runtime_error{"Cannot read icon: " + filename.native()};
pixels.resize(PNG_IMAGE_SIZE(png_ref));
if (!png_image_finish_read(&png_ref, nullptr, pixels.data(), 0, nullptr))
{
png_image_free(&png_ref);
throw std::runtime_error{"Cannot read icon: " + filename.native()};
}
png_image_free(&png_ref);
return png_data;
}
else if (magic == 40)
{
auto width = read<uint32_t>(data); // Width of image in pixels
auto height = read<uint32_t>(data); // Height of image in pixels
auto planes = read<uint16_t>(data); // Must be 1
auto bpp = read<uint16_t>(data); // 1, 4, 8, 16, 24, 32
auto compression = read<uint32_t>(data); // Must be 0 for icons
auto image_size = read<uint32_t>(data); // Size of image (without this header)
auto x_res = read<uint32_t>(data);
auto y_res = read<uint32_t>(data);
auto used_colors = read<uint32_t>(data);
auto important_colors = read<uint32_t>(data);
if (planes != 1 or compression != 0)
return {};
if (bpp != 1 and
bpp != 4 and
bpp != 8 and
bpp != 16 and
bpp != 24 and
bpp != 32)
return {};
auto w = width;
auto h = height / 2;
std::span<uint8_t> palette; // BGRX
if (bpp <= 16)
{
// Load the palette
if (used_colors == 0)
used_colors = 1 << bpp;
palette = read<uint8_t>(data, used_colors * 4);
}
size_t xor_stride = rowstride(w, bpp);
size_t and_stride = rowstride(w, 1);
size_t dst_stride = 4 * w;
std::span<uint8_t> xor_map = read<uint8_t>(data, xor_stride * h);
std::span<uint8_t> and_map = read<uint8_t>(data, and_stride * h);
std::vector<uint8_t> dest_buffer;
dest_buffer.resize(h * dst_stride);
switch (bpp)
{
case 1:
for (int y = 0; y < h; y++)
{
uint8_t * src_xor_row = xor_map.data() + xor_stride * y;
uint8_t * src_and_row = and_map.data() + and_stride * y;
uint8_t * dst_row = dest_buffer.data() + dst_stride * (h - 1 - y);
for (int x = 0, i = 0; x < w; x++)
{
int colour = (src_xor_row[x / 8] >> (7 - (x % 8))) & 0x1;
if (colour >= used_colors)
return {};
uint8_t b = palette[4 * colour + 0]; // Blue
uint8_t g = palette[4 * colour + 1]; // Green
uint8_t r = palette[4 * colour + 2]; // Red
// Get alpha from AND mask (0: opaque => 0xff, 1: transparent => 0)
uint8_t a = src_and_row[x / 8] & (1 << (7 - x % 8)) ? 0 : 0xff;
*dst_row++ = b;
*dst_row++ = g;
*dst_row++ = r;
*dst_row++ = a;
}
}
break;
case 4:
for (int y = 0; y < h; y++)
{
uint8_t * src_xor_row = xor_map.data() + xor_stride * y;
uint8_t * src_and_row = and_map.data() + and_stride * y;
uint8_t * dst_row = dest_buffer.data() + dst_stride * (h - 1 - y);
for (int x = 0, i = 0; x < w; x++)
{
int colour = (src_xor_row[x / 2] >> (4 - 4 * (x % 2))) & 0xf;
if (colour >= used_colors)
return {};
uint8_t b = palette[4 * colour + 0]; // Blue
uint8_t g = palette[4 * colour + 1]; // Green
uint8_t r = palette[4 * colour + 2]; // Red
// Get alpha from AND mask (0: opaque => 0xff, 1: transparent => 0)
uint8_t a = src_and_row[x / 8] & (1 << (7 - x % 8)) ? 0 : 0xff;
*dst_row++ = b;
*dst_row++ = g;
*dst_row++ = r;
*dst_row++ = a;
}
}
break;
case 8:
for (int y = 0; y < h; y++)
{
uint8_t * src_xor_row = xor_map.data() + xor_stride * y;
uint8_t * src_and_row = and_map.data() + and_stride * y;
uint8_t * dst_row = dest_buffer.data() + dst_stride * (h - 1 - y);
for (int x = 0, i = 0; x < w; x++)
{
int colour = *src_xor_row++;
if (colour >= used_colors)
return {};
uint8_t b = palette[4 * colour + 0]; // Blue
uint8_t g = palette[4 * colour + 1]; // Green
uint8_t r = palette[4 * colour + 2]; // Red
// Get alpha from AND mask (0: opaque => 0xff, 1: transparent => 0)
uint8_t a = src_and_row[x / 8] & (1 << (7 - x % 8)) ? 0 : 0xff;
*dst_row++ = b;
*dst_row++ = g;
*dst_row++ = r;
*dst_row++ = a;
}
}
break;
case 16:
for (int y = 0; y < h; y++)
{
uint8_t * src_xor_row = xor_map.data() + xor_stride * y;
uint8_t * src_and_row = and_map.data() + and_stride * y;
uint8_t * dst_row = dest_buffer.data() + dst_stride * (h - 1 - y);
for (int x = 0, i = 0; x < w; x++)
{
int colour = (src_xor_row[1] << 8) | src_xor_row[0];
src_xor_row += 2;
if (colour >= used_colors)
return {};
uint8_t b = palette[4 * colour + 0]; // Blue
uint8_t g = palette[4 * colour + 1]; // Green
uint8_t r = palette[4 * colour + 2]; // Red
// Get alpha from AND mask (0: opaque => 0xff, 1: transparent => 0)
uint8_t a = src_and_row[x / 8] & (1 << (7 - x % 8)) ? 0 : 0xff;
*dst_row++ = b;
*dst_row++ = g;
*dst_row++ = r;
*dst_row++ = a;
}
}
break;
case 24:
for (int y = 0; y < h; y++)
{
uint8_t * src_xor_row = xor_map.data() + xor_stride * y;
uint8_t * src_and_row = and_map.data() + and_stride * y;
uint8_t * dst_row = dest_buffer.data() + dst_stride * (h - 1 - y);
for (int x = 0, i = 0; x < w; x++)
{
uint8_t b = *src_xor_row++; // Blue
uint8_t g = *src_xor_row++; // Green
uint8_t r = *src_xor_row++; // Red
// Get alpha from AND mask (0: opaque => 0xff, 1: transparent => 0)
uint8_t a = src_and_row[x / 8] & (1 << (7 - x % 8)) ? 0 : 0xff;
*dst_row++ = b;
*dst_row++ = g;
*dst_row++ = r;
*dst_row++ = a;
}
}
break;
case 32:
for (int y = 0; y < h; y++)
{
uint8_t * src_xor_row = (uint8_t *)xor_map.data() + xor_stride * y;
uint8_t * dst_row = dest_buffer.data() + dst_stride * (h - 1 - y);
memcpy(dst_row, src_xor_row, dst_stride);
}
break;
}
png_image png{
.version = PNG_IMAGE_VERSION,
.width = w,
.height = h,
.format = PNG_FORMAT_BGRA,
};
std::vector<std::byte> png_data{65536};
png_alloc_size_t png_size = png_data.size();
png_image_write_to_memory(&png, png_data.data(), &png_size, false /* convert_to_8_bit*/, dest_buffer.data(), w * 4, nullptr);
if (png_size > png_data.size())
{
png_data.resize(png_size);
png_image_write_to_memory(&png, png_data.data(), &png_size, false /* convert_to_8_bit*/, dest_buffer.data(), w * 4, nullptr);
}
else
png_data.resize(png_size);
return png_data;
}
throw std::runtime_error{"Wrong magic number in " + filename.native()};
}
std::vector<std::byte> load_zip(const std::filesystem::path & filename, int size)
{
std::unique_ptr<archive, decltype(&archive_read_free)> zip{archive_read_new(), &archive_read_free};
archive_read_support_filter_all(zip.get());
archive_read_support_format_all(zip.get());
if (auto rc = archive_read_open_filename(zip.get(), filename.c_str(), 1'000'000); rc != ARCHIVE_OK)
throw std::runtime_error{"Cannot open " + filename.native() + ": " + archive_error_string(zip.get())};
archive_entry * entry;
int width = 0;
int height = 0;
std::vector<std::byte> png;
while (archive_read_next_header(zip.get(), &entry) == ARCHIVE_OK)
{
printf("%s\n", archive_entry_pathname(entry));
std::vector<std::byte> buffer;
buffer.resize(archive_entry_size(entry));
if (auto status = archive_read_data(zip.get(), buffer.data(), buffer.size()); status < 0)
continue;
// Try reading the PNG
std::vector<uint8_t> pixels;
png_image png_ref{
.version = PNG_IMAGE_VERSION,
.format = PNG_FORMAT_BGRA,
};
if (not png_image_begin_read_from_memory(&png_ref, buffer.data(), buffer.size()))
{
png_image_free(&png_ref);
continue;
}
// Keep the largest icon only
if (png_ref.width * png_ref.height < width * height)
continue;
pixels.resize(PNG_IMAGE_SIZE(png_ref));
if (!png_image_finish_read(&png_ref, nullptr, pixels.data(), 0, nullptr))
{
png_image_free(&png_ref);
continue;
}
// PNG read successfully: keep it until we find a better one
width = png_ref.width;
height = png_ref.height;
png = std::move(buffer);
png_image_free(&png_ref);
}
return png;
}
std::unordered_map<std::filesystem::path, std::vector<std::byte>> icon_cache;
} // namespace
const std::vector<std::byte> & wivrn::load_icon(const std::filesystem::path & filename, int size)
{
auto it = icon_cache.find(filename);
if (it != icon_cache.end() and not it->second.empty())
return it->second;
std::vector<std::byte> icon;
if (filename.extension() == ".svg")
{
icon = load_svg(filename, size);
}
else if (filename.extension() == ".ico")
{
// Steam icon (Windows)
icon = load_ico(filename, size);
}
else if (filename.extension() == ".zip")
{
// Steam icon (Linux)
icon = load_zip(filename, size);
}
else
{
// TODO read arbitrary format / rewrite as png
icon = load_file(filename);
}
return icon_cache.emplace(filename, std::move(icon)).first->second;
}
+27
View File
@@ -0,0 +1,27 @@
/*
* 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 <vector>
namespace wivrn
{
const std::vector<std::byte> & load_icon(const std::filesystem::path & filename, int size);
}
+186
View File
@@ -0,0 +1,186 @@
/*
* 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 "steam_app_info.h"
#include <bit>
#include <cctype>
#include <cstring>
#include <fstream>
#include <span>
#include <string_view>
namespace
{
template <typename T>
T read(std::span<char> & buffer);
template <typename T>
requires std::is_integral_v<T>
T read(std::span<char> & buffer)
{
if (sizeof(T) > buffer.size())
throw std::runtime_error{"File truncated"};
T value;
memcpy(&value, buffer.data(), sizeof(T));
buffer = buffer.subspan(sizeof(T));
static_assert(std::endian::native == std::endian::big or std::endian::native == std::endian::little);
if constexpr (std::endian::native == std::endian::big)
return std::byteswap(value);
else
return value;
}
template <>
std::string_view read<std::string_view>(std::span<char> & buffer)
{
size_t size = strnlen((char *)buffer.data(), buffer.size());
if (size == buffer.size())
throw std::runtime_error{"File truncated"};
char * str = buffer.data();
buffer = buffer.subspan(size + 1);
return {str, size};
}
std::span<char> read(std::span<char> & buffer, size_t size)
{
if (size > buffer.size())
throw std::runtime_error{"File truncated"};
std::span<char> value{buffer.data(), size};
buffer = buffer.subspan(size);
return value;
}
std::vector<std::string_view> read_string_table(std::span<char> buffer)
{
std::vector<std::string_view> string_table;
uint32_t count = read<uint32_t>(buffer);
string_table.reserve(count);
for (size_t i = 0; i < count; i++)
string_table.emplace_back(read<std::string_view>(buffer));
return string_table;
}
void read_vdf(wivrn::steam_app_info::info & info, const std::string & prefix, std::span<char> & bindata, const std::vector<std::string_view> & string_table)
{
int type = read<uint8_t>(bindata);
while (type != 8)
{
std::string name{string_table.at(read<uint32_t>(bindata))};
for (char & c: name)
c = std::tolower(c);
// https://github.com/ValveResourceFormat/ValveKeyValue/blob/master/ValveKeyValue/ValveKeyValue/KeyValues1/KV1BinaryNodeType.cs
switch (type)
{
case 0: // Dictionary
read_vdf(info, prefix + name + ".", bindata, string_table);
break;
case 1: // UTF-8 string
info.emplace(prefix + name, read<std::string_view>(bindata));
break;
case 2: // uint32_t
info.emplace(prefix + name, read<uint32_t>(bindata));
break;
// case 3: // float
// break;
default:
throw std::runtime_error{"Unknown object type " + std::to_string(type)};
}
type = read<uint8_t>(bindata);
}
}
} // namespace
wivrn::steam_app_info::steam_app_info(std::filesystem::path path)
{
std::vector<std::string_view> string_table;
{
std::ifstream f{path};
data = std::vector<char>{std::istreambuf_iterator{f}, {}};
}
std::span<char> buffer = data;
// See https://github.com/SteamDatabase/SteamAppInfo/blob/master/README.md#file-header
uint32_t magic = read<uint32_t>(buffer);
if ((magic & 0xff'ff'ff'00) != 0x07'56'44'00)
throw std::runtime_error{"Wrong magic number"};
int version = magic & 0xff;
if (version < 41)
throw std::runtime_error{"Unsupported version"};
int universe = read<uint32_t>(buffer);
if (version >= 41)
{
size_t string_offset = read<uint64_t>(buffer);
string_table = read_string_table(std::span<char>{data}.subspan(string_offset));
}
else
throw std::runtime_error{"Unsupported version"};
while (true)
{
// See https://github.com/SteamDatabase/SteamAppInfo/blob/master/README.md#app-entry-repeated
auto app_id = read<uint32_t>(buffer);
if (app_id == 0)
break;
auto size_data = read<uint32_t>(buffer);
char * current_offset = buffer.data();
read<uint32_t>(buffer); // info_state
read<uint32_t>(buffer); // last_updated
read<uint64_t>(buffer); // pics_token
read(buffer, 20); // SHA1 of the app info
read<uint32_t>(buffer); // change number
// if (version < 38)
// read<uint8_t>(buffer); // section type
read(buffer, 20); // SHA1 of the bin data
auto bindata = read(buffer, size_data - (buffer.data() - current_offset));
try
{
bindata = bindata.subspan(4 + 1); // Skip the checksum + type (must be 0)
info app_info;
read_vdf(app_info, "", bindata, string_table);
app_data.emplace(app_id, app_info);
}
catch (...)
{
// Ignore errors
}
}
}
+51
View File
@@ -0,0 +1,51 @@
/*
* 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 <unordered_map>
#include <variant>
#include <vector>
namespace wivrn
{
class steam_app_info
{
public:
using info = std::unordered_map<std::string, std::variant<uint32_t, std::string_view>>;
private:
std::vector<char> data;
std::unordered_map<int, info> app_data;
public:
steam_app_info(std::filesystem::path path);
steam_app_info() = default;
steam_app_info(const steam_app_info &) = delete;
steam_app_info(steam_app_info &&) = default;
steam_app_info & operator=(const steam_app_info &) = delete;
steam_app_info & operator=(steam_app_info &&) = default;
const auto & get(int appid) const
{
return app_data.at(appid);
}
};
} // namespace wivrn
-7
View File
@@ -19,13 +19,6 @@
#include "strings.h"
std::string utils::trim(std::string input)
{
input.resize(input.find_last_not_of("\n ") + 1);
return input;
}
std::vector<std::string> utils::split(const std::string & s, const std::string & sep)
{
std::string::size_type i = 0;
-22
View File
@@ -19,32 +19,10 @@
#pragma once
#include <sstream>
#include <string>
#include <vector>
namespace utils
{
std::string trim(std::string input);
template <typename T>
std::string join(const std::vector<T> & vec, const std::string & sep = ", ")
{
std::stringstream s;
if (!vec.empty())
{
s << vec[0];
for (size_t i = 1, n = vec.size(); i < n; i++)
{
s << sep << vec[i];
}
}
return s.str();
}
std::vector<std::string> split(const std::string & s, const std::string & sep = "\n");
} // namespace utils
+10
View File
@@ -76,6 +76,16 @@ public:
{
return locked<T, Mutex>(value, mutex);
}
T & get_unsafe()
{
return value;
}
const T & get_unsafe() const
{
return value;
}
};
template <typename T>
+218
View File
@@ -0,0 +1,218 @@
/*
* 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 "xdg_icon_lookup.h"
#include "ini.h"
#include "strings.h"
#include "utils/flatpak.h"
#include "xdg_base_directory.h"
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <limits>
#include <optional>
namespace
{
enum class icon_theme_type
{
fixed,
scalable,
threshold
};
struct icon_theme_dir
{
std::filesystem::path path;
int size;
int scale;
icon_theme_type type;
int min_size;
int max_size;
int threshold;
bool match_size(int required_size, int required_scale) const
{
if (scale != required_scale)
return false;
switch (type)
{
case icon_theme_type::fixed:
return size == required_size;
case icon_theme_type::scalable:
return min_size <= required_size and required_size <= max_size;
case icon_theme_type::threshold:
return size - threshold <= required_size and required_size <= size + threshold;
}
return false;
}
int size_distance(int required_size, int required_scale) const
{
switch (type)
{
case icon_theme_type::fixed:
return abs(size * scale - required_size * required_scale);
case icon_theme_type::scalable:
if (required_size * required_scale < min_size * scale)
return min_size * scale - required_size * required_scale;
if (required_size * required_scale > max_size * scale)
return required_size * required_scale - max_size * scale;
return 0;
case icon_theme_type::threshold:
if (required_size * required_scale < (size - threshold) * scale)
return min_size * scale - required_size * required_scale;
if (required_size * required_scale > (size + threshold) * scale)
return required_size * required_scale - max_size * scale;
return 0;
}
return std::numeric_limits<int>::max();
}
};
void find_icon_theme_dirs_helper(const std::vector<std::filesystem::path> & base_dirs, std::vector<icon_theme_dir> & dirs, std::vector<std::string> & themes, std::string theme)
{
// Theme is passed by copy because the themes vector might be resized
for (const auto & base_dir: base_dirs)
{
const auto theme_dir = base_dir / "icons" / theme;
const auto index_theme = theme_dir / "index.theme";
if (not std::filesystem::exists(index_theme))
continue;
try
{
std::ifstream file{index_theme};
wivrn::ini index{file};
for (const auto & inherited_theme: utils::split(index.get<std::string>("Icon Theme", "Inherits", ""), ","))
{
if (inherited_theme != "" and not std::ranges::contains(themes, inherited_theme))
themes.push_back(inherited_theme);
}
for (auto directory: utils::split(index.get<std::string>("Icon Theme", "Directories", ""), ","))
{
int size = index.get<int>(directory, "Size");
int scale = index.get<int>(directory, "Scale", 1);
int min_size = index.get<int>(directory, "MinSize", size);
int max_size = index.get<int>(directory, "MaxSize", size);
int threshold = index.get<int>(directory, "Threshold", 2);
std::string type_str = index.get<std::string>(directory, "Type", "Threshold");
icon_theme_type type = icon_theme_type::threshold;
if (type_str == "Fixed")
type = icon_theme_type::fixed;
else if (type_str == "Scalable")
type = icon_theme_type::scalable;
else if (type_str == "Threshold")
type = icon_theme_type::threshold;
dirs.push_back(icon_theme_dir{
.path = theme_dir / directory,
.size = size,
.scale = scale,
.type = type,
.min_size = min_size,
.max_size = max_size,
.threshold = threshold,
});
}
}
catch (std::exception & e)
{
}
}
}
std::vector<icon_theme_dir> find_icon_theme_dirs(std::vector<std::string> themes)
{
std::vector<icon_theme_dir> dirs;
std::vector<std::filesystem::path> base_dirs = xdg_data_dirs();
if (wivrn::is_flatpak())
{
// Try to guess host data dirs
base_dirs.push_back("/run/host/usr/share");
}
for (size_t i = 0; i < themes.size(); ++i)
find_icon_theme_dirs_helper(base_dirs, dirs, themes, themes[i]);
if (not std::ranges::contains(themes, "hicolor"))
find_icon_theme_dirs_helper(base_dirs, dirs, themes, "hicolor");
return dirs;
}
} // namespace
std::optional<std::filesystem::path> wivrn::xdg_icon_lookup(const std::string & icon_name, int size, int scale)
{
if (std::filesystem::exists(icon_name))
return icon_name;
static const std::vector<icon_theme_dir> dirs = find_icon_theme_dirs({"hicolor"});
for (const auto & dir: dirs)
{
if (dir.match_size(size, scale))
{
for (const auto & ext: {".png", ".svg", ".xpm"})
{
if (std::filesystem::exists(dir.path / (icon_name + ext)))
return dir.path / (icon_name + ext);
}
}
}
int best_distance = std::numeric_limits<int>::max();
std::optional<std::filesystem::path> best_path;
for (const auto & dir: dirs)
{
if (dir.size_distance(size, scale) < best_distance)
{
for (const auto & ext: {".png", ".svg", ".xpm"})
{
if (std::filesystem::exists(dir.path / (icon_name + ext)))
{
best_distance = dir.size_distance(size, scale);
best_path = dir.path / (icon_name + ext);
}
}
}
}
return best_path;
}
+28
View File
@@ -0,0 +1,28 @@
/*
* 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 <optional>
#include <string>
namespace wivrn
{
std::optional<std::filesystem::path> xdg_icon_lookup(const std::string & icon_name, int size, int scale = 1);
}
+156 -75
View File
@@ -34,7 +34,6 @@
#include "smp.h"
#include "wivrn_serialization_types.h"
#include "xr/pico_eye_types.h"
namespace wivrn
{
@@ -42,86 +41,103 @@ namespace wivrn
// Default port for server to listen, both TCP and UDP
static const int default_port = 9757;
static constexpr int protocol_revision = 2;
static constexpr int protocol_revision = 1;
enum class device_id : uint8_t
{
HEAD, // /user/head
LEFT_CONTROLLER_HAPTIC, // /user/hand/left/output/haptic
RIGHT_CONTROLLER_HAPTIC, // /user/hand/right/output/haptic
LEFT_TRIGGER_HAPTIC, // /user/hand/left/output/haptic_trigger
RIGHT_TRIGGER_HAPTIC, // /user/hand/right/output/haptic_trigger
LEFT_THUMB_HAPTIC, // /user/hand/left/output/haptic_thumb
RIGHT_THUMB_HAPTIC, // /user/hand/right/output/haptic_thumb
LEFT_GRIP, // /user/hand/left/input/grip/pose
LEFT_AIM, // /user/hand/left/input/aim/pose
LEFT_PALM, // /user/hand/left/palm_ext/pose
RIGHT_GRIP, // /user/hand/right/input/grip/pose
RIGHT_AIM, // /user/hand/right/input/aim/pose
RIGHT_PALM, // /user/hand/right/palm_ext/pose
X_CLICK, // /user/hand/left/input/x/click
X_TOUCH, // /user/hand/left/input/x/touch
Y_CLICK, // /user/hand/left/input/y/click
Y_TOUCH, // /user/hand/left/input/y/touch
MENU_CLICK, // /user/hand/left/input/menu/click
LEFT_SQUEEZE_CLICK, // /user/hand/left/input/squeeze/click
LEFT_SQUEEZE_FORCE, // /user/hand/left/input/squeeze/force
LEFT_SQUEEZE_VALUE, // /user/hand/left/input/squeeze/value
LEFT_TRIGGER_CLICK, // /user/hand/left/input/trigger/click
LEFT_TRIGGER_VALUE, // /user/hand/left/input/trigger/value
LEFT_TRIGGER_TOUCH, // /user/hand/left/input/trigger/touch
LEFT_TRIGGER_PROXIMITY, // /user/hand/left/input/trigger/proximity
LEFT_TRIGGER_CURL, // /user/hand/left/input/trigger/curl_fb
LEFT_TRIGGER_SLIDE, // /user/hand/left/input/trigger/slide_fb
LEFT_TRIGGER_FORCE, // /user/hand/left/input/trigger/force
LEFT_THUMBSTICK_X, // /user/hand/left/input/thumbstick/x
LEFT_THUMBSTICK_Y, // /user/hand/left/input/thumbstick/y
LEFT_THUMBSTICK_CLICK, // /user/hand/left/input/thumbstick/click
LEFT_THUMBSTICK_TOUCH, // /user/hand/left/input/thumbstick/touch
LEFT_THUMBREST_TOUCH, // /user/hand/left/input/thumbrest/touch
LEFT_THUMBREST_FORCE, // /user/hand/left/input/thumbrest/force
LEFT_THUMB_PROXIMITY, // /user/hand/left/input/thumb_resting_surfaces/proximity
LEFT_TRACKPAD_X, // /user/hand/left/input/trackpad/x
LEFT_TRACKPAD_Y, // /user/hand/left/input/trackpad/y
LEFT_TRACKPAD_CLICK, // /user/hand/left/input/trackpad/click
LEFT_TRACKPAD_TOUCH, // /user/hand/left/input/trackpad/touch
LEFT_TRACKPAD_FORCE, // /user/hand/left/input/trackpad/force
LEFT_STYLUS_FORCE, // /user/hand/left/input/stylus_fb/force
A_CLICK, // /user/hand/right/input/a/click
A_TOUCH, // /user/hand/right/input/a/touch
B_CLICK, // /user/hand/right/input/b/click
B_TOUCH, // /user/hand/right/input/b/touch
SYSTEM_CLICK, // /user/hand/right/input/system/click
RIGHT_SQUEEZE_CLICK, // /user/hand/right/input/squeeze/click
RIGHT_SQUEEZE_FORCE, // /user/hand/right/input/squeeze/force
RIGHT_SQUEEZE_VALUE, // /user/hand/right/input/squeeze/value
RIGHT_TRIGGER_CLICK, // /user/hand/right/input/trigger/click
RIGHT_TRIGGER_VALUE, // /user/hand/right/input/trigger/value
RIGHT_TRIGGER_TOUCH, // /user/hand/right/input/trigger/touch
RIGHT_TRIGGER_PROXIMITY, // /user/hand/right/input/trigger/proximity
RIGHT_TRIGGER_CURL, // /user/hand/right/input/trigger/curl_fb
RIGHT_TRIGGER_SLIDE, // /user/hand/right/input/trigger/slide_fb
RIGHT_TRIGGER_FORCE, // /user/hand/right/input/trigger/force
RIGHT_THUMBSTICK_X, // /user/hand/right/input/thumbstick/x
RIGHT_THUMBSTICK_Y, // /user/hand/right/input/thumbstick/y
RIGHT_THUMBSTICK_CLICK, // /user/hand/right/input/thumbstick/click
RIGHT_THUMBSTICK_TOUCH, // /user/hand/right/input/thumbstick/touch
RIGHT_THUMBREST_TOUCH, // /user/hand/right/input/thumbrest/touch
RIGHT_THUMBREST_FORCE, // /user/hand/right/input/thumbrest/force
RIGHT_THUMB_PROXIMITY, // /user/hand/right/input/thumb_resting_surfaces/proximity
RIGHT_TRACKPAD_X, // /user/hand/right/input/trackpad/x
RIGHT_TRACKPAD_Y, // /user/hand/right/input/trackpad/y
RIGHT_TRACKPAD_CLICK, // /user/hand/right/input/trackpad/click
RIGHT_TRACKPAD_TOUCH, // /user/hand/right/input/trackpad/touch
RIGHT_TRACKPAD_FORCE, // /user/hand/right/input/trackpad/force
RIGHT_STYLUS_FORCE, // /user/hand/right/input/stylus_fb/force
EYE_GAZE, // /user/eyes_ext/input/gaze_ext/pose
HEAD, // /user/head
LEFT_CONTROLLER_HAPTIC, // /user/hand/left/output/haptic
RIGHT_CONTROLLER_HAPTIC, // /user/hand/right/output/haptic
LEFT_TRIGGER_HAPTIC, // /user/hand/left/output/haptic_trigger
RIGHT_TRIGGER_HAPTIC, // /user/hand/right/output/haptic_trigger
LEFT_THUMB_HAPTIC, // /user/hand/left/output/haptic_thumb
RIGHT_THUMB_HAPTIC, // /user/hand/right/output/haptic_thumb
LEFT_GRIP, // /user/hand/left/input/grip/pose
LEFT_AIM, // /user/hand/left/input/aim/pose
LEFT_PALM, // /user/hand/left/palm_ext/pose
RIGHT_GRIP, // /user/hand/right/input/grip/pose
RIGHT_AIM, // /user/hand/right/input/aim/pose
RIGHT_PALM, // /user/hand/right/palm_ext/pose
X_CLICK, // /user/hand/left/input/x/click
X_TOUCH, // /user/hand/left/input/x/touch
Y_CLICK, // /user/hand/left/input/y/click
Y_TOUCH, // /user/hand/left/input/y/touch
MENU_CLICK, // /user/hand/left/input/menu/click
LEFT_SQUEEZE_CLICK, // /user/hand/left/input/squeeze/click
LEFT_SQUEEZE_FORCE, // /user/hand/left/input/squeeze/force
LEFT_SQUEEZE_VALUE, // /user/hand/left/input/squeeze/value
LEFT_TRIGGER_CLICK, // /user/hand/left/input/trigger/click
LEFT_TRIGGER_VALUE, // /user/hand/left/input/trigger/value
LEFT_TRIGGER_TOUCH, // /user/hand/left/input/trigger/touch
LEFT_TRIGGER_PROXIMITY, // /user/hand/left/input/trigger/proximity
LEFT_TRIGGER_CURL, // /user/hand/left/input/trigger/curl_fb
LEFT_TRIGGER_SLIDE, // /user/hand/left/input/trigger/slide_fb
LEFT_TRIGGER_FORCE, // /user/hand/left/input/trigger/force
LEFT_THUMBSTICK_X, // /user/hand/left/input/thumbstick/x
LEFT_THUMBSTICK_Y, // /user/hand/left/input/thumbstick/y
LEFT_THUMBSTICK_CLICK, // /user/hand/left/input/thumbstick/click
LEFT_THUMBSTICK_TOUCH, // /user/hand/left/input/thumbstick/touch
LEFT_THUMBREST_TOUCH, // /user/hand/left/input/thumbrest/touch
LEFT_THUMBREST_FORCE, // /user/hand/left/input/thumbrest/force
LEFT_THUMB_PROXIMITY, // /user/hand/left/input/thumb_resting_surfaces/proximity
LEFT_TRACKPAD_X, // /user/hand/left/input/trackpad/x
LEFT_TRACKPAD_Y, // /user/hand/left/input/trackpad/y
LEFT_TRACKPAD_CLICK, // /user/hand/left/input/trackpad/click
LEFT_TRACKPAD_TOUCH, // /user/hand/left/input/trackpad/touch
LEFT_TRACKPAD_FORCE, // /user/hand/left/input/trackpad/force
LEFT_STYLUS_FORCE, // /user/hand/left/input/stylus_fb/force
LEFT_PINCH_POSE, // /user/hand/left/input/pinch_ext/pose
LEFT_PINCH_VALUE, // /user/hand/left/input/pinch_ext/value
LEFT_PINCH_READY, // /user/hand/left/input/pinch_ext/ready_ext
LEFT_POKE, // /user/hand/left/input/poke_ext/pose
LEFT_AIM_ACTIVATE_VALUE, // /user/hand/left/input/aim_activate_ext/value
LEFT_AIM_ACTIVATE_READY, // /user/hand/left/input/aim_activate_ext/ready_ext
LEFT_GRASP_VALUE, // /user/hand/left/input/grasp_ext/value
LEFT_GRASP_READY, // /user/hand/left/input/grasp_ext/ready_ext
A_CLICK, // /user/hand/right/input/a/click
A_TOUCH, // /user/hand/right/input/a/touch
B_CLICK, // /user/hand/right/input/b/click
B_TOUCH, // /user/hand/right/input/b/touch
SYSTEM_CLICK, // /user/hand/right/input/system/click
RIGHT_SQUEEZE_CLICK, // /user/hand/right/input/squeeze/click
RIGHT_SQUEEZE_FORCE, // /user/hand/right/input/squeeze/force
RIGHT_SQUEEZE_VALUE, // /user/hand/right/input/squeeze/value
RIGHT_TRIGGER_CLICK, // /user/hand/right/input/trigger/click
RIGHT_TRIGGER_VALUE, // /user/hand/right/input/trigger/value
RIGHT_TRIGGER_TOUCH, // /user/hand/right/input/trigger/touch
RIGHT_TRIGGER_PROXIMITY, // /user/hand/right/input/trigger/proximity
RIGHT_TRIGGER_CURL, // /user/hand/right/input/trigger/curl_fb
RIGHT_TRIGGER_SLIDE, // /user/hand/right/input/trigger/slide_fb
RIGHT_TRIGGER_FORCE, // /user/hand/right/input/trigger/force
RIGHT_THUMBSTICK_X, // /user/hand/right/input/thumbstick/x
RIGHT_THUMBSTICK_Y, // /user/hand/right/input/thumbstick/y
RIGHT_THUMBSTICK_CLICK, // /user/hand/right/input/thumbstick/click
RIGHT_THUMBSTICK_TOUCH, // /user/hand/right/input/thumbstick/touch
RIGHT_THUMBREST_TOUCH, // /user/hand/right/input/thumbrest/touch
RIGHT_THUMBREST_FORCE, // /user/hand/right/input/thumbrest/force
RIGHT_THUMB_PROXIMITY, // /user/hand/right/input/thumb_resting_surfaces/proximity
RIGHT_TRACKPAD_X, // /user/hand/right/input/trackpad/x
RIGHT_TRACKPAD_Y, // /user/hand/right/input/trackpad/y
RIGHT_TRACKPAD_CLICK, // /user/hand/right/input/trackpad/click
RIGHT_TRACKPAD_TOUCH, // /user/hand/right/input/trackpad/touch
RIGHT_TRACKPAD_FORCE, // /user/hand/right/input/trackpad/force
RIGHT_STYLUS_FORCE, // /user/hand/right/input/stylus_fb/force
RIGHT_PINCH_POSE, // /user/hand/right/input/pinch_ext/pose
RIGHT_PINCH_VALUE, // /user/hand/right/input/pinch_ext/value
RIGHT_PINCH_READY, // /user/hand/right/input/pinch_ext/ready_ext
RIGHT_POKE, // /user/hand/right/input/poke_ext/pose
RIGHT_AIM_ACTIVATE_VALUE, // /user/hand/right/input/aim_activate_ext/value
RIGHT_AIM_ACTIVATE_READY, // /user/hand/right/input/aim_activate_ext/ready_ext
RIGHT_GRASP_VALUE, // /user/hand/right/input/grasp_ext/value
RIGHT_GRASP_READY, // /user/hand/right/input/grasp_ext/ready_ext
EYE_GAZE, // /user/eyes_ext/input/gaze_ext/pose
};
enum class interaction_profile : uint8_t
{
none,
khr_simple_controller,
ext_hand_interaction_ext,
bytedance_pico_neo3_controller,
bytedance_pico4_controller,
bytedance_pico4s_controller,
@@ -165,6 +181,7 @@ namespace from_headset
{
struct crypto_handshake
{
uint64_t protocol_version;
std::string public_key; // In PEM format
std::string name;
};
@@ -198,7 +215,6 @@ enum face_type : uint8_t
none,
fb2,
htc,
pico,
};
struct headset_info_packet
@@ -223,6 +239,11 @@ struct headset_info_packet
uint32_t num_generic_trackers;
std::vector<video_codec> supported_codecs; // from preferred to least preferred
std::string system_name;
// Used for the application list
std::string language;
std::string country;
std::string variant;
};
struct handshake
@@ -410,6 +431,35 @@ struct refresh_rate_changed
float to;
};
struct session_state_changed
{
XrSessionState state;
};
struct user_presence_changed
{
bool present;
};
struct override_foveation_center
{
bool enabled;
float pitch;
float distance;
};
struct get_application_list
{
std::string language;
std::string country;
std::string variant;
};
struct start_app
{
std::string app_id;
};
using packets = std::variant<
crypto_handshake,
pin_check_1,
@@ -427,7 +477,12 @@ using packets = std::variant<
timesync_response,
battery,
visibility_mask_changed,
refresh_rate_changed>;
refresh_rate_changed,
session_state_changed,
user_presence_changed,
override_foveation_center,
get_application_list,
start_app>;
} // namespace from_headset
namespace to_headset
@@ -441,6 +496,7 @@ struct crypto_handshake
pin_needed,
client_already_paired,
pairing_disabled,
incompatible_version,
};
std::string public_key; // In PEM format
@@ -589,9 +645,13 @@ struct tracking_control
left_aim,
left_grip,
left_palm,
left_pinch,
left_poke,
right_aim,
right_grip,
right_palm,
right_pinch,
right_poke,
left_hand,
right_hand,
face,
@@ -611,6 +671,25 @@ struct refresh_rate_change
float fps;
};
struct application_list
{
std::string language;
std::string country;
std::string variant;
struct application
{
std::string id;
std::string name;
};
std::vector<application> applications;
};
struct application_icon
{
std::string id;
std::vector<std::byte> image; // In PNG
};
using packets = std::variant<
crypto_handshake,
pin_check_2,
@@ -623,6 +702,8 @@ using packets = std::variant<
haptics,
timesync_query,
tracking_control,
refresh_rate_change>;
refresh_rate_change,
application_list,
application_icon>;
} // namespace to_headset
} // namespace wivrn
+75 -24
View File
@@ -28,6 +28,7 @@
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <optional>
#include <span>
#include <stdexcept>
@@ -88,15 +89,6 @@ struct hash_context
};
} // namespace details
template <typename T, typename Enable = void>
struct serialization_traits;
template <typename T>
size_t serialized_size(const T & x)
{
return serialization_traits<T>::size(x);
}
class deserialization_error : public std::runtime_error
{
static std::string hexdump(std::span<uint8_t> raw_data)
@@ -124,6 +116,32 @@ public:
std::runtime_error("Deserialization error\n" + hexdump(raw_data)) {}
};
class serialization_error : public std::runtime_error
{
public:
serialization_error() :
std::runtime_error("Serialization error") {}
};
template <typename T, typename Enable = void>
struct serialization_traits;
template <typename T>
size_t serialized_size(const T & x)
{
return serialization_traits<T>::size(x);
}
constexpr size_t serialized_size_of_size(size_t size)
{
if (size < 0x7fff)
return sizeof(uint16_t);
else if (size < 0x7fff'ffff)
return 2 * sizeof(uint16_t);
else
throw serialization_error{};
}
class serialization_packet
{
std::vector<uint8_t> buffer;
@@ -165,6 +183,23 @@ public:
serialization_traits<T>::serialize(value, *this);
}
constexpr void serialize_size(size_t size)
{
if (size < 0x7fff)
{
serialize<uint16_t>(size);
}
else if (size < 0x7fff'ffff)
{
serialize<uint16_t>((size & 0x7fff) | 0x8000);
serialize<uint16_t>(size >> 15);
}
else
{
throw serialization_error{};
}
}
operator std::vector<std::span<uint8_t>> *()
{
return &this->operator std::vector<std::span<uint8_t>> &();
@@ -243,6 +278,16 @@ public:
return serialization_traits<T>::deserialize(*this);
}
size_t deserialize_size()
{
size_t size = deserialize<uint16_t>();
if (size & 0x8000)
size = (size & 0x7fff) | (deserialize<uint16_t>() << 15);
return size;
}
template <typename T>
void deserialize(T & v)
{
@@ -394,6 +439,7 @@ struct serialize_bits<T, std::tuple<std::integer_sequence<size_t, i, mid...>, Bi
return (sizeof(boost::pfr::tuple_element_t<mid, T>) + ... + sizeof(boost::pfr::tuple_element_t<i, T>)) + serialize_bits<T, std::tuple<Bits...>>::size(t);
}
};
} // namespace details
template <typename T>
@@ -554,14 +600,14 @@ struct serialization_traits<std::string>
static void serialize(const std::string & value, serialization_packet & packet)
{
packet.serialize<uint16_t>(value.size());
packet.serialize_size(value.size());
packet.write(value.data(), value.size());
}
static std::string deserialize(deserialization_packet & packet)
{
std::string value;
size_t size = packet.deserialize<uint16_t>();
size_t size = packet.deserialize_size();
packet.check_remaining_size(size);
@@ -576,7 +622,7 @@ struct serialization_traits<std::string>
}
static size_t size(const std::string & value)
{
return sizeof(uint16_t) + value.size();
return serialized_size_of_size(value.size()) + value.size();
}
};
@@ -592,7 +638,7 @@ struct serialization_traits<std::vector<T>>
static void serialize(const std::vector<T> & value, serialization_packet & packet)
{
packet.serialize<uint16_t>(value.size());
packet.serialize_size(value.size());
if constexpr (serialization_traits<T>::is_trivially_serializable())
{
@@ -608,7 +654,7 @@ struct serialization_traits<std::vector<T>>
static std::vector<T> deserialize(deserialization_packet & packet)
{
std::vector<T> value;
size_t size = packet.deserialize<uint16_t>();
size_t size = packet.deserialize_size();
if constexpr (serialization_traits<T>::is_trivially_serializable())
{
@@ -635,10 +681,10 @@ struct serialization_traits<std::vector<T>>
static size_t size(const std::vector<T> & value)
{
if constexpr (is_trivially_serializable())
return sizeof(uint16_t) + value.size() * sizeof(T);
return serialized_size_of_size(value.size()) + value.size() * sizeof(T);
else
{
size_t res = sizeof(uint16_t);
size_t res = serialized_size_of_size(value.size());
for (const auto & item: value)
res += serialized_size(item);
return res;
@@ -756,6 +802,9 @@ struct serialization_traits<std::array<T, N>>
template <typename... T>
struct serialization_traits<std::variant<T...>>
{
using size_type = uint8_t;
static_assert(sizeof...(T) <= std::numeric_limits<size_type>::max() + 1);
template <typename U, typename... V>
static constexpr void type_list_hash(details::hash_context & h)
{
@@ -777,7 +826,7 @@ struct serialization_traits<std::variant<T...>>
static void serialize(const std::variant<T...> & value, serialization_packet & packet)
{
packet.serialize<uint8_t>(value.index());
packet.serialize<size_type>(value.index());
std::visit([&](const auto & x) { packet.serialize(x); }, value);
}
@@ -794,7 +843,7 @@ struct serialization_traits<std::variant<T...>>
static std::variant<T...> deserialize(deserialization_packet & packet)
{
uint8_t type_index = packet.deserialize<uint8_t>();
size_type type_index = packet.deserialize<size_type>();
if (type_index >= sizeof...(T))
throw deserialization_error(packet.initial_buffer);
@@ -807,7 +856,7 @@ struct serialization_traits<std::variant<T...>>
static size_t size(const std::variant<T...> & value)
{
return 1 + std::visit([](const auto & x) { return serialized_size(x); }, value);
return sizeof(size_type) + std::visit([](const auto & x) { return serialized_size(x); }, value);
}
};
@@ -857,22 +906,24 @@ struct serialization_traits<std::span<uint8_t>>
static void serialize(const std::span<uint8_t> & value, serialization_packet & packet)
{
packet.serialize<uint16_t>(value.size());
packet.serialize_size(value.size());
packet.write(value);
}
static std::span<uint8_t> deserialize(deserialization_packet & packet)
{
size_t size = packet.deserialize<uint16_t>();
size_t size = packet.deserialize_size();
return packet.read_span(size);
}
static bool consteval is_trivially_serializable()
{
return false;
}
static size_t size(const std::span<uint8_t> & x)
static size_t size(const std::span<uint8_t> & value)
{
return 1 + x.size_bytes();
return serialized_size_of_size(value.size()) + value.size_bytes();
}
};
@@ -929,7 +980,7 @@ struct serialization_traits<crypto::bignum>
static size_t size(const crypto::bignum & value)
{
return 2 + value.data_size();
return serialized_size_of_size(value.data_size()) + value.data_size();
}
};
+11 -11
View File
@@ -34,21 +34,21 @@ static_assert(hash(1234) == 0x1fabbdf10314a21d);
static_assert(hash(-1234) == 0x77fa1c9653db5a84);
static_assert(hash(0) == 0xaf63ad4c86019caf);
static_assert(serialization_type_hash<bool>() == hash("uint8"));
static_assert(serialization_type_hash<int>() == hash("int32"));
static_assert(serialization_type_hash<float>() == hash("float32"));
static_assert(serialization_type_hash<double>() == hash("float64"));
static_assert(serialization_type_hash<std::chrono::nanoseconds>() == hash("duration<int64,1/1000000000>"));
static_assert(serialization_type_hash<std::optional<int>>() == hash("optional<int32>"));
static_assert(serialization_type_hash<std::vector<int>>() == hash("vector<int32>"));
static_assert(serialization_type_hash<std::array<int, 42>>() == hash("array<int32,42>"));
static_assert(serialization_type_hash<std::string>() == hash("string"));
static_assert(serialization_type_hash<std::variant<int, float>>() == hash("variant<int32,float32>"));
static_assert(serialization_type_hash<bool>(0) == hash("uint8"));
static_assert(serialization_type_hash<int>(0) == hash("int32"));
static_assert(serialization_type_hash<float>(0) == hash("float32"));
static_assert(serialization_type_hash<double>(0) == hash("float64"));
static_assert(serialization_type_hash<std::chrono::nanoseconds>(0) == hash("duration<int64,1/1000000000>"));
static_assert(serialization_type_hash<std::optional<int>>(0) == hash("optional<int32>"));
static_assert(serialization_type_hash<std::vector<int>>(0) == hash("vector<int32>"));
static_assert(serialization_type_hash<std::array<int, 42>>(0) == hash("array<int32,42>"));
static_assert(serialization_type_hash<std::string>(0) == hash("string"));
static_assert(serialization_type_hash<std::variant<int, float>>(0) == hash("variant<int32,float32>"));
struct test
{
int x;
float y;
};
static_assert(serialization_type_hash<test>() == hash("structure{int32,float32}"));
static_assert(serialization_type_hash<test>(0) == hash("structure{int32,float32}"));
} // namespace
+16 -16
View File
@@ -471,14 +471,14 @@ wivrn::deserialization_packet wivrn::TCP::receive_raw()
{
ssize_t expected_size;
if (data.size_bytes() < sizeof(uint16_t))
if (data.size_bytes() < sizeof(uint32_t))
{
expected_size = sizeof(uint16_t) - data.size_bytes();
expected_size = sizeof(uint32_t) - data.size_bytes();
}
else
{
uint32_t payload_size = *reinterpret_cast<uint16_t *>(data.data());
expected_size = payload_size + sizeof(uint16_t) - data.size_bytes();
uint32_t payload_size = *reinterpret_cast<uint32_t *>(data.data());
expected_size = payload_size + sizeof(uint32_t) - data.size_bytes();
}
if (expected_size > capacity_left)
@@ -518,35 +518,35 @@ wivrn::deserialization_packet wivrn::TCP::receive_raw()
capacity_left -= received_size;
}
if (data.size_bytes() < sizeof(uint16_t))
if (data.size_bytes() < sizeof(uint32_t))
return {};
uint32_t payload_size = *reinterpret_cast<uint16_t *>(data.data());
uint32_t payload_size = *reinterpret_cast<uint32_t *>(data.data());
if (payload_size == 0)
throw std::runtime_error("Invalid packet: 0 size");
if (data.size_bytes() < sizeof(uint16_t) + payload_size)
if (data.size_bytes() < sizeof(uint32_t) + payload_size)
return {};
auto span = data.subspan(sizeof(uint16_t), payload_size);
data = data.subspan(sizeof(uint16_t) + payload_size);
auto span = data.subspan(sizeof(uint32_t), payload_size);
data = data.subspan(sizeof(uint32_t) + payload_size);
return deserialization_packet{buffer, span};
}
wivrn::deserialization_packet wivrn::TCP::receive_pending()
{
if (data.size_bytes() < sizeof(uint16_t))
if (data.size_bytes() < sizeof(uint32_t))
return {};
uint32_t payload_size = *reinterpret_cast<uint16_t *>(data.data());
uint32_t payload_size = *reinterpret_cast<uint32_t *>(data.data());
if (payload_size == 0)
throw std::runtime_error("Invalid packet: 0 size");
if (data.size_bytes() < sizeof(uint16_t) + payload_size)
if (data.size_bytes() < sizeof(uint32_t) + payload_size)
return {};
auto span = data.subspan(sizeof(uint16_t), payload_size);
data = data.subspan(sizeof(uint16_t) + payload_size);
auto span = data.subspan(sizeof(uint32_t), payload_size);
data = data.subspan(sizeof(uint32_t) + payload_size);
return deserialization_packet{buffer, span};
}
@@ -557,7 +557,7 @@ void wivrn::TCP::send_raw(serialization_packet && packet)
std::vector<std::span<uint8_t>> & data = packet;
uint16_t size = 0;
uint32_t size = 0;
iovecs.emplace_back(&size, sizeof(size));
for (const auto & span: data)
{
@@ -611,7 +611,7 @@ void wivrn::TCP::send_raw(serialization_packet && packet)
void wivrn::TCP::send_many_raw(std::span<serialization_packet> packets)
{
thread_local std::vector<iovec> iovecs;
thread_local std::vector<uint16_t> sizes;
thread_local std::vector<uint32_t> sizes;
thread_local std::vector<std::span<uint8_t>> spans;
if (packets.empty())

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