Initial commit
Co-authored-by: Patrick Nicolas <patricknicolas@laposte.net>
This commit is contained in:
+11
@@ -0,0 +1,11 @@
|
||||
*~
|
||||
.cxx/
|
||||
.gradle/
|
||||
_deps/
|
||||
|
||||
build/
|
||||
build-*/
|
||||
|
||||
*.so
|
||||
a.out
|
||||
*.pgm
|
||||
@@ -0,0 +1,76 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
package="org.meumeu.wivrn"
|
||||
android:installLocation="auto">
|
||||
|
||||
<!-- Tell the system this app works in either 3dof or 6dof mode -->
|
||||
<uses-feature android:name="android.hardware.vr.headtracking" android:required="true" android:version="1" />
|
||||
|
||||
<!-- Allow starting the application even without controllers -->
|
||||
<uses-feature android:name="oculus.software.handtracking" android:required="false" />
|
||||
<uses-permission android:name="com.oculus.permission.HAND_TRACKING" />
|
||||
|
||||
<!-- Required for XR_FB_render_model -->
|
||||
<uses-feature android:name="com.oculus.feature.RENDER_MODEL" android:required="false" />
|
||||
<uses-permission android:name="com.oculus.permission.RENDER_MODEL" />
|
||||
|
||||
<uses-sdk android:minSdkVersion="29" />
|
||||
|
||||
<!-- If building externally with the OpenXR AAR, this would be merged in automatically. -->
|
||||
<uses-permission android:name="org.khronos.openxr.permission.OPENXR" />
|
||||
<uses-permission android:name="org.khronos.openxr.permission.OPENXR_SYSTEM" />
|
||||
|
||||
<!-- Allow network access -->
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
|
||||
<queries tools:ignore="ExportedContentProvider">
|
||||
<provider android:authorities="org.khronos.openxr.runtime_broker;org.khronos.openxr.system_runtime_broker" />
|
||||
</queries>
|
||||
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:hasCode="false"
|
||||
android:icon="@mipmap/ic_wivrn_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_wivrn_launcher">
|
||||
|
||||
<profileable android:shell="true" />
|
||||
<meta-data android:name="com.oculus.intent.category.VR" android:value="vr_only"/>
|
||||
<meta-data android:name="com.oculus.supportedDevices" android:value="quest|quest2|cambria"/>
|
||||
|
||||
<!-- 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. -->
|
||||
<!-- Theme.Black.NoTitleBar.Fullscreen gives solid black instead of a (bad stereoscopic) gradient on app transition. -->
|
||||
<activity
|
||||
android:exported="true"
|
||||
android:name="android.app.NativeActivity"
|
||||
android:configChanges="screenSize|screenLayout|orientation|keyboardHidden|keyboard|navigation|uiMode|density"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleTask"
|
||||
android:resizeableActivity="false"
|
||||
android:screenOrientation="landscape"
|
||||
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
|
||||
tools:ignore="NonResizeableActivity">
|
||||
|
||||
<!-- Tell NativeActivity the name of the .so -->
|
||||
<meta-data
|
||||
android:name="android.app.lib_name"
|
||||
android:value="WiVRn" />
|
||||
|
||||
|
||||
<!-- This filter lets the apk show up as a launchable icon. -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="com.oculus.intent.category.VR" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
<category android:name="org.khronos.openxr.intent.category.IMMERSIVE_HMD" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
cmake_minimum_required(VERSION 3.19)
|
||||
project(WiVRn VERSION 1.0 LANGUAGES C CXX)
|
||||
|
||||
|
||||
option(USE_SYSTEM_FREETYPE "Use system FreeType" ON)
|
||||
|
||||
set(TINYGLTF_BUILD_LOADER_EXAMPLE OFF)
|
||||
set(TINYGLTF_BUILD_GL_EXAMPLES OFF)
|
||||
set(TINYGLTF_BUILD_VALIDATOR_EXAMPLE OFF)
|
||||
set(TINYGLTF_BUILD_BUILDER_EXAMPLE OFF)
|
||||
set(TINYGLTF_HEADER_ONLY OFF)
|
||||
set(TINYGLTF_INSTALL OFF)
|
||||
|
||||
include(FetchContent)
|
||||
include(ExternalProject)
|
||||
|
||||
FetchContent_Declare(spdlog
|
||||
GIT_REPOSITORY https://github.com/gabime/spdlog.git
|
||||
GIT_TAG v1.10.0)
|
||||
|
||||
FetchContent_Declare(boostpfr
|
||||
GIT_REPOSITORY https://github.com/boostorg/pfr.git
|
||||
GIT_TAG 69c5692cd666b1685a5eef00a4a79ca2e6093ff0)
|
||||
|
||||
FetchContent_Declare(glm
|
||||
GIT_REPOSITORY https://github.com/g-truc/glm.git
|
||||
GIT_TAG 0.9.9.8)
|
||||
|
||||
FetchContent_Declare(tinygltf
|
||||
GIT_REPOSITORY https://github.com/syoyo/tinygltf.git
|
||||
GIT_TAG v2.6.3)
|
||||
|
||||
if (USE_SYSTEM_FREETYPE)
|
||||
find_package(Freetype REQUIRED)
|
||||
find_package(harfbuzz REQUIRED)
|
||||
set(deps_freetype Freetype::Freetype harfbuzz::harfbuzz)
|
||||
else()
|
||||
FetchContent_Declare(
|
||||
freetype
|
||||
GIT_REPOSITORY https://gitlab.freedesktop.org/freetype/freetype.git
|
||||
GIT_TAG VER-2-12-1
|
||||
CMAKE_ARGS
|
||||
-DCMAKE_BUILD_TYPE=Release
|
||||
-DFT_DISABLE_ZLIB=TRUE
|
||||
-DFT_DISABLE_BZIP2=TRUE
|
||||
-DFT_DISABLE_PNG=TRUE
|
||||
# -DFT_DISABLE_HARFBUZZ=TRUE
|
||||
-DFT_REQUIRE_HARFBUZZ=TRUE
|
||||
-DFT_DISABLE_BROTLI=TRUE
|
||||
-DBUILD_SHARED_LIBS=TRUE)
|
||||
|
||||
FetchContent_Declare(
|
||||
harfbuzz
|
||||
# DEPENDS freetype_without_harfbuzz
|
||||
GIT_REPOSITORY https://github.com/harfbuzz/harfbuzz.git
|
||||
GIT_TAG 5.3.1
|
||||
CMAKE_ARGS -DHB_HAVE_FREETYPE=ON)
|
||||
|
||||
set(deps_freetype freetype harfbuzz)
|
||||
set(fetch_content freetype harfbuzz)
|
||||
endif()
|
||||
|
||||
FetchContent_MakeAvailable(spdlog boostpfr glm tinygltf ${fetch_content})
|
||||
|
||||
FetchContent_GetProperties(tinygltf SOURCE_DIR TinyGLTF_SOURCE_DIR)
|
||||
|
||||
#add_subdirectory(${TinyGLTF_SOURCE_DIR})
|
||||
#add_library(TinyGLTF INTERFACE)
|
||||
#target_include_directories(TinyGLTF INTERFACE ${TinyGLTF_SOURCE_DIR})
|
||||
|
||||
find_package(Vulkan REQUIRED)
|
||||
|
||||
get_property(importTargets DIRECTORY "${CMAKE_SOURCE_DIR}" PROPERTY IMPORTED_TARGETS)
|
||||
get_property(buildsystemTargets DIRECTORY "${CMAKE_SOURCE_DIR}" PROPERTY BUILDSYSTEM_TARGETS)
|
||||
message("Imported targets: ${importTargets}")
|
||||
message("Build system targets: ${buildsystemTargets}")
|
||||
|
||||
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
|
||||
include(CompileGLSL)
|
||||
|
||||
if(ANDROID)
|
||||
include(AndroidNdkModules)
|
||||
android_ndk_import_module_native_app_glue()
|
||||
find_library(ANDROID_LIBRARY NAMES android)
|
||||
|
||||
find_library(MEDIA_LIBRARY NAMES mediandk)
|
||||
|
||||
if(OCULUS_SDK)
|
||||
add_library(OpenXR SHARED IMPORTED)
|
||||
target_include_directories(OpenXR INTERFACE ${OCULUS_SDK}/3rdParty/khronos/openxr/OpenXR-SDK/include)
|
||||
|
||||
if(CMAKE_BUILD_TYPE STREQUAL Debug)
|
||||
set_property(TARGET OpenXR
|
||||
PROPERTY IMPORTED_LOCATION ${OCULUS_SDK}/OpenXR/Libs/Android/${ANDROID_ABI}/Debug/libopenxr_loader.so)
|
||||
else()
|
||||
set_property(TARGET OpenXR
|
||||
PROPERTY IMPORTED_LOCATION ${OCULUS_SDK}/OpenXR/Libs/Android/${ANDROID_ABI}/Release/libopenxr_loader.so)
|
||||
endif()
|
||||
else()
|
||||
message(FATAL_ERROR "TODO: implement non-oculus android headsets")
|
||||
endif()
|
||||
|
||||
add_library(${PROJECT_NAME} MODULE)
|
||||
target_link_libraries(${PROJECT_NAME} ${ANDROID_LIBRARY})
|
||||
target_link_libraries(${PROJECT_NAME} ${MEDIA_LIBRARY})
|
||||
target_link_libraries(${PROJECT_NAME} native_app_glue)
|
||||
target_link_libraries(${PROJECT_NAME} OpenXR)
|
||||
target_link_libraries(${PROJECT_NAME} Boost::pfr)
|
||||
target_compile_definitions(${PROJECT_NAME} PRIVATE -DXR_USE_PLATFORM_ANDROID -DVK_USE_PLATFORM_ANDROID_KHR)
|
||||
target_link_options(${PROJECT_NAME} PRIVATE -Wl,--undefined=ANativeActivity_onCreate)
|
||||
|
||||
file(GLOB PLATFORM_SOURCE CONFIGURE_DEPENDS
|
||||
"src/decoder/android/*.cpp")
|
||||
target_sources(${PROJECT_NAME} PRIVATE ${PLATFORM_SOURCE})
|
||||
else()
|
||||
find_package(OpenXR REQUIRED)
|
||||
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET libavcodec libavutil
|
||||
libswscale)
|
||||
|
||||
add_executable(${PROJECT_NAME})
|
||||
target_compile_definitions(${PROJECT_NAME} PRIVATE -DXR_USE_PLATFORM_XLIB)
|
||||
target_link_libraries(${PROJECT_NAME} OpenXR::openxr_loader
|
||||
OpenXR::headers PkgConfig::LIBAV)
|
||||
|
||||
file(GLOB PLATFORM_SOURCE CONFIGURE_DEPENDS
|
||||
"src/decoder/ffmpeg/*.cpp")
|
||||
target_sources(${PROJECT_NAME} PRIVATE ${PLATFORM_SOURCE})
|
||||
endif()
|
||||
|
||||
target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_20)
|
||||
target_compile_definitions(${PROJECT_NAME} PRIVATE "XR_USE_TIMESPEC=1")
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden)
|
||||
|
||||
file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS
|
||||
"src/*.cpp"
|
||||
"src/decoder/*.cpp"
|
||||
"src/external/*.c"
|
||||
"src/scenes/*.cpp"
|
||||
"src/utils/*.cpp"
|
||||
"src/vk/*.cpp"
|
||||
"src/xr/*.cpp"
|
||||
"src/render/*.cpp")
|
||||
file(GLOB_RECURSE VULKAN_SHADERS CONFIGURE_DEPENDS "src/*.glsl")
|
||||
|
||||
target_sources(${PROJECT_NAME} PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS})
|
||||
|
||||
target_link_libraries(${PROJECT_NAME} Vulkan::Vulkan spdlog::spdlog glm::glm tinygltf ${deps_freetype})
|
||||
target_compile_definitions(${PROJECT_NAME} PRIVATE -DXR_USE_GRAPHICS_API_VULKAN)
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE -fdiagnostics-color -Wall -Wextra -pedantic) # -Werror
|
||||
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE -Wno-missing-field-initializers -Wno-unused-parameter
|
||||
$<$<COMPILE_LANG_AND_ID:CXX,GNU>:-Wno-volatile>
|
||||
$<$<COMPILE_LANG_AND_ID:CXX,Clang>:-Wno-deprecated-volatile>
|
||||
)
|
||||
|
||||
target_include_directories(${PROJECT_NAME} PRIVATE src)
|
||||
target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
execute_process(COMMAND git describe --always OUTPUT_VARIABLE GIT_VERSION)
|
||||
string(STRIP ${GIT_VERSION} GIT_VERSION)
|
||||
|
||||
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/version.h
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-D GIT_EXECUTABLE=${GIT_EXECUTABLE}
|
||||
-D INPUT_FILE=${CMAKE_CURRENT_SOURCE_DIR}/src/version.h.in
|
||||
-D OUTPUT_FILE=${CMAKE_CURRENT_BINARY_DIR}/version.h
|
||||
-P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/GitVersion.cmake
|
||||
)
|
||||
target_sources(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/version.h)
|
||||
|
||||
if (CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/vk_layer_settings.txt
|
||||
"khronos_validation.debug_action = VK_DBG_LAYER_ACTION_LOG_MSG,VK_DBG_LAYER_ACTION_BREAK
|
||||
khronos_validation.report_flags = error,warn
|
||||
khronos_validation.log_filename = stdout
|
||||
khronos_validation.disables =
|
||||
khronos_validation.enables = VK_VALIDATION_FEATURE_ENABLE_THREAD_SAFETY_EXT
|
||||
")
|
||||
endif()
|
||||
|
||||
compile_glsl(${PROJECT_NAME} ${VULKAN_SHADERS})
|
||||
@@ -0,0 +1,77 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:7.2.2'
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
buildToolsVersion "30.0.3"
|
||||
ndkVersion "25.1.8937393"
|
||||
|
||||
defaultConfig {
|
||||
applicationId "org.meumeu.wivrn"
|
||||
// for Vulkan, need at least 24
|
||||
// for AImage_getHardwareBuffer, API 26
|
||||
minSdkVersion 29
|
||||
compileSdkVersion 29
|
||||
|
||||
versionName = "1.0"
|
||||
versionCode = 1
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
//abiFilters "armeabi-v7a", 'arm64-v8a'//, 'x86', 'x86_64'
|
||||
arguments '-DANDROID_TOOLCHAIN=clang', '-DANDROID_STL=c++_static', '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', '-DUSE_SYSTEM_FREETYPE=OFF'
|
||||
resValue "string", "app_name", "WiVRn"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flavorDimensions "device"
|
||||
|
||||
productFlavors {
|
||||
oculus {
|
||||
dimension "device"
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
abiFilters 'arm64-v8a'
|
||||
arguments '-DOCULUS_SDK=' + file('OculusSDK').absolutePath
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
main {
|
||||
manifest.srcFile 'AndroidManifest.xml'
|
||||
res.srcDir 'resources'
|
||||
}
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
version '3.22.1'
|
||||
path 'CMakeLists.txt'
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
signingConfig signingConfigs.debug
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
|
||||
function(compile_glsl_aux shader_stage glsl_filename output)
|
||||
|
||||
cmake_path(GET glsl_filename STEM shader_name)
|
||||
|
||||
string(TOUPPER ${shader_stage} shader_stage_upper)
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${output}
|
||||
COMMAND echo "{ \"${shader_name}.${shader_stage}\", {" >> ${output}
|
||||
COMMAND Vulkan::glslc -mfmt=num -fshader-stage=${shader_stage} -D${shader_stage_upper}_SHADER ${in_file} -o - >> ${output}
|
||||
COMMAND echo "}}," >> ${output}
|
||||
DEPENDS ${glsl_filename}
|
||||
VERBATIM
|
||||
APPEND
|
||||
)
|
||||
|
||||
endfunction()
|
||||
|
||||
|
||||
|
||||
function(compile_glsl target_name)
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${target_name}_shaders.cpp
|
||||
COMMAND echo "#include <cstdint>" > ${target_name}_shaders.cpp
|
||||
COMMAND echo "#include <map>" >> ${target_name}_shaders.cpp
|
||||
COMMAND echo "#include <vector>" >> ${target_name}_shaders.cpp
|
||||
COMMAND echo "#include <string>" >> ${target_name}_shaders.cpp
|
||||
COMMAND echo "extern const std::map<std::string, std::vector<uint32_t>> shaders = {" >> ${target_name}_shaders.cpp
|
||||
VERBATIM)
|
||||
|
||||
foreach(in_file IN LISTS ARGN)
|
||||
if (in_file MATCHES "\.\(vert|frag|tesc|tese|geom|comp\)\.glsl$")
|
||||
set(shader_stage ${CMAKE_MATCH_1})
|
||||
compile_glsl_aux(${shader_stage} ${in_file} ${target_name}_shaders.cpp)
|
||||
else()
|
||||
compile_glsl_aux(vert ${in_file} ${target_name}_shaders.cpp)
|
||||
compile_glsl_aux(frag ${in_file} ${target_name}_shaders.cpp)
|
||||
endif()
|
||||
|
||||
|
||||
endforeach()
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${target_name}_shaders.cpp
|
||||
COMMAND echo "};" >> ${target_name}_shaders.cpp
|
||||
APPEND
|
||||
VERBATIM)
|
||||
|
||||
target_sources(${target_name} PRIVATE ${target_name}_shaders.cpp)
|
||||
|
||||
endfunction()
|
||||
@@ -0,0 +1,5 @@
|
||||
|
||||
execute_process(COMMAND git describe --always OUTPUT_VARIABLE GIT_VERSION)
|
||||
string(STRIP ${GIT_VERSION} GIT_VERSION)
|
||||
|
||||
configure_file(${INPUT_FILE} ${OUTPUT_FILE})
|
||||
Vendored
BIN
Binary file not shown.
+2
@@ -0,0 +1,2 @@
|
||||
SPDX-FileCopyrightText: Copyright 2007-2014, 2017 the original author or authors.
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,2 @@
|
||||
SPDX-FileCopyrightText: Copyright 2010 the original author or authors.
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
@@ -0,0 +1,187 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
@@ -0,0 +1,26 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<group
|
||||
android:scaleX="2.475"
|
||||
android:scaleY="2.475"
|
||||
android:translateX="23.75"
|
||||
android:translateY="24.3">
|
||||
<!--
|
||||
Copyright (c) 2020-2022, The Khronos Group Inc.
|
||||
Copyright (c) 2020, Google
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
Based on a Material Icons asset ("emoji-people") with added text
|
||||
in "Miriam Libre" Bold, converted to path, and manually simplified.
|
||||
-->
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M14,4A2,2 0,0 1,12 6,2 2,0 0,1 10,4 2,2 0,0 1,12 2,2 2,0 0,1 14,4Z" />
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M4,2C4,5.16 6.11,7.8409 9,8.7109L9,22h2v-6h2v6h2L15,10.0508L18.9492,14 20.3594,12.5898 15.8906,8.1094C15.5006,7.7194 14.8293,7 13.5293,7L10.9902,7C8.2402,6.99 6,4.75 6,2ZM9.6836,8.2168h0.373c0.034,0 0.0728,0.0171 0.0898,0.0469l0.6328,1.0039 0.6328,-1.0039c0.017,-0.0298 0.0558,-0.0469 0.0898,-0.0469h0.375c0.131,0 0.1001,0.1229 0.084,0.1484l-0.875,1.3867 0.8535,1.3555c0.0583,0.0926 -0.0668,0.1484 -0.084,0.1484h-0.375c-0.034,0 -0.0728,-0.0171 -0.0898,-0.0469l-0.6113,-0.9688 -0.6113,0.9688c-0.017,0.0298 -0.0558,0.0469 -0.0898,0.0469L9.7051,11.2559c-0.1321,0 -0.1019,-0.1231 -0.0859,-0.1484L10.4727,9.752 9.5977,8.3652c-0.0552,-0.0875 0,-0.1529 0.0859,-0.1484zM12.6836,8.2168h0.7949c0.527,0 0.9473,0.4118 0.9473,0.9219 0,0.4165 -0.2757,0.7579 -0.6582,0.877l0.7051,1.0918c0.0127,0.0213 0.0176,0.0373 0.0176,0.0586 0,0.051 -0.0382,0.0898 -0.0977,0.0898h-0.3496c-0.0425,0 -0.0839,-0.0203 -0.1094,-0.0586L13.2285,10.0625h-0.209v1.1035c0,0.051 -0.0388,0.0898 -0.0898,0.0898h-0.3398c-0.051,0 -0.0898,-0.0388 -0.0898,-0.0898L12.5,8.4004c0,-0.102 0.0816,-0.1836 0.1836,-0.1836zM13.0195,8.7051v0.8672h0.4336c0.2593,0 0.4453,-0.1812 0.4453,-0.4277 0,-0.255 -0.186,-0.4395 -0.4453,-0.4395zM9.7754,11.8145h0.2715c0.0685,0 0.1069,0.0502 0.1191,0.0898l0.623,2.0117 0.625,-2.0117c0.0208,-0.067 0.079,-0.0898 0.1191,-0.0898L11.8125,11.8145c0.0866,0 0.0969,0.0913 0.0879,0.1191l-0.8359,2.5723c-0.0221,0.068 -0.0707,0.0898 -0.1211,0.084h-0.3008c-0.0728,0 -0.1067,-0.0459 -0.1191,-0.084L9.6875,11.9336c-0.0265,-0.0814 0.0469,-0.1191 0.0879,-0.1191zM12.4414,11.8145L12.75,11.8145c0.0627,0 0.0801,0.0534 0.0801,0.082v1.0859h0.127l0.8867,-1.1133c0.0283,-0.036 0.0684,-0.0547 0.1172,-0.0547h0.3496c0.093,0 0.0729,0.1015 0.0586,0.1191l-1.002,1.2422 1.0059,1.2793c0.06,0.0764 -0.0353,0.1213 -0.0586,0.1211l-0.3574,-0.0039c-0.0463,0 -0.085,-0.0187 -0.1133,-0.0547L12.9766,13.418L12.8301,13.418v1.0723c0,0.063 -0.0524,0.082 -0.0801,0.082h-0.3086c-0.0641,0 -0.082,-0.0533 -0.082,-0.082v-2.5938c0,-0.0641 0.043,-0.0777 0.082,-0.082z" />
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!--
|
||||
Copyright (c) 2020-2022, The Khronos Group Inc.
|
||||
Copyright (c) 2020, Google
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
Based on a Material Icons asset ("emoji-people") with added text
|
||||
in "Miriam Libre" Bold, converted to path, and manually simplified.
|
||||
-->
|
||||
<background android:drawable="@color/ic_wivrn_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_wivrn_vk" />
|
||||
</adaptive-icon>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.7 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 8.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Copyright (c) 2020 The Khronos Group Inc.
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
-->
|
||||
<resources>
|
||||
<color name="ic_wivrn_launcher_background">#782B90</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,112 @@
|
||||
---
|
||||
Language: Cpp
|
||||
# BasedOnStyle: LLVM
|
||||
AccessModifierOffset: -8
|
||||
AlignAfterOpenBracket: Align
|
||||
AlignConsecutiveAssignments: false
|
||||
AlignConsecutiveDeclarations: false
|
||||
#AlignConsecutiveMacros: true
|
||||
AlignEscapedNewlines: Right
|
||||
AlignOperands: true
|
||||
AlignTrailingComments: true
|
||||
#AllowAllArgumentsOnNextLine: false
|
||||
#AllowAllConstructorInitializersOnNextLine: false
|
||||
AllowAllParametersOfDeclarationOnNextLine: false
|
||||
AllowShortBlocksOnASingleLine: false
|
||||
AllowShortCaseLabelsOnASingleLine: false
|
||||
AllowShortFunctionsOnASingleLine: Empty
|
||||
AllowShortIfStatementsOnASingleLine: false
|
||||
#AllowShortLambdasOnASingleLine: Inline
|
||||
AllowShortLoopsOnASingleLine: false
|
||||
AlwaysBreakAfterReturnType: None
|
||||
AlwaysBreakBeforeMultilineStrings: false
|
||||
AlwaysBreakTemplateDeclarations: Yes
|
||||
BinPackArguments: false
|
||||
BinPackParameters: false
|
||||
BraceWrapping:
|
||||
AfterClass: true
|
||||
AfterControlStatement: true
|
||||
AfterEnum: true
|
||||
AfterFunction: true
|
||||
AfterNamespace: true
|
||||
AfterStruct: true
|
||||
AfterUnion: true
|
||||
AfterExternBlock: true
|
||||
BeforeCatch: true
|
||||
BeforeElse: true
|
||||
IndentBraces: false
|
||||
SplitEmptyFunction: false
|
||||
SplitEmptyRecord: false
|
||||
SplitEmptyNamespace: false
|
||||
BreakBeforeBinaryOperators: None
|
||||
BreakBeforeBraces: Custom
|
||||
BreakBeforeTernaryOperators: true
|
||||
BreakConstructorInitializers: AfterColon
|
||||
BreakInheritanceList: AfterColon
|
||||
BreakStringLiterals: true
|
||||
ColumnLimit: 0
|
||||
#CommentPragmas: '^ IWYU pragma:'
|
||||
CompactNamespaces: false
|
||||
ConstructorInitializerAllOnOneLineOrOnePerLine: true
|
||||
ConstructorInitializerIndentWidth: 8
|
||||
ContinuationIndentWidth: 8
|
||||
Cpp11BracedListStyle: true
|
||||
DerivePointerAlignment: false
|
||||
DisableFormat: false
|
||||
ExperimentalAutoDetectBinPacking: false
|
||||
FixNamespaceComments: true
|
||||
#ForEachMacros:
|
||||
# - foreach
|
||||
# - Q_FOREACH
|
||||
# - BOOST_FOREACH
|
||||
IncludeBlocks: Preserve
|
||||
IncludeCategories:
|
||||
# openxr/openxr_platform.h depends on vulkan/vulkan.h
|
||||
- Regex: '^<vulkan/.*>$'
|
||||
Priority: 2
|
||||
- Regex: '^<openxr/.*>$'
|
||||
Priority: 3
|
||||
- Regex: '^<.*>$'
|
||||
Priority: 1
|
||||
- Regex: '^".*"$'
|
||||
Priority: 1
|
||||
IncludeIsMainRegex: '$'
|
||||
IndentCaseLabels: true
|
||||
IndentPPDirectives: None
|
||||
IndentWidth: 8
|
||||
IndentWrappedFunctionNames: false
|
||||
KeepEmptyLinesAtTheStartOfBlocks: false
|
||||
Language: Cpp
|
||||
MacroBlockBegin: ''
|
||||
MacroBlockEnd: ''
|
||||
MaxEmptyLinesToKeep: 1
|
||||
NamespaceIndentation: None
|
||||
PenaltyBreakAssignment: 2
|
||||
PenaltyBreakBeforeFirstCallParameter: 19
|
||||
PenaltyBreakComment: 300
|
||||
PenaltyBreakFirstLessLess: 120
|
||||
PenaltyBreakString: 1000
|
||||
PenaltyExcessCharacter: 1000000
|
||||
PenaltyReturnTypeOnItsOwnLine: 60
|
||||
PointerAlignment: Middle
|
||||
ReflowComments: true
|
||||
SortIncludes: true
|
||||
SortUsingDeclarations: true
|
||||
SpaceAfterCStyleCast: false
|
||||
#SpaceAfterLogicalNot: false
|
||||
SpaceAfterTemplateKeyword: true
|
||||
SpaceBeforeAssignmentOperators: true
|
||||
SpaceBeforeCpp11BracedList: false
|
||||
SpaceBeforeCtorInitializerColon: true
|
||||
SpaceBeforeInheritanceColon: true
|
||||
SpaceBeforeParens: ControlStatements
|
||||
SpaceBeforeRangeBasedForLoopColon: false
|
||||
SpaceInEmptyParentheses: false
|
||||
SpacesBeforeTrailingComments: 1
|
||||
SpacesInAngles: false
|
||||
SpacesInCStyleCastParentheses: false
|
||||
SpacesInParentheses: false
|
||||
SpacesInSquareBrackets: false
|
||||
Standard: Cpp11
|
||||
TabWidth: 8
|
||||
UseTab: ForIndentation
|
||||
@@ -0,0 +1,924 @@
|
||||
/*
|
||||
* 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 "application.h"
|
||||
#include "external/magic_enum.hpp"
|
||||
#include "scene.h"
|
||||
#include "spdlog/common.h"
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "utils/ranges.h"
|
||||
#include "utils/strings.h"
|
||||
#include "vk/details/enumerate.h"
|
||||
#include "vk/pipeline.h"
|
||||
#include "vk/shader.h"
|
||||
#include "vk/vk.h"
|
||||
#include "xr/xr.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <openxr/openxr_platform.h>
|
||||
|
||||
#ifndef NDEBUG
|
||||
#include "utils/backtrace.h"
|
||||
#endif
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#include <android/native_activity.h>
|
||||
#endif
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
application * application::instance_ = nullptr;
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
jni_thread::jni_thread(application & app) :
|
||||
vm(app.app_info.native_app->activity->vm)
|
||||
{
|
||||
vm->AttachCurrentThread(&env, nullptr);
|
||||
}
|
||||
|
||||
jni_thread::jni_thread() :
|
||||
jni_thread(application::instance())
|
||||
{
|
||||
}
|
||||
|
||||
jni_thread::~jni_thread()
|
||||
{
|
||||
vm->DetachCurrentThread();
|
||||
}
|
||||
#endif
|
||||
|
||||
VkBool32 application::vulkan_debug_report_callback(
|
||||
VkDebugReportFlagsEXT flags,
|
||||
VkDebugReportObjectTypeEXT objectType,
|
||||
uint64_t object,
|
||||
size_t location,
|
||||
int32_t messageCode,
|
||||
const char * pLayerPrefix,
|
||||
const char * pMessage,
|
||||
void * pUserData)
|
||||
{
|
||||
if (instance_->debug_report_ignored_objects.contains(object))
|
||||
return VK_FALSE;
|
||||
|
||||
spdlog::level::level_enum level = spdlog::level::info;
|
||||
|
||||
if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)
|
||||
{
|
||||
level = spdlog::level::info;
|
||||
}
|
||||
else if (flags & (VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT))
|
||||
{
|
||||
level = spdlog::level::warn;
|
||||
}
|
||||
else if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
|
||||
{
|
||||
level = spdlog::level::err;
|
||||
}
|
||||
else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)
|
||||
{
|
||||
level = spdlog::level::debug;
|
||||
}
|
||||
|
||||
// for(const std::string& s: utils::split(pMessage, "|"))
|
||||
// spdlog::log(level, s);
|
||||
spdlog::log(level, pMessage);
|
||||
|
||||
auto it = instance_->debug_report_object_name.find(object);
|
||||
if (it != instance_->debug_report_object_name.end())
|
||||
{
|
||||
spdlog::log(level, "{:#016x}: {}", object, it->second);
|
||||
}
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (level >= spdlog::level::warn)
|
||||
{
|
||||
bool validation_layer_found = false;
|
||||
for (auto & i: utils::backtrace(20))
|
||||
{
|
||||
if (i.library == "libVkLayer_khronos_validation.so")
|
||||
validation_layer_found = true;
|
||||
|
||||
if (validation_layer_found && i.library != "libVkLayer_khronos_validation.so")
|
||||
spdlog::log(level, "{:#016x}: {} + {:#x}", i.pc, i.library, i.pc - i.library_base);
|
||||
}
|
||||
}
|
||||
|
||||
if (level >= spdlog::level::err)
|
||||
abort();
|
||||
#endif
|
||||
|
||||
return VK_FALSE;
|
||||
}
|
||||
|
||||
void application::initialize_vulkan()
|
||||
{
|
||||
auto graphics_requirements = xr_system_id.graphics_requirements();
|
||||
XrVersion vulkan_version = std::max(app_info.min_vulkan_version, graphics_requirements.minApiVersionSupported);
|
||||
spdlog::info("OpenXR runtime wants Vulkan {}", xr::to_string(graphics_requirements.minApiVersionSupported));
|
||||
spdlog::info("Requesting Vulkan {}", xr::to_string(vulkan_version));
|
||||
|
||||
std::vector<const char *> layers;
|
||||
|
||||
spdlog::info("Available Vulkan layers:");
|
||||
bool validation_layer_found = false;
|
||||
for (VkLayerProperties & i: vk::details::enumerate<VkLayerProperties>(vkEnumerateInstanceLayerProperties))
|
||||
{
|
||||
spdlog::info(" {}", i.layerName);
|
||||
if (!strcmp(i.layerName, "VK_LAYER_KHRONOS_validation"))
|
||||
{
|
||||
validation_layer_found = true;
|
||||
}
|
||||
}
|
||||
#ifndef NDEBUG
|
||||
if (validation_layer_found)
|
||||
{
|
||||
spdlog::info("Using Vulkan validation layer");
|
||||
layers.push_back("VK_LAYER_KHRONOS_validation");
|
||||
}
|
||||
#endif
|
||||
|
||||
std::vector<const char *> instance_extensions{};
|
||||
std::vector<const char *> device_extensions{};
|
||||
|
||||
#ifndef NDEBUG
|
||||
bool debug_report_found = false;
|
||||
bool debug_utils_found = false;
|
||||
#endif
|
||||
spdlog::info("Available Vulkan instance extensions:");
|
||||
for (VkExtensionProperties & i: vk::details::enumerate<VkExtensionProperties>(vkEnumerateInstanceExtensionProperties, nullptr))
|
||||
{
|
||||
spdlog::info(" {}", i.extensionName);
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (!strcmp(i.extensionName, VK_EXT_DEBUG_REPORT_EXTENSION_NAME))
|
||||
debug_report_found = true;
|
||||
|
||||
if (!strcmp(i.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME))
|
||||
debug_utils_found = true;
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (debug_utils_found && debug_report_found)
|
||||
{
|
||||
// debug_extensions_found = true;
|
||||
// spdlog::info("Using debug extensions");
|
||||
instance_extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
|
||||
// instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
device_extensions.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
|
||||
device_extensions.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
|
||||
device_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
|
||||
device_extensions.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
|
||||
device_extensions.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);
|
||||
device_extensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
|
||||
device_extensions.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
|
||||
device_extensions.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
|
||||
instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
|
||||
instance_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME);
|
||||
#endif
|
||||
|
||||
VkApplicationInfo applicationInfo{};
|
||||
applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
||||
applicationInfo.apiVersion = VK_MAKE_API_VERSION(0, XR_VERSION_MAJOR(vulkan_version), XR_VERSION_MINOR(vulkan_version), 0);
|
||||
applicationInfo.pApplicationName = app_info.name.c_str();
|
||||
applicationInfo.applicationVersion = app_info.version;
|
||||
applicationInfo.pEngineName = engine_name;
|
||||
applicationInfo.engineVersion = engine_version;
|
||||
|
||||
VkInstanceCreateInfo instanceCreateInfo{};
|
||||
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
||||
instanceCreateInfo.pApplicationInfo = &applicationInfo;
|
||||
instanceCreateInfo.enabledLayerCount = layers.size();
|
||||
instanceCreateInfo.ppEnabledLayerNames = layers.data();
|
||||
instanceCreateInfo.enabledExtensionCount = instance_extensions.size();
|
||||
instanceCreateInfo.ppEnabledExtensionNames = instance_extensions.data();
|
||||
|
||||
XrVulkanInstanceCreateInfoKHR create_info{};
|
||||
create_info.type = XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR;
|
||||
create_info.systemId = xr_system_id;
|
||||
create_info.createFlags = 0;
|
||||
create_info.pfnGetInstanceProcAddr = vkGetInstanceProcAddr;
|
||||
create_info.vulkanCreateInfo = &instanceCreateInfo;
|
||||
create_info.vulkanAllocator = nullptr;
|
||||
|
||||
auto xrCreateVulkanInstanceKHR =
|
||||
xr_instance.get_proc<PFN_xrCreateVulkanInstanceKHR>("xrCreateVulkanInstanceKHR");
|
||||
|
||||
VkResult vresult;
|
||||
XrResult xresult = xrCreateVulkanInstanceKHR(xr_instance, &create_info, &vk_instance, &vresult);
|
||||
CHECK_VK(vresult, "xrCreateVulkanInstanceKHR");
|
||||
CHECK_XR(xresult, "xrCreateVulkanInstanceKHR");
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (debug_report_found)
|
||||
{
|
||||
VkDebugReportCallbackCreateInfoEXT debug_report_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT,
|
||||
.flags = VK_DEBUG_REPORT_INFORMATION_BIT_EXT |
|
||||
VK_DEBUG_REPORT_WARNING_BIT_EXT |
|
||||
VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT |
|
||||
VK_DEBUG_REPORT_ERROR_BIT_EXT |
|
||||
VK_DEBUG_REPORT_DEBUG_BIT_EXT,
|
||||
.pfnCallback = vulkan_debug_report_callback,
|
||||
};
|
||||
VkDebugReportCallbackEXT debug_report_callback;
|
||||
auto vkCreateDebugReportCallbackEXT = get_vulkan_proc<PFN_vkCreateDebugReportCallbackEXT>("vkCreateDebugReportCallbackEXT");
|
||||
CHECK_VK(vkCreateDebugReportCallbackEXT(vk_instance, &debug_report_info, nullptr, &debug_report_callback));
|
||||
}
|
||||
#endif
|
||||
|
||||
vk_physical_device = xr_system_id.physical_device(vk_instance);
|
||||
|
||||
spdlog::info("Available Vulkan device extensions:");
|
||||
for (VkExtensionProperties & i: vk::details::enumerate<VkExtensionProperties>(vkEnumerateDeviceExtensionProperties, vk_physical_device, nullptr))
|
||||
{
|
||||
spdlog::info(" {}", i.extensionName);
|
||||
}
|
||||
|
||||
VkPhysicalDeviceProperties prop;
|
||||
vkGetPhysicalDeviceProperties(vk_physical_device, &prop);
|
||||
spdlog::info("Initializing Vulkan with device {}", prop.deviceName);
|
||||
|
||||
uint32_t count;
|
||||
vkGetPhysicalDeviceQueueFamilyProperties(vk_physical_device, &count, nullptr);
|
||||
std::vector<VkQueueFamilyProperties> queue_properties(count);
|
||||
vkGetPhysicalDeviceQueueFamilyProperties(vk_physical_device, &count, queue_properties.data());
|
||||
|
||||
vk_queue_family_index = -1;
|
||||
[[maybe_unused]] bool vk_queue_found = false;
|
||||
for (size_t i = 0; i < queue_properties.size(); i++)
|
||||
{
|
||||
if (queue_properties[i].queueFlags & VkQueueFlagBits::VK_QUEUE_GRAPHICS_BIT)
|
||||
{
|
||||
vk_queue_found = true;
|
||||
vk_queue_family_index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert(vk_queue_found);
|
||||
spdlog::info("Using queue family {}", vk_queue_family_index);
|
||||
|
||||
float queuePriority = 0.0f;
|
||||
|
||||
VkDeviceQueueCreateInfo queueCreateInfo{};
|
||||
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
||||
queueCreateInfo.queueFamilyIndex = vk_queue_family_index;
|
||||
queueCreateInfo.queueCount = 1;
|
||||
queueCreateInfo.pQueuePriorities = &queuePriority;
|
||||
|
||||
VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR ycbcr_feature{
|
||||
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES_KHR,
|
||||
.samplerYcbcrConversion = VK_TRUE};
|
||||
|
||||
VkPhysicalDeviceFeatures deviceFeatures{};
|
||||
|
||||
VkDeviceCreateInfo createInfo{};
|
||||
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
||||
createInfo.pNext = &ycbcr_feature;
|
||||
createInfo.pQueueCreateInfos = &queueCreateInfo;
|
||||
createInfo.queueCreateInfoCount = 1;
|
||||
createInfo.pEnabledFeatures = &deviceFeatures;
|
||||
createInfo.enabledExtensionCount = device_extensions.size();
|
||||
createInfo.ppEnabledExtensionNames = device_extensions.data();
|
||||
|
||||
vk_device = xr_system_id.create_device(vk_physical_device, createInfo);
|
||||
|
||||
vkGetDeviceQueue(vk_device, vk_queue_family_index, 0, &vk_queue);
|
||||
}
|
||||
|
||||
void application::log_views()
|
||||
{
|
||||
for (XrViewConfigurationType i: xr_system_id.view_configurations())
|
||||
{
|
||||
spdlog::info("View configuration {}", xr::to_string(i));
|
||||
XrViewConfigurationProperties p = xr_system_id.view_configuration_properties(i);
|
||||
|
||||
spdlog::info(" fovMutable: {}", p.fovMutable ? "true" : "false");
|
||||
|
||||
int n = 0;
|
||||
for (const XrViewConfigurationView & j: xr_system_id.view_configuration_views(i))
|
||||
{
|
||||
spdlog::info(" View {}:", ++n);
|
||||
spdlog::info(" Recommended: {}x{}, {} sample(s)", j.recommendedImageRectWidth, j.recommendedImageRectHeight, j.recommendedSwapchainSampleCount);
|
||||
spdlog::info(" Maximum: {}x{}, {} sample(s)", j.maxImageRectWidth, j.maxImageRectHeight, j.maxSwapchainSampleCount);
|
||||
}
|
||||
|
||||
for (const XrEnvironmentBlendMode j: xr_system_id.environment_blend_modes(i))
|
||||
{
|
||||
spdlog::info(" Blend mode: {}", xr::to_string(j));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void application::initialize()
|
||||
{
|
||||
// LogLayersAndExtensions
|
||||
assert(!xr_instance);
|
||||
std::vector<const char *> extensions{XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME /*, XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME*/};
|
||||
|
||||
for (XrExtensionProperties & i: xr::instance::extensions())
|
||||
{
|
||||
if (!strcmp(i.extensionName, XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME))
|
||||
extensions.push_back(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME);
|
||||
if (!strcmp(i.extensionName, XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME))
|
||||
extensions.push_back(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME);
|
||||
}
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
xr_instance =
|
||||
xr::instance(app_info.name, app_info.native_app->activity->vm, app_info.native_app->activity->clazz, extensions);
|
||||
#else
|
||||
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());
|
||||
|
||||
xr_system_id = xr::system(xr_instance, app_info.formfactor);
|
||||
spdlog::info("Created OpenXR system for form factor {}", xr::to_string(app_info.formfactor));
|
||||
|
||||
// Log view configurations and blend modes
|
||||
log_views();
|
||||
|
||||
initialize_vulkan();
|
||||
|
||||
xr_session = xr::session(xr_instance, xr_system_id, vk_instance, vk_physical_device, vk_device, vk_queue_family_index);
|
||||
|
||||
auto spaces = xr_session.get_reference_spaces();
|
||||
spdlog::info("{} reference spaces", spaces.size());
|
||||
for (XrReferenceSpaceType i: spaces)
|
||||
{
|
||||
spdlog::info(" {}", xr::to_string(i));
|
||||
}
|
||||
|
||||
view_space = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_VIEW);
|
||||
world_space = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_STAGE);
|
||||
|
||||
swapchain_format = VK_FORMAT_UNDEFINED;
|
||||
for (auto i: xr_session.get_swapchain_formats())
|
||||
{
|
||||
if (std::find(supported_formats.begin(), supported_formats.end(), i) != supported_formats.end())
|
||||
{
|
||||
swapchain_format = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (swapchain_format == VK_FORMAT_UNDEFINED)
|
||||
throw std::runtime_error("No supported swapchain format");
|
||||
|
||||
spdlog::info("Using format {}", string_VkFormat(swapchain_format));
|
||||
|
||||
// XrViewConfigurationProperties view_props = xr_system_id.view_configuration_properties(viewconfig);
|
||||
|
||||
auto views = xr_system_id.view_configuration_views(app_info.viewconfig);
|
||||
|
||||
xr_swapchains.reserve(views.size());
|
||||
for (auto & view: views)
|
||||
{
|
||||
xr_swapchains.emplace_back(xr_session, vk_device, swapchain_format, view.recommendedImageRectWidth, view.recommendedImageRectHeight);
|
||||
|
||||
spdlog::info("Created swapchain {}: {}x{}", xr_swapchains.size(), xr_swapchains.back().width(), xr_swapchains.back().height());
|
||||
}
|
||||
|
||||
vk_cmdpool = vk::command_pool{vk_device, vk_queue_family_index};
|
||||
|
||||
// TODO get it from application info
|
||||
xr_actionset = xr::actionset(xr_instance, "actions", "Actions");
|
||||
std::vector<XrActionSuggestedBinding> bindings;
|
||||
|
||||
for (const auto & [name, type]: oculus_touch)
|
||||
{
|
||||
std::string name_without_slashes = std::string(name).substr(1);
|
||||
|
||||
for (char & i: name_without_slashes)
|
||||
{
|
||||
if (i == '/')
|
||||
i = '_';
|
||||
}
|
||||
|
||||
auto a = xr_actionset.create_action(type, name_without_slashes);
|
||||
actions.emplace_back(a, type, name);
|
||||
|
||||
if (type == XR_ACTION_TYPE_POSE_INPUT)
|
||||
{
|
||||
action_spaces.push_back(xr_session.create_action_space(a));
|
||||
}
|
||||
|
||||
bindings.push_back({a, xr_instance.string_to_path(name)});
|
||||
}
|
||||
|
||||
xr_instance.suggest_bindings("/interaction_profiles/oculus/touch_controller", bindings);
|
||||
|
||||
xr_session.attach_actionsets({xr_actionset});
|
||||
|
||||
interaction_profile_changed();
|
||||
}
|
||||
|
||||
std::pair<XrAction, XrActionType> application::get_action(const std::string & requested_name)
|
||||
{
|
||||
for (const auto & [action, type, name]: instance_->actions)
|
||||
{
|
||||
if (name == requested_name)
|
||||
return {action, type};
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
application::application(application_info info) :
|
||||
app_info(std::move(info)), jni(*this)
|
||||
{
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
// https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html
|
||||
|
||||
JNIEnv * Env = jni.get_JNIEnv();
|
||||
ANativeActivity * activity = app_info.native_app->activity;
|
||||
|
||||
jmethodID jtmID;
|
||||
|
||||
jclass jNativeClass = Env->GetObjectClass(activity->clazz);
|
||||
jtmID = Env->GetMethodID(jNativeClass, "getApplication", "()Landroid/app/Application;");
|
||||
|
||||
jobject jNativeApplication = (jobject)Env->CallObjectMethod(activity->clazz, jtmID);
|
||||
jtmID = Env->GetMethodID(Env->GetObjectClass(jNativeApplication), "getApplicationContext", "()Landroid/content/Context;");
|
||||
|
||||
jobject jNativeContext = (jobject)Env->CallObjectMethod(jNativeApplication, jtmID);
|
||||
jfieldID jNativeWIFI_SERVICE_fid = Env->GetStaticFieldID(Env->GetObjectClass(jNativeContext), "WIFI_SERVICE", "Ljava/lang/String;");
|
||||
jstring jNativeSFID_jstr = (jstring)Env->GetStaticObjectField(Env->FindClass("android/content/Context"), jNativeWIFI_SERVICE_fid);
|
||||
jstring wifiLockjStr = Env->NewStringUTF("WIVRn");
|
||||
|
||||
jtmID = Env->GetMethodID(Env->FindClass("android/content/Context"), "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
|
||||
jobject jSystemService = Env->CallObjectMethod(jNativeContext, jtmID, jNativeSFID_jstr);
|
||||
|
||||
jclass jWMClass = Env->FindClass("android/net/wifi/WifiManager");
|
||||
jclass jWMMLClass = Env->FindClass("android/net/wifi/WifiManager$MulticastLock");
|
||||
jtmID = Env->GetMethodID(jWMClass, "createMulticastLock", "(Ljava/lang/String;)Landroid/net/wifi/WifiManager$MulticastLock;");
|
||||
jobject jMCObj = Env->CallObjectMethod(jSystemService, jtmID, wifiLockjStr);
|
||||
|
||||
jtmID = Env->GetMethodID(jWMMLClass, "setReferenceCounted", "(Z)V");
|
||||
Env->CallVoidMethod(jMCObj, jtmID, 0);
|
||||
|
||||
jtmID = Env->GetMethodID(jWMMLClass, "acquire", "()V");
|
||||
Env->CallVoidMethod(jMCObj, jtmID);
|
||||
jtmID = Env->GetMethodID(jWMMLClass, "isHeld", "()Z");
|
||||
jboolean isheld = Env->CallBooleanMethod(jMCObj, jtmID);
|
||||
if (isheld)
|
||||
{
|
||||
spdlog::info("MulticastLock acquired");
|
||||
}
|
||||
else
|
||||
{
|
||||
spdlog::info("MulticastLock is not acquired");
|
||||
}
|
||||
|
||||
jclass jWMWLClass = Env->FindClass("android/net/wifi/WifiManager$WifiLock");
|
||||
jtmID = Env->GetMethodID(jWMClass, "createWifiLock", "(ILjava/lang/String;)Landroid/net/wifi/WifiManager$WifiLock;");
|
||||
// jobject jMCObj2 = Env->CallObjectMethod(jSystemService, jtmID, 4 /* WIFI_MODE_FULL_LOW_LATENCY */, wifiLockjStr);
|
||||
jobject jMCObj2 = Env->CallObjectMethod(jSystemService, jtmID, 3 /* WIFI_MODE_FULL_HIGH_PERF */, wifiLockjStr);
|
||||
|
||||
jtmID = Env->GetMethodID(jWMWLClass, "setReferenceCounted", "(Z)V");
|
||||
Env->CallVoidMethod(jMCObj2, jtmID, 0);
|
||||
|
||||
jtmID = Env->GetMethodID(jWMWLClass, "acquire", "()V");
|
||||
Env->CallVoidMethod(jMCObj2, jtmID);
|
||||
jtmID = Env->GetMethodID(jWMWLClass, "isHeld", "()Z");
|
||||
isheld = Env->CallBooleanMethod(jMCObj2, jtmID);
|
||||
if (isheld)
|
||||
{
|
||||
spdlog::info("WifiLock low latency acquired");
|
||||
}
|
||||
else
|
||||
{
|
||||
spdlog::info("WifiLock low latency is not acquired");
|
||||
}
|
||||
|
||||
Env->DeleteLocalRef(wifiLockjStr);
|
||||
|
||||
app_info.native_app->userData = this;
|
||||
app_info.native_app->onAppCmd = [](android_app * app, int32_t cmd) {
|
||||
switch (cmd)
|
||||
{
|
||||
// There is no APP_CMD_CREATE. The ANativeActivity creates the
|
||||
// application thread from onCreate(). The application thread
|
||||
// then calls android_main().
|
||||
case APP_CMD_START:
|
||||
break;
|
||||
case APP_CMD_RESUME:
|
||||
static_cast<application *>(app->userData)->resumed = true;
|
||||
break;
|
||||
case APP_CMD_PAUSE:
|
||||
static_cast<application *>(app->userData)->resumed = false;
|
||||
break;
|
||||
case APP_CMD_STOP:
|
||||
break;
|
||||
case APP_CMD_DESTROY:
|
||||
static_cast<application *>(app->userData)->native_window = nullptr;
|
||||
break;
|
||||
case APP_CMD_INIT_WINDOW:
|
||||
static_cast<application *>(app->userData)->native_window = app->window;
|
||||
break;
|
||||
case APP_CMD_TERM_WINDOW:
|
||||
static_cast<application *>(app->userData)->native_window = nullptr;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize the loader for this platform
|
||||
PFN_xrInitializeLoaderKHR initializeLoader = nullptr;
|
||||
if (XR_SUCCEEDED(xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", (PFN_xrVoidFunction *)(&initializeLoader))))
|
||||
{
|
||||
XrLoaderInitInfoAndroidKHR loaderInitInfoAndroid{};
|
||||
loaderInitInfoAndroid.type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR;
|
||||
loaderInitInfoAndroid.next = nullptr;
|
||||
loaderInitInfoAndroid.applicationVM = app_info.native_app->activity->vm;
|
||||
loaderInitInfoAndroid.applicationContext = app_info.native_app->activity->clazz;
|
||||
initializeLoader((const XrLoaderInitInfoBaseHeaderKHR *)&loaderInitInfoAndroid);
|
||||
}
|
||||
#endif
|
||||
|
||||
assert(instance_ == nullptr);
|
||||
instance_ = this;
|
||||
|
||||
try
|
||||
{
|
||||
initialize();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
cleanup();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void application::cleanup()
|
||||
{
|
||||
// The Vulkan device and instance are destroyed by the OpenXR runtime
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
app_info.native_app->activity->vm->DetachCurrentThread();
|
||||
#endif
|
||||
assert(instance_ == this);
|
||||
instance_ = nullptr;
|
||||
}
|
||||
|
||||
application::~application()
|
||||
{
|
||||
cleanup();
|
||||
}
|
||||
|
||||
void application::loop()
|
||||
{
|
||||
poll_events();
|
||||
|
||||
if (!is_session_running())
|
||||
{
|
||||
// Throttle loop since xrWaitFrame won't be called.
|
||||
std::this_thread::sleep_for(250ms);
|
||||
}
|
||||
else
|
||||
{
|
||||
poll_actions();
|
||||
|
||||
auto scene = current_scene();
|
||||
if (scene)
|
||||
{
|
||||
if (scene != last_scene)
|
||||
{
|
||||
if (last_scene)
|
||||
last_scene->on_unfocused();
|
||||
|
||||
scene->on_focused();
|
||||
|
||||
last_scene = scene;
|
||||
}
|
||||
|
||||
scene->render();
|
||||
}
|
||||
else
|
||||
{
|
||||
exit_requested = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
void application::run()
|
||||
{
|
||||
std::thread application_thread{[&]() {
|
||||
jni_thread jni;
|
||||
|
||||
while (!is_exit_requested())
|
||||
{
|
||||
try
|
||||
{
|
||||
loop();
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::error("Caught exception in application_thread: \"{}\"", e.what());
|
||||
exit_requested = true;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
spdlog::error("Caught unknown exception in application_thread");
|
||||
exit_requested = true;
|
||||
}
|
||||
}
|
||||
}};
|
||||
pthread_setname_np(application_thread.native_handle(), "application_thread");
|
||||
|
||||
// Read all pending events.
|
||||
while (!exit_requested)
|
||||
{
|
||||
int events;
|
||||
struct android_poll_source * source;
|
||||
|
||||
while (ALooper_pollAll(-1, nullptr, &events, (void **)&source) >= 0)
|
||||
{
|
||||
// Process this event.
|
||||
if (source != nullptr)
|
||||
source->process(app_info.native_app, source);
|
||||
}
|
||||
|
||||
if (app_info.native_app->destroyRequested)
|
||||
{
|
||||
exit_requested = true;
|
||||
}
|
||||
}
|
||||
|
||||
application_thread.join();
|
||||
}
|
||||
#else
|
||||
void application::run()
|
||||
{
|
||||
while (!is_exit_requested())
|
||||
{
|
||||
loop();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
std::shared_ptr<scene> application::current_scene()
|
||||
{
|
||||
std::unique_lock _{instance_->scene_stack_lock};
|
||||
if (!instance_->scene_stack.empty())
|
||||
return instance_->scene_stack.back();
|
||||
else
|
||||
return {};
|
||||
}
|
||||
|
||||
void application::pop_scene()
|
||||
{
|
||||
std::unique_lock _{instance_->scene_stack_lock};
|
||||
if (!instance_->scene_stack.empty())
|
||||
instance_->scene_stack.pop_back();
|
||||
}
|
||||
|
||||
void application::push_scene(std::shared_ptr<scene> s)
|
||||
{
|
||||
std::unique_lock _{instance_->scene_stack_lock};
|
||||
instance_->scene_stack.push_back(std::move(s));
|
||||
}
|
||||
|
||||
void application::poll_actions()
|
||||
{
|
||||
instance_->xr_session.sync_actions(instance_->xr_actionset);
|
||||
}
|
||||
|
||||
bool application::read_action(XrAction action, bool & value)
|
||||
{
|
||||
if (!is_focused())
|
||||
return false;
|
||||
|
||||
XrActionStateGetInfo get_info{
|
||||
.type = XR_TYPE_ACTION_STATE_GET_INFO,
|
||||
.action = action,
|
||||
};
|
||||
|
||||
XrActionStateBoolean state{XR_TYPE_ACTION_STATE_BOOLEAN};
|
||||
CHECK_XR(xrGetActionStateBoolean(instance_->xr_session, &get_info, &state));
|
||||
|
||||
if (!state.isActive)
|
||||
return false;
|
||||
|
||||
value = state.currentState;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool application::read_action(XrAction action, float & value)
|
||||
{
|
||||
if (!is_focused())
|
||||
return false;
|
||||
|
||||
XrActionStateGetInfo get_info{
|
||||
.type = XR_TYPE_ACTION_STATE_GET_INFO,
|
||||
.action = action,
|
||||
};
|
||||
|
||||
XrActionStateFloat state{XR_TYPE_ACTION_STATE_FLOAT};
|
||||
CHECK_XR(xrGetActionStateFloat(instance_->xr_session, &get_info, &state));
|
||||
|
||||
if (!state.isActive)
|
||||
return false;
|
||||
|
||||
value = state.currentState;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool application::read_action(XrAction action, XrVector2f & value)
|
||||
{
|
||||
if (!is_focused())
|
||||
return false;
|
||||
|
||||
XrActionStateGetInfo get_info{
|
||||
.type = XR_TYPE_ACTION_STATE_GET_INFO,
|
||||
.action = action,
|
||||
};
|
||||
|
||||
XrActionStateVector2f state{XR_TYPE_ACTION_STATE_VECTOR2F};
|
||||
CHECK_XR(xrGetActionStateVector2f(instance_->xr_session, &get_info, &state));
|
||||
|
||||
if (!state.isActive)
|
||||
return false;
|
||||
|
||||
value = state.currentState;
|
||||
return true;
|
||||
}
|
||||
|
||||
void application::haptic_start(XrAction action, XrPath subpath, int64_t duration, float frequency, float amplitude)
|
||||
{
|
||||
if (!is_focused())
|
||||
return;
|
||||
|
||||
XrHapticActionInfo action_info{
|
||||
.type = XR_TYPE_HAPTIC_ACTION_INFO,
|
||||
.action = action,
|
||||
.subactionPath = subpath,
|
||||
};
|
||||
|
||||
XrHapticVibration vibration{
|
||||
.type = XR_TYPE_HAPTIC_VIBRATION,
|
||||
.duration = duration,
|
||||
.frequency = frequency,
|
||||
.amplitude = amplitude};
|
||||
|
||||
CHECK_XR(xrApplyHapticFeedback(application::instance_->xr_session, &action_info, (XrHapticBaseHeader *)&vibration));
|
||||
}
|
||||
|
||||
void application::haptic_stop(XrAction action, XrPath subpath)
|
||||
{
|
||||
if (!is_focused())
|
||||
return;
|
||||
|
||||
XrHapticActionInfo action_info{
|
||||
.type = XR_TYPE_HAPTIC_ACTION_INFO,
|
||||
.action = action,
|
||||
.subactionPath = subpath,
|
||||
};
|
||||
|
||||
CHECK_XR(xrStopHapticFeedback(application::instance_->xr_session, &action_info));
|
||||
}
|
||||
|
||||
void application::session_state_changed(XrSessionState new_state, XrTime timestamp)
|
||||
{
|
||||
// See HandleSessionStateChangedEvent
|
||||
spdlog::info("Session state changed at timestamp {}: {} => {}", timestamp, xr::to_string(session_state), xr::to_string(new_state));
|
||||
session_state = new_state;
|
||||
|
||||
switch (new_state)
|
||||
{
|
||||
case XR_SESSION_STATE_READY:
|
||||
xr_session.begin_session(app_info.viewconfig);
|
||||
session_running = true;
|
||||
break;
|
||||
|
||||
case XR_SESSION_STATE_SYNCHRONIZED:
|
||||
session_visible = false;
|
||||
session_focused = false;
|
||||
break;
|
||||
|
||||
case XR_SESSION_STATE_VISIBLE:
|
||||
session_visible = true;
|
||||
session_focused = false;
|
||||
break;
|
||||
|
||||
case XR_SESSION_STATE_FOCUSED:
|
||||
session_visible = true;
|
||||
session_focused = true;
|
||||
break;
|
||||
|
||||
case XR_SESSION_STATE_STOPPING:
|
||||
session_visible = false;
|
||||
session_focused = false;
|
||||
xr_session.end_session();
|
||||
session_running = false;
|
||||
break;
|
||||
|
||||
case XR_SESSION_STATE_EXITING:
|
||||
exit_requested = true;
|
||||
break;
|
||||
|
||||
case XR_SESSION_STATE_LOSS_PENDING:
|
||||
exit_requested = true;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void application::interaction_profile_changed()
|
||||
{
|
||||
spdlog::info("Interaction profile changed");
|
||||
|
||||
for (auto i: {"/user/hand/left", "/user/hand/right", "/user/head", "/user/gamepad"})
|
||||
{
|
||||
try
|
||||
{
|
||||
spdlog::info("Current interaction profile for {}: {}", i, xr_session.get_current_interaction_profile(i));
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::warn("Cannot get current interaction profile for {}: {}", i, e.what());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
for (auto [i, j]: utils::zip(actions, oculus_touch))
|
||||
{
|
||||
auto sources = xr_session.localized_sources_for_action(std::get<XrAction>(i));
|
||||
if (!sources.empty())
|
||||
{
|
||||
spdlog::info(" Sources for {}", j.first);
|
||||
for (auto & k: sources)
|
||||
{
|
||||
spdlog::info(" {}", k);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
spdlog::warn(" No source for {}", j.first);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void application::poll_events()
|
||||
{
|
||||
xr::event e;
|
||||
while (xr_instance.poll_event(e))
|
||||
{
|
||||
switch (e.header.type)
|
||||
{
|
||||
case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: {
|
||||
exit_requested = true;
|
||||
}
|
||||
break;
|
||||
case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: {
|
||||
if (e.interaction_profile_changed.session == xr_session)
|
||||
interaction_profile_changed();
|
||||
else
|
||||
spdlog::error("Received XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED for "
|
||||
"unknown session");
|
||||
}
|
||||
break;
|
||||
case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: {
|
||||
spdlog::warn("XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING in space {} in {:.6}s", magic_enum::enum_name(e.space_changed_pending.referenceSpaceType), (e.space_changed_pending.changeTime - now()) / 1.e9);
|
||||
}
|
||||
break;
|
||||
case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
|
||||
if (e.state_changed.session == xr_session)
|
||||
session_state_changed(e.state_changed.state, e.state_changed.time);
|
||||
else
|
||||
spdlog::error("Received XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED for unknown "
|
||||
"session");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
spdlog::info("Received event type {}", xr::to_string(e.header.type));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
/*
|
||||
* 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
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#include <android_native_app_glue.h>
|
||||
#endif
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "vk/vk.h"
|
||||
#include "xr/xr.h"
|
||||
#include <array>
|
||||
#include <mutex>
|
||||
#include <unordered_set>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <openxr/openxr.h>
|
||||
#include <openxr/openxr_platform.h>
|
||||
#include <openxr/openxr_reflection.h>
|
||||
|
||||
class scene;
|
||||
|
||||
struct application_info
|
||||
{
|
||||
std::string name = "Unnamed application";
|
||||
int version = VK_MAKE_VERSION(1, 0, 0);
|
||||
XrFormFactor formfactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
|
||||
XrViewConfigurationType viewconfig = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
|
||||
XrVersion min_vulkan_version = XR_MAKE_VERSION(1, 1, 0);
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
android_app * native_app;
|
||||
#endif
|
||||
};
|
||||
|
||||
class application;
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
class jni_thread
|
||||
{
|
||||
JNIEnv * env = nullptr;
|
||||
JavaVM * vm = nullptr;
|
||||
|
||||
public:
|
||||
explicit jni_thread(application & app);
|
||||
jni_thread();
|
||||
~jni_thread();
|
||||
|
||||
JNIEnv * get_JNIEnv()
|
||||
{
|
||||
return env;
|
||||
}
|
||||
};
|
||||
#else
|
||||
class [[maybe_unused]] jni_thread
|
||||
{
|
||||
public:
|
||||
explicit jni_thread(application & app) {}
|
||||
jni_thread() = default;
|
||||
~jni_thread() = default;
|
||||
};
|
||||
#endif
|
||||
|
||||
class application
|
||||
{
|
||||
friend class scene;
|
||||
friend class jni_thread;
|
||||
|
||||
application_info app_info;
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
ANativeWindow * native_window = nullptr;
|
||||
bool resumed = false;
|
||||
#endif
|
||||
|
||||
static inline const char engine_name[] = "No engine";
|
||||
static inline const int engine_version = VK_MAKE_VERSION(1, 0, 0);
|
||||
|
||||
static inline const std::array<VkFormat, 2> supported_formats = {VK_FORMAT_R8G8B8A8_SRGB,
|
||||
VK_FORMAT_B8G8R8A8_SRGB};
|
||||
|
||||
void initialize_vulkan();
|
||||
|
||||
void log_views();
|
||||
|
||||
void initialize();
|
||||
void cleanup();
|
||||
|
||||
void poll_events();
|
||||
|
||||
void session_state_changed(XrSessionState new_state, XrTime timestamp);
|
||||
void interaction_profile_changed();
|
||||
|
||||
static application * instance_;
|
||||
|
||||
jni_thread jni;
|
||||
|
||||
// OpenXR stuff
|
||||
xr::instance xr_instance;
|
||||
xr::system xr_system_id;
|
||||
xr::session xr_session;
|
||||
std::vector<xr::swapchain> xr_swapchains;
|
||||
XrSessionState session_state = XR_SESSION_STATE_UNKNOWN;
|
||||
|
||||
xr::space world_space;
|
||||
xr::space view_space;
|
||||
xr::actionset xr_actionset;
|
||||
std::vector<std::tuple<XrAction, XrActionType, std::string>> actions;
|
||||
std::vector<xr::space> action_spaces;
|
||||
|
||||
// Vulkan stuff
|
||||
VkInstance vk_instance{};
|
||||
VkPhysicalDevice vk_physical_device{};
|
||||
VkDevice vk_device{};
|
||||
uint32_t vk_queue_family_index;
|
||||
VkQueue vk_queue{};
|
||||
|
||||
vk::renderpass vk_renderpass;
|
||||
vk::pipeline vk_pipeline;
|
||||
vk::command_pool vk_cmdpool;
|
||||
|
||||
VkFormat swapchain_format;
|
||||
|
||||
static inline const std::pair<const char *, XrActionType> oculus_touch[] = {
|
||||
{"/user/hand/left/output/haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
|
||||
{"/user/hand/right/output/haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
|
||||
|
||||
{"/user/hand/left/input/grip/pose", XR_ACTION_TYPE_POSE_INPUT},
|
||||
{"/user/hand/left/input/aim/pose", XR_ACTION_TYPE_POSE_INPUT},
|
||||
|
||||
{"/user/hand/right/input/grip/pose", XR_ACTION_TYPE_POSE_INPUT},
|
||||
{"/user/hand/right/input/aim/pose", XR_ACTION_TYPE_POSE_INPUT},
|
||||
|
||||
{"/user/hand/left/input/x/click", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/left/input/x/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/left/input/y/click", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/left/input/y/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/left/input/menu/click", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/left/input/squeeze/value", XR_ACTION_TYPE_FLOAT_INPUT},
|
||||
{"/user/hand/left/input/trigger/value", XR_ACTION_TYPE_FLOAT_INPUT},
|
||||
{"/user/hand/left/input/trigger/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/left/input/thumbstick", XR_ACTION_TYPE_VECTOR2F_INPUT},
|
||||
{"/user/hand/left/input/thumbstick/click", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/left/input/thumbstick/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/left/input/thumbrest/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
|
||||
{"/user/hand/right/input/a/click", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/right/input/a/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/right/input/b/click", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/right/input/b/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/right/input/system/click", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/right/input/squeeze/value", XR_ACTION_TYPE_FLOAT_INPUT},
|
||||
{"/user/hand/right/input/trigger/value", XR_ACTION_TYPE_FLOAT_INPUT},
|
||||
{"/user/hand/right/input/trigger/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/right/input/thumbstick", XR_ACTION_TYPE_VECTOR2F_INPUT},
|
||||
{"/user/hand/right/input/thumbstick/click", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/right/input/thumbstick/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
{"/user/hand/right/input/thumbrest/touch", XR_ACTION_TYPE_BOOLEAN_INPUT},
|
||||
};
|
||||
|
||||
bool session_running = false;
|
||||
bool session_focused = false;
|
||||
bool session_visible = false;
|
||||
bool debug_extensions_found = false;
|
||||
std::atomic<bool> exit_requested = false;
|
||||
|
||||
std::mutex scene_stack_lock;
|
||||
std::vector<std::shared_ptr<scene>> scene_stack;
|
||||
std::shared_ptr<scene> last_scene;
|
||||
|
||||
void loop();
|
||||
|
||||
static VkBool32 vulkan_debug_report_callback(VkDebugReportFlagsEXT flags,
|
||||
VkDebugReportObjectTypeEXT objectType,
|
||||
uint64_t object,
|
||||
size_t location,
|
||||
int32_t messageCode,
|
||||
const char * pLayerPrefix,
|
||||
const char * pMessage,
|
||||
void * pUserData);
|
||||
std::unordered_set<uint64_t> debug_report_ignored_objects;
|
||||
std::unordered_map<uint64_t, std::string> debug_report_object_name;
|
||||
|
||||
public:
|
||||
application(application_info info);
|
||||
|
||||
application(const application &) = delete;
|
||||
~application();
|
||||
|
||||
static bool is_session_running()
|
||||
{
|
||||
return instance_->session_running;
|
||||
}
|
||||
|
||||
static bool is_focused()
|
||||
{
|
||||
return instance_->session_focused;
|
||||
}
|
||||
|
||||
static bool is_visible()
|
||||
{
|
||||
return instance_->session_visible;
|
||||
}
|
||||
|
||||
static bool is_exit_requested()
|
||||
{
|
||||
return instance_->exit_requested;
|
||||
};
|
||||
|
||||
static void poll_actions();
|
||||
static bool read_action(XrAction action, float & value);
|
||||
static bool read_action(XrAction action, bool & value);
|
||||
static bool read_action(XrAction action, XrVector2f & value);
|
||||
static void haptic_start(XrAction action, XrPath subpath, int64_t duration, float frequency, float amplitude);
|
||||
static void haptic_stop(XrAction action, XrPath subpath);
|
||||
|
||||
static const std::vector<std::tuple<XrAction, XrActionType, std::string>> & inputs()
|
||||
{
|
||||
return instance_->actions;
|
||||
}
|
||||
static std::pair<XrAction, XrActionType> get_action(const std::string & name);
|
||||
|
||||
static XrPath string_to_path(const std::string & s)
|
||||
{
|
||||
return instance_->xr_instance.string_to_path(s);
|
||||
}
|
||||
|
||||
static std::string path_to_string(XrPath p)
|
||||
{
|
||||
return instance_->xr_instance.path_to_string(p);
|
||||
}
|
||||
|
||||
void run();
|
||||
|
||||
static void push_scene(std::shared_ptr<scene>);
|
||||
|
||||
template <typename T, typename... Args>
|
||||
static void push_scene(Args &&... args)
|
||||
{
|
||||
std::unique_lock _{instance_->scene_stack_lock};
|
||||
|
||||
instance_->scene_stack.push_back(std::make_shared<T>(std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
static void pop_scene();
|
||||
|
||||
static std::shared_ptr<scene> current_scene();
|
||||
|
||||
static application & instance()
|
||||
{
|
||||
assert(instance_ != nullptr);
|
||||
return *instance_;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
static T get_vulkan_proc(const char * proc_name)
|
||||
{
|
||||
auto proc = vkGetInstanceProcAddr(instance_->vk_instance, proc_name);
|
||||
if (!proc)
|
||||
throw std::runtime_error(std::string("Cannot find Vulkan function ") + proc_name);
|
||||
return (T)proc;
|
||||
}
|
||||
|
||||
static XrSpace view()
|
||||
{
|
||||
return instance_->view_space;
|
||||
};
|
||||
static XrSpace left_grip()
|
||||
{
|
||||
return instance_->action_spaces[0];
|
||||
};
|
||||
static XrSpace left_aim()
|
||||
{
|
||||
return instance_->action_spaces[1];
|
||||
};
|
||||
static XrSpace right_grip()
|
||||
{
|
||||
return instance_->action_spaces[2];
|
||||
};
|
||||
static XrSpace right_aim()
|
||||
{
|
||||
return instance_->action_spaces[3];
|
||||
};
|
||||
|
||||
static void ignore_debug_reports_for(void * object)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
instance_->debug_report_ignored_objects.emplace((uint64_t)object);
|
||||
#endif
|
||||
}
|
||||
|
||||
static void unignore_debug_reports_for(void * object)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
instance_->debug_report_ignored_objects.erase((uint64_t)object);
|
||||
#endif
|
||||
}
|
||||
|
||||
static void set_debug_reports_name(void * object, std::string name)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
instance_->debug_report_object_name[(uint64_t)object] = std::move(name);
|
||||
#endif
|
||||
}
|
||||
|
||||
static XrTime now()
|
||||
{
|
||||
return instance_->xr_instance.now();
|
||||
}
|
||||
|
||||
static uint32_t queue_family_index()
|
||||
{
|
||||
return instance_->vk_queue_family_index;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,838 @@
|
||||
/*
|
||||
* 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 "android_decoder.h"
|
||||
#include "application.h"
|
||||
#include "scenes/stream.h"
|
||||
#include "utils/check.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include <algorithm>
|
||||
#include <android/hardware_buffer.h>
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <media/NdkImage.h>
|
||||
#include <media/NdkImageReader.h>
|
||||
#include <media/NdkMediaCodec.h>
|
||||
#include <media/NdkMediaFormat.h>
|
||||
#include <mutex>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <thread>
|
||||
#include <vulkan/vulkan_android.h>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
#include "external/magic_enum.hpp"
|
||||
|
||||
DEUGLIFY(AMediaFormat)
|
||||
|
||||
struct wivrn::android::decoder::pipeline_context
|
||||
{
|
||||
VkDevice device;
|
||||
VkAndroidHardwareBufferFormatPropertiesANDROID ahb_format;
|
||||
|
||||
VkSamplerYcbcrConversion ycbcr_conversion;
|
||||
VkSampler sampler;
|
||||
|
||||
std::vector<VkFramebuffer> framebuffers;
|
||||
VkDescriptorSetLayout descriptor_set_layout;
|
||||
VkDescriptorPool descriptor_pool;
|
||||
std::mutex descriptor_pool_mutex;
|
||||
vk::pipeline_layout layout;
|
||||
vk::pipeline pipeline;
|
||||
|
||||
~pipeline_context()
|
||||
{
|
||||
vkDestroyDescriptorPool(device, descriptor_pool, nullptr);
|
||||
vkDestroyDescriptorSetLayout(device, descriptor_set_layout, nullptr);
|
||||
vkDestroySampler(device, sampler, nullptr);
|
||||
vkDestroySamplerYcbcrConversion(device, ycbcr_conversion, nullptr);
|
||||
}
|
||||
|
||||
pipeline_context(VkDevice device, VkAndroidHardwareBufferFormatPropertiesANDROID & ahb_format, VkRenderPass renderpass) :
|
||||
device(device), ahb_format(ahb_format)
|
||||
{
|
||||
assert(ahb_format.externalFormat != 0);
|
||||
spdlog::info("AndroidHardwareBufferProperties");
|
||||
spdlog::info(" Vulkan format: {}", magic_enum::enum_name(ahb_format.format));
|
||||
spdlog::info(" External format: {:#x}", ahb_format.externalFormat);
|
||||
spdlog::info(" Format features: {:#x}", ahb_format.formatFeatures);
|
||||
spdlog::info(" samplerYcbcrConversionComponents: ({}, {}, {}, {})",
|
||||
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.r),
|
||||
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.g),
|
||||
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.b),
|
||||
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.a));
|
||||
spdlog::info(" Suggested YCbCr model: {}", ahb_format.suggestedYcbcrModel);
|
||||
spdlog::info(" Suggested YCbCr range: {}", ahb_format.suggestedYcbcrRange);
|
||||
spdlog::info(" Suggested X chroma offset: {}", ahb_format.suggestedXChromaOffset);
|
||||
spdlog::info(" Suggested Y chroma offset: {}", ahb_format.suggestedYChromaOffset);
|
||||
|
||||
VkFilter yuv_filter;
|
||||
if (ahb_format.formatFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT)
|
||||
yuv_filter = VK_FILTER_LINEAR;
|
||||
else
|
||||
yuv_filter = VK_FILTER_NEAREST;
|
||||
|
||||
// Create VkSamplerYcbcrConversion
|
||||
VkExternalFormatANDROID ycbcr_create_info2{.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID,
|
||||
.externalFormat = ahb_format.externalFormat};
|
||||
|
||||
VkSamplerYcbcrConversionCreateInfo ycbcr_create_info{
|
||||
.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO,
|
||||
.pNext = &ycbcr_create_info2,
|
||||
.format = VK_FORMAT_UNDEFINED,
|
||||
.ycbcrModel = ahb_format.suggestedYcbcrModel,
|
||||
.ycbcrRange = ahb_format.suggestedYcbcrRange,
|
||||
.components = ahb_format.samplerYcbcrConversionComponents,
|
||||
.xChromaOffset = ahb_format.suggestedXChromaOffset,
|
||||
.yChromaOffset = ahb_format.suggestedYChromaOffset,
|
||||
.chromaFilter = yuv_filter,
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateSamplerYcbcrConversion(device, &ycbcr_create_info, nullptr, &ycbcr_conversion));
|
||||
|
||||
// Create VkSampler
|
||||
VkSamplerYcbcrConversionInfo sampler_info2{
|
||||
.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO,
|
||||
.conversion = ycbcr_conversion,
|
||||
};
|
||||
|
||||
VkSamplerCreateInfo sampler_info{
|
||||
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
|
||||
.pNext = &sampler_info2,
|
||||
.magFilter = yuv_filter,
|
||||
.minFilter = yuv_filter,
|
||||
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
|
||||
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.mipLodBias = 0.0f,
|
||||
.anisotropyEnable = VK_FALSE,
|
||||
.maxAnisotropy = 1,
|
||||
.compareEnable = VK_FALSE,
|
||||
.compareOp = VK_COMPARE_OP_NEVER,
|
||||
.minLod = 0.0f,
|
||||
.maxLod = 0.0f,
|
||||
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, // TODO TBC
|
||||
.unnormalizedCoordinates = VK_FALSE,
|
||||
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateSampler(device, &sampler_info, nullptr, &sampler));
|
||||
|
||||
// Create VkDescriptorSetLayout with an immutable sampler
|
||||
VkDescriptorSetLayoutBinding samplerLayoutBinding{
|
||||
.binding = 0,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
.pImmutableSamplers = &sampler,
|
||||
};
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo layoutInfo{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.bindingCount = 1,
|
||||
.pBindings = &samplerLayoutBinding,
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptor_set_layout));
|
||||
|
||||
VkDescriptorPoolSize poolSize{};
|
||||
poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
poolSize.descriptorCount = 100;
|
||||
|
||||
VkDescriptorPoolCreateInfo poolInfo{};
|
||||
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
||||
poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
|
||||
poolInfo.poolSizeCount = 1;
|
||||
poolInfo.pPoolSizes = &poolSize;
|
||||
poolInfo.maxSets = poolSize.descriptorCount;
|
||||
CHECK_VK(vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptor_pool));
|
||||
|
||||
// Create graphics pipeline
|
||||
vk::shader vertex_shader(device, "stream.vert");
|
||||
vk::shader fragment_shader(device, "stream.frag");
|
||||
|
||||
VkPipelineColorBlendAttachmentState pcbas{};
|
||||
pcbas.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT;
|
||||
|
||||
layout = vk::pipeline_layout(
|
||||
device, {.descriptor_set_layouts = {descriptor_set_layout}});
|
||||
|
||||
vk::pipeline::graphics_info pipeline_info{
|
||||
.shader_stages =
|
||||
{{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vertex_shader, .pName = "main"},
|
||||
{.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fragment_shader, .pName = "main"}},
|
||||
.vertex_input_bindings = {},
|
||||
.vertex_input_attributes = {},
|
||||
.InputAssemblyState = {.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP},
|
||||
.viewports = {{}},
|
||||
.scissors = {{}},
|
||||
.RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1},
|
||||
.MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT},
|
||||
.ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas},
|
||||
.dynamic_states = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR},
|
||||
.renderPass = renderpass,
|
||||
.subpass = 0,
|
||||
};
|
||||
|
||||
pipeline = vk::pipeline(device, pipeline_info, layout);
|
||||
}
|
||||
};
|
||||
|
||||
struct wivrn::android::decoder::mapped_hardware_buffer
|
||||
{
|
||||
std::shared_ptr<pipeline_context> pipeline;
|
||||
VkImageView image_view{};
|
||||
VkImage vimage{};
|
||||
VkDeviceMemory memory{};
|
||||
VkDescriptorSet descriptor_set{};
|
||||
VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
|
||||
~mapped_hardware_buffer()
|
||||
{
|
||||
assert(pipeline);
|
||||
auto device = pipeline->device;
|
||||
{
|
||||
std::unique_lock lock(pipeline->descriptor_pool_mutex);
|
||||
vkFreeDescriptorSets(device, pipeline->descriptor_pool, 1, &descriptor_set);
|
||||
}
|
||||
vkDestroyImageView(device, image_view, nullptr);
|
||||
vkFreeMemory(device, memory, nullptr);
|
||||
vkDestroyImage(device, vimage, nullptr);
|
||||
}
|
||||
};
|
||||
|
||||
namespace
|
||||
{
|
||||
const char * mime(xrt::drivers::wivrn::video_codec codec)
|
||||
{
|
||||
using c = xrt::drivers::wivrn::video_codec;
|
||||
switch (codec)
|
||||
{
|
||||
case c::h264:
|
||||
return "video/avc";
|
||||
case c::h265:
|
||||
return "video/hevc";
|
||||
}
|
||||
assert(false);
|
||||
}
|
||||
|
||||
void check(media_status_t status, const char * msg)
|
||||
{
|
||||
if (status != AMEDIA_OK)
|
||||
{
|
||||
spdlog::error("{}: MediaCodec error {}", msg, (int)status);
|
||||
throw std::runtime_error("MediaCodec error");
|
||||
}
|
||||
}
|
||||
|
||||
namespace nal_h264
|
||||
{
|
||||
static const int sps = 7;
|
||||
static const int pps = 8;
|
||||
} // namespace nal_h264
|
||||
|
||||
namespace nal_h265
|
||||
{
|
||||
static const int vps = 32;
|
||||
static const int sps = 33;
|
||||
static const int pps = 34;
|
||||
static const int aud = 35;
|
||||
static const int filler = 38;
|
||||
}; // namespace nal_h265
|
||||
|
||||
enum class nal_class
|
||||
{
|
||||
csd,
|
||||
data,
|
||||
garbage
|
||||
};
|
||||
|
||||
nal_class get_nal_class_h264(uint8_t * nal)
|
||||
{
|
||||
uint8_t nal_type = (nal[2] == 0 ? nal[4] : nal[3]) & 0x1F;
|
||||
// spdlog::info("H264 NAL type {}", (int)nal_type);
|
||||
switch (nal_type)
|
||||
{
|
||||
case nal_h264::sps:
|
||||
case nal_h264::pps:
|
||||
return nal_class::csd;
|
||||
default:
|
||||
return nal_class::data;
|
||||
}
|
||||
}
|
||||
|
||||
nal_class get_nal_class_h265(uint8_t * nal)
|
||||
{
|
||||
uint8_t nal_type = ((nal[2] == 0 ? nal[4] : nal[3]) >> 1) & 0x3F;
|
||||
// spdlog::info("H265 NAL type {}", (int)nal_type);
|
||||
switch (nal_type)
|
||||
{
|
||||
case nal_h265::vps:
|
||||
case nal_h265::sps:
|
||||
case nal_h265::pps:
|
||||
return nal_class::csd;
|
||||
case nal_h265::aud:
|
||||
case nal_h265::filler:
|
||||
return nal_class::garbage;
|
||||
default:
|
||||
return nal_class::data;
|
||||
}
|
||||
}
|
||||
|
||||
nal_class get_nal_class(uint8_t * nal, xrt::drivers::wivrn::video_codec codec)
|
||||
{
|
||||
switch (codec)
|
||||
{
|
||||
case xrt::drivers::wivrn::video_codec::h264:
|
||||
return get_nal_class_h264(nal);
|
||||
|
||||
case xrt::drivers::wivrn::video_codec::h265:
|
||||
return get_nal_class_h265(nal);
|
||||
}
|
||||
}
|
||||
|
||||
std::pair<std::vector<uint8_t>, std::vector<uint8_t>> filter_csd(std::span<uint8_t> packet,
|
||||
xrt::drivers::wivrn::video_codec codec)
|
||||
{
|
||||
if (packet.size() < 4)
|
||||
return {};
|
||||
|
||||
std::array<uint8_t, 3> header = {{0, 0, 1}};
|
||||
auto end = packet.end();
|
||||
auto header_start = packet.begin();
|
||||
|
||||
std::pair<std::vector<uint8_t>, std::vector<uint8_t>> out;
|
||||
|
||||
while (header_start != end)
|
||||
{
|
||||
auto next_header = std::search(header_start + 3, end, header.begin(), header.end());
|
||||
if (next_header != end and next_header[-1] == 0)
|
||||
{
|
||||
next_header--;
|
||||
}
|
||||
|
||||
switch (get_nal_class(&*header_start, codec))
|
||||
{
|
||||
case nal_class::csd:
|
||||
out.first.insert(out.first.end(), header_start, next_header);
|
||||
break;
|
||||
case nal_class::data:
|
||||
out.second.insert(out.second.end(), header_start, next_header);
|
||||
break;
|
||||
case nal_class::garbage:
|
||||
break;
|
||||
}
|
||||
|
||||
header_start = next_header;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
namespace wivrn::android
|
||||
{
|
||||
|
||||
void decoder::push_nals(std::span<uint8_t> data, int64_t timestamp, uint32_t flags)
|
||||
{
|
||||
while (!data.empty())
|
||||
{
|
||||
auto t1 = application::now();
|
||||
auto input_buffer = input_buffers.pop();
|
||||
auto t2 = application::now();
|
||||
assert(input_buffer >= 0);
|
||||
|
||||
if (t2 - t1 > 1'000'000)
|
||||
spdlog::warn("input_buffers.pop() took {}µs", (t2 - t1) / 1000);
|
||||
|
||||
size_t size;
|
||||
t1 = application::now();
|
||||
uint8_t * buffer = AMediaCodec_getInputBuffer(media_codec.get(), input_buffer, &size);
|
||||
t2 = application::now();
|
||||
if (t2 - t1 > 1'000'000)
|
||||
spdlog::warn("AMediaCodec_getInputBuffer() took {}µs", (t2 - t1) / 1000);
|
||||
|
||||
size = std::min(data.size(), size);
|
||||
|
||||
memcpy(buffer, data.data(), size);
|
||||
|
||||
data = data.subspan(size);
|
||||
|
||||
t1 = application::now();
|
||||
check(AMediaCodec_queueInputBuffer(media_codec.get(), input_buffer, 0 /* offset */, size, timestamp, flags),
|
||||
"AMediaCodec_queueInputBuffer");
|
||||
t2 = application::now();
|
||||
if (t2 - t1 > 1'000'000)
|
||||
spdlog::warn("AMediaCodec_queueInputBuffer() took {}µs", (t2 - t1) / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
decoder::decoder(VkDevice device, VkPhysicalDevice physical_device, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, std::weak_ptr<scenes::stream> weak_scene, shard_accumulator * accumulator) :
|
||||
description(description), device(device), weak_scene(weak_scene), accumulator(accumulator)
|
||||
{
|
||||
AImageReader * ir;
|
||||
check(AImageReader_newWithUsage(description.width, description.height, AIMAGE_FORMAT_PRIVATE, AHARDWAREBUFFER_USAGE_CPU_READ_NEVER | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE, 5 /* maxImages */, &ir),
|
||||
"AImageReader_newWithUsage");
|
||||
image_reader.reset(ir);
|
||||
|
||||
AImageReader_ImageListener listener{this, on_image_available};
|
||||
check(AImageReader_setImageListener(ir, &listener), "AImageReader_setImageListener");
|
||||
|
||||
vkGetAndroidHardwareBufferPropertiesANDROID =
|
||||
application::get_vulkan_proc<PFN_vkGetAndroidHardwareBufferPropertiesANDROID>(
|
||||
"vkGetAndroidHardwareBufferPropertiesANDROID");
|
||||
|
||||
output_releaser = std::thread([this]() {
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
auto index = output_buffers.pop();
|
||||
auto status = AMediaCodec_releaseOutputBuffer(media_codec.get(), index, true);
|
||||
// will trigger on_image_available through ImageReader
|
||||
if (status != AMEDIA_OK)
|
||||
spdlog::error("AMediaCodec_releaseOutputBuffer: MediaCodec error {}",
|
||||
(int)status);
|
||||
}
|
||||
catch (const utils::sync_queue_closed & e)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (const std::exception & e)
|
||||
{
|
||||
spdlog::error("error in output releaser thread: {}", e.what());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
decoder::~decoder()
|
||||
{
|
||||
input_buffers.close();
|
||||
output_buffers.close();
|
||||
output_releaser.join();
|
||||
for (auto & i: blit_targets)
|
||||
vkDestroyFramebuffer(device, i.framebuffer, nullptr);
|
||||
}
|
||||
|
||||
void decoder::set_blit_targets(std::vector<decoder::blit_target> targets, VkFormat format)
|
||||
{
|
||||
// Create renderpass
|
||||
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
|
||||
|
||||
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{
|
||||
.format = format,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD,
|
||||
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
}},
|
||||
.subpasses = {VkSubpassDescription{
|
||||
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||||
.colorAttachmentCount = 1,
|
||||
.pColorAttachments = &color_ref,
|
||||
}},
|
||||
.dependencies = {}};
|
||||
|
||||
renderpass = vk::renderpass(device, renderpass_info);
|
||||
|
||||
// Remove old blit targets first
|
||||
for (auto & i: blit_targets)
|
||||
vkDestroyFramebuffer(device, i.framebuffer, nullptr);
|
||||
|
||||
blit_targets = std::move(targets);
|
||||
|
||||
for (auto & i: blit_targets)
|
||||
{
|
||||
VkFramebufferCreateInfo fb_create_info{};
|
||||
fb_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
||||
fb_create_info.renderPass = renderpass;
|
||||
fb_create_info.attachmentCount = 1;
|
||||
fb_create_info.pAttachments = &i.image_view;
|
||||
fb_create_info.width = i.extent.width;
|
||||
fb_create_info.height = i.extent.height;
|
||||
fb_create_info.layers = 1;
|
||||
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &i.framebuffer));
|
||||
}
|
||||
}
|
||||
|
||||
void decoder::push_data(std::span<uint8_t> data, uint64_t frame_index, bool partial)
|
||||
{
|
||||
auto [csd, not_csd] = filter_csd(data, description.codec);
|
||||
|
||||
if (!media_codec)
|
||||
{
|
||||
if (csd.empty())
|
||||
{
|
||||
// TODO request I frame
|
||||
return;
|
||||
}
|
||||
|
||||
AMediaFormat_ptr format(AMediaFormat_new());
|
||||
AMediaFormat_setString(format.get(), AMEDIAFORMAT_KEY_MIME, mime(description.codec));
|
||||
// AMediaFormat_setInt32(format.get(), "vendor.qti-ext-dec-low-latency.enable", 1); // Qualcomm low
|
||||
// latency mode
|
||||
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_WIDTH, description.width);
|
||||
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_HEIGHT, description.height);
|
||||
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_OPERATING_RATE, 72);
|
||||
AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_PRIORITY, 0);
|
||||
// AMediaFormat_setBuffer(format.get(), AMEDIAFORMAT_KEY_CSD_0, csd.data(), csd.size());
|
||||
|
||||
media_codec.reset(AMediaCodec_createDecoderByType(mime(description.codec)));
|
||||
|
||||
char * codec_name;
|
||||
check(AMediaCodec_getName(media_codec.get(), &codec_name), "AMediaCodec_getName");
|
||||
spdlog::info("Created MediaCodec decoder \"{}\"", codec_name);
|
||||
AMediaCodec_releaseName(media_codec.get(), codec_name);
|
||||
|
||||
ANativeWindow * window;
|
||||
|
||||
check(AImageReader_getWindow(image_reader.get(), &window), "AImageReader_getWindow");
|
||||
|
||||
AMediaCodecOnAsyncNotifyCallback callback{
|
||||
.onAsyncInputAvailable = decoder::on_media_input_available,
|
||||
.onAsyncOutputAvailable = decoder::on_media_output_available,
|
||||
.onAsyncFormatChanged = decoder::on_media_format_changed,
|
||||
.onAsyncError = decoder::on_media_error,
|
||||
};
|
||||
check(AMediaCodec_setAsyncNotifyCallback(media_codec.get(), callback, this),
|
||||
"AMediaCodec_setAsyncNotifyCallback");
|
||||
|
||||
check(AMediaCodec_configure(media_codec.get(), format.get(), window, nullptr /* crypto */, 0 /* flags */),
|
||||
"AMediaCodec_configure");
|
||||
|
||||
check(AMediaCodec_start(media_codec.get()), "AMediaCodec_start");
|
||||
}
|
||||
|
||||
if (!csd.empty())
|
||||
push_nals(csd, 0, AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG);
|
||||
|
||||
uint64_t fake_timestamp_us = frame_index * 10'000;
|
||||
push_nals(not_csd, fake_timestamp_us, partial ? AMEDIACODEC_BUFFER_FLAG_PARTIAL_FRAME : 0);
|
||||
}
|
||||
|
||||
void decoder::frame_completed(xrt::drivers::wivrn::from_headset::feedback & feedback, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info)
|
||||
{
|
||||
// nothing required for decoder, mediacodec will callback when done
|
||||
|
||||
feedback.sent_to_decoder = application::now();
|
||||
frame_infos.push(std::make_pair(feedback, view_info));
|
||||
}
|
||||
|
||||
void decoder::on_image_available(void * context, AImageReader * reader)
|
||||
{
|
||||
try
|
||||
{
|
||||
static_cast<decoder *>(context)->on_image_available(reader);
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::error("Exception in decoder::on_image_available: {}", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void decoder::on_image_available(AImageReader * reader)
|
||||
{
|
||||
assert(reader == image_reader.get());
|
||||
// Executed on image reader thread
|
||||
|
||||
AImage * image = nullptr;
|
||||
try
|
||||
{
|
||||
check(AImageReader_acquireLatestImage(image_reader.get(), &image), "AImageReader_acquireLatestImage");
|
||||
|
||||
int64_t fake_timestamp_ns;
|
||||
check(AImage_getTimestamp(image, &fake_timestamp_ns), "AImage_getTimestamp");
|
||||
uint64_t frame_index = (fake_timestamp_ns + 5'000'000) / (10'000'000);
|
||||
|
||||
frame_infos.drop_until([frame_index](auto & x) { return x.first.frame_index >= frame_index; });
|
||||
|
||||
auto info = frame_infos.pop_if([frame_index](auto & x) { return x.first.frame_index == frame_index; });
|
||||
|
||||
if (!info)
|
||||
{
|
||||
spdlog::warn("No frame info for frame {}, dropping frame", frame_index);
|
||||
AImage_delete(image);
|
||||
return;
|
||||
}
|
||||
|
||||
auto [feedback, view_info] = *info;
|
||||
|
||||
feedback.received_from_decoder = application::now();
|
||||
assert(feedback.frame_index == frame_index);
|
||||
|
||||
auto handle = std::make_shared<decoder::blit_handle>();
|
||||
handle->feedback = feedback;
|
||||
handle->view_info = view_info;
|
||||
handle->vk_data = map_hardware_buffer(image);
|
||||
handle->aimage = image;
|
||||
|
||||
if (auto scene = weak_scene.lock())
|
||||
scene->push_blit_handle(accumulator, std::move(handle));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
if (image)
|
||||
AImage_delete(image);
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<decoder::mapped_hardware_buffer> decoder::map_hardware_buffer(AImage * image)
|
||||
{
|
||||
AHardwareBuffer * hardware_buffer;
|
||||
check(AImage_getHardwareBuffer(image, &hardware_buffer), "AImage_getHardwareBuffer");
|
||||
|
||||
std::lock_guard lock(hbm_mutex);
|
||||
|
||||
AHardwareBuffer_Desc buffer_desc{};
|
||||
AHardwareBuffer_describe(hardware_buffer, &buffer_desc);
|
||||
|
||||
VkAndroidHardwareBufferFormatPropertiesANDROID format_properties{};
|
||||
format_properties.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
|
||||
|
||||
VkAndroidHardwareBufferPropertiesANDROID properties{};
|
||||
properties.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
|
||||
properties.pNext = &format_properties;
|
||||
CHECK_VK(vkGetAndroidHardwareBufferPropertiesANDROID(device, hardware_buffer, &properties));
|
||||
|
||||
if (!pipeline || memcmp(&pipeline->ahb_format, &format_properties, sizeof(format_properties)))
|
||||
{
|
||||
pipeline.reset();
|
||||
pipeline = std::make_shared<pipeline_context>(device, format_properties, renderpass);
|
||||
hardware_buffer_map.clear();
|
||||
}
|
||||
|
||||
auto it = hardware_buffer_map.find(hardware_buffer);
|
||||
if (it != hardware_buffer_map.end())
|
||||
return it->second;
|
||||
|
||||
VkExternalFormatANDROID img_info3{.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID,
|
||||
.externalFormat = format_properties.externalFormat};
|
||||
|
||||
VkExternalMemoryImageCreateInfo img_info2{
|
||||
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
|
||||
.pNext = &img_info3,
|
||||
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
|
||||
|
||||
VkImageCreateInfo img_info{.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
|
||||
.pNext = &img_info2,
|
||||
.flags = 0,
|
||||
.imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = VK_FORMAT_UNDEFINED,
|
||||
.extent = {buffer_desc.width, buffer_desc.height, 1},
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 1,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_SAMPLED_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
|
||||
vk::image vimage(device, img_info);
|
||||
|
||||
VkImportAndroidHardwareBufferInfoANDROID mem_info3{
|
||||
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID,
|
||||
.buffer = hardware_buffer};
|
||||
|
||||
VkMemoryDedicatedAllocateInfo mem_info2{.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
|
||||
.pNext = &mem_info3,
|
||||
.image = vimage};
|
||||
|
||||
assert(properties.memoryTypeBits != 0);
|
||||
VkMemoryAllocateInfo mem_info{.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
|
||||
.pNext = &mem_info2,
|
||||
.allocationSize = properties.allocationSize,
|
||||
.memoryTypeIndex = (uint32_t)(ffs(properties.memoryTypeBits) - 1)};
|
||||
|
||||
vk::device_memory memory(device, mem_info);
|
||||
CHECK_VK(vkBindImageMemory(device, vimage, memory, 0));
|
||||
|
||||
VkSamplerYcbcrConversionInfo ycbcr_info{.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO,
|
||||
.conversion = pipeline->ycbcr_conversion};
|
||||
|
||||
VkImageViewCreateInfo iv_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
|
||||
.pNext = &ycbcr_info,
|
||||
.image = vimage,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D,
|
||||
.format = VK_FORMAT_UNDEFINED,
|
||||
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
|
||||
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1}};
|
||||
|
||||
// TODO: vk::image_view
|
||||
VkImageView image_view;
|
||||
application::ignore_debug_reports_for(vimage);
|
||||
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &image_view));
|
||||
application::unignore_debug_reports_for(vimage);
|
||||
|
||||
// TODO: vk::descriptor_set
|
||||
VkDescriptorSet descriptor_set;
|
||||
VkDescriptorSetAllocateInfo descriptor_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
|
||||
.descriptorPool = pipeline->descriptor_pool,
|
||||
.descriptorSetCount = 1,
|
||||
.pSetLayouts = &pipeline->descriptor_set_layout,
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock lock(pipeline->descriptor_pool_mutex);
|
||||
CHECK_VK(vkAllocateDescriptorSets(device, &descriptor_info, &descriptor_set));
|
||||
}
|
||||
|
||||
VkDescriptorImageInfo image_info{
|
||||
.imageView = image_view,
|
||||
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
};
|
||||
|
||||
VkWriteDescriptorSet descriptor_write{
|
||||
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
|
||||
.dstSet = descriptor_set,
|
||||
.dstBinding = 0,
|
||||
.dstArrayElement = 0,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.pImageInfo = &image_info,
|
||||
};
|
||||
|
||||
vkUpdateDescriptorSets(device, 1, &descriptor_write, 0, nullptr);
|
||||
|
||||
auto handle = std::make_shared<mapped_hardware_buffer>();
|
||||
handle->pipeline = pipeline;
|
||||
handle->vimage = vimage.release();
|
||||
handle->image_view = image_view;
|
||||
handle->memory = memory.release();
|
||||
handle->descriptor_set = descriptor_set;
|
||||
|
||||
hardware_buffer_map[hardware_buffer] = handle;
|
||||
return handle;
|
||||
}
|
||||
|
||||
void decoder::on_media_error(AMediaCodec *, void * userdata, media_status_t error, int32_t actionCode, const char * detail)
|
||||
{
|
||||
spdlog::warn("Mediacodec error: {}", detail);
|
||||
}
|
||||
void decoder::on_media_format_changed(AMediaCodec *, void * userdata, AMediaFormat *)
|
||||
{
|
||||
spdlog::info("Mediacodec format changed");
|
||||
}
|
||||
void decoder::on_media_input_available(AMediaCodec *, void * userdata, int32_t index)
|
||||
{
|
||||
auto self = (decoder *)userdata;
|
||||
self->input_buffers.push(index);
|
||||
}
|
||||
void decoder::on_media_output_available(AMediaCodec * media_codec, void * userdata, int32_t index, AMediaCodecBufferInfo * bufferInfo)
|
||||
{
|
||||
auto self = (decoder *)userdata;
|
||||
self->output_buffers.push(index);
|
||||
// will be consumed by dedicated thread
|
||||
}
|
||||
|
||||
void decoder::blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> target_indices)
|
||||
{
|
||||
if (handle.vk_data->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
|
||||
{
|
||||
VkImageMemoryBarrier memory_barrier{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.srcAccessMask = 0,
|
||||
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
|
||||
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = handle.vk_data->vimage,
|
||||
.subresourceRange = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
}};
|
||||
|
||||
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &memory_barrier);
|
||||
|
||||
handle.vk_data->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||||
}
|
||||
|
||||
for (size_t target_index: target_indices)
|
||||
{
|
||||
assert(target_index < blit_targets.size());
|
||||
|
||||
auto & target = blit_targets[target_index];
|
||||
if (description.offset_x > target.offset.x + target.extent.width)
|
||||
continue;
|
||||
if (description.offset_x + description.width < target.offset.x)
|
||||
continue;
|
||||
|
||||
int x0 = description.offset_x - target.offset.x;
|
||||
int y0 = description.offset_y;
|
||||
int x1 = x0 + description.width;
|
||||
int y1 = y0 + description.height;
|
||||
|
||||
VkRenderPassBeginInfo begin_info{
|
||||
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
|
||||
.renderPass = renderpass,
|
||||
.framebuffer = target.framebuffer,
|
||||
.renderArea =
|
||||
{
|
||||
.offset = {0, 0},
|
||||
.extent = target.extent,
|
||||
},
|
||||
.clearValueCount = 0,
|
||||
};
|
||||
|
||||
vkCmdBeginRenderPass(command_buffer, &begin_info, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, handle.vk_data->pipeline->pipeline);
|
||||
|
||||
VkViewport viewport{.x = (float)x0,
|
||||
.y = (float)y0,
|
||||
.width = (float)description.width,
|
||||
.height = (float)description.height,
|
||||
.minDepth = 0,
|
||||
.maxDepth = 1};
|
||||
|
||||
x0 = std::clamp<int>(x0, 0, target.extent.width);
|
||||
x1 = std::clamp<int>(x1, 0, target.extent.width);
|
||||
y0 = std::clamp<int>(y0, 0, target.extent.height);
|
||||
y1 = std::clamp<int>(y1, 0, target.extent.height);
|
||||
|
||||
VkRect2D scissor{
|
||||
.offset = {.x = x0, .y = y0},
|
||||
.extent = {.width = (uint32_t)(x1 - x0), .height = (uint32_t)(y1 - y0)},
|
||||
};
|
||||
|
||||
vkCmdSetViewport(command_buffer, 0, 1, &viewport);
|
||||
vkCmdSetScissor(command_buffer, 0, 1, &scissor);
|
||||
|
||||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, handle.vk_data->pipeline->layout, 0, 1, &handle.vk_data->descriptor_set, 0, nullptr);
|
||||
vkCmdDraw(command_buffer, 3, 1, 0, 0);
|
||||
|
||||
vkCmdEndRenderPass(command_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
decoder::blit_handle::~blit_handle()
|
||||
{
|
||||
AImage_delete(aimage);
|
||||
}
|
||||
|
||||
} // namespace wivrn::android
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* 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/sync_queue.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/image.h"
|
||||
#include "vk/renderpass.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include <media/NdkImage.h>
|
||||
#include <media/NdkImageReader.h>
|
||||
#include <media/NdkMediaCodec.h>
|
||||
#include <media/NdkMediaFormat.h>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
#define DEUGLIFY(x) \
|
||||
struct x##_deleter \
|
||||
{ \
|
||||
void operator()(x * ptr) \
|
||||
{ \
|
||||
x##_delete(ptr); \
|
||||
} \
|
||||
}; \
|
||||
using x##_ptr = std::unique_ptr<x, x##_deleter>;
|
||||
|
||||
DEUGLIFY(AImageReader)
|
||||
DEUGLIFY(AMediaCodec)
|
||||
|
||||
class shard_accumulator;
|
||||
|
||||
namespace scenes
|
||||
{
|
||||
class stream;
|
||||
}
|
||||
|
||||
namespace wivrn::android
|
||||
{
|
||||
class decoder
|
||||
{
|
||||
public:
|
||||
struct pipeline_context;
|
||||
|
||||
struct blit_target
|
||||
{
|
||||
VkImage image;
|
||||
VkImageView image_view;
|
||||
VkOffset2D offset;
|
||||
VkExtent2D extent;
|
||||
|
||||
VkFramebuffer framebuffer;
|
||||
std::shared_ptr<pipeline_context> pipeline;
|
||||
};
|
||||
|
||||
struct mapped_hardware_buffer;
|
||||
|
||||
struct blit_handle
|
||||
{
|
||||
xrt::drivers::wivrn::from_headset::feedback feedback;
|
||||
xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t view_info;
|
||||
|
||||
std::shared_ptr<mapped_hardware_buffer> vk_data;
|
||||
|
||||
AImage * aimage{};
|
||||
|
||||
~blit_handle();
|
||||
};
|
||||
|
||||
private:
|
||||
xrt::drivers::wivrn::to_headset::video_stream_description::item description;
|
||||
|
||||
VkDevice device;
|
||||
|
||||
AImageReader_ptr image_reader;
|
||||
|
||||
AMediaCodec_ptr media_codec;
|
||||
std::weak_ptr<scenes::stream> weak_scene;
|
||||
shard_accumulator * accumulator;
|
||||
|
||||
PFN_vkGetAndroidHardwareBufferPropertiesANDROID vkGetAndroidHardwareBufferPropertiesANDROID;
|
||||
|
||||
void on_image_available(AImageReader * reader);
|
||||
static void on_image_available(void * context, AImageReader * reader);
|
||||
|
||||
utils::sync_queue<int32_t> input_buffers;
|
||||
utils::sync_queue<int32_t> output_buffers;
|
||||
utils::sync_queue<std::pair<xrt::drivers::wivrn::from_headset::feedback, xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t>> frame_infos;
|
||||
|
||||
std::thread output_releaser;
|
||||
static void on_media_error(AMediaCodec *, void * userdata, media_status_t error, int32_t actionCode, const char * detail);
|
||||
static void on_media_format_changed(AMediaCodec *, void * userdata, AMediaFormat *);
|
||||
static void on_media_input_available(AMediaCodec *, void * userdata, int32_t index);
|
||||
static void on_media_output_available(AMediaCodec *, void * userdata, int32_t index, AMediaCodecBufferInfo * bufferInfo);
|
||||
|
||||
void push_nals(std::span<uint8_t> data, int64_t timestamp, uint32_t flags);
|
||||
|
||||
std::vector<blit_target> blit_targets;
|
||||
|
||||
std::shared_ptr<pipeline_context> pipeline;
|
||||
std::mutex hbm_mutex;
|
||||
std::unordered_map<AHardwareBuffer *, std::shared_ptr<mapped_hardware_buffer>> hardware_buffer_map;
|
||||
vk::renderpass renderpass;
|
||||
|
||||
std::shared_ptr<mapped_hardware_buffer> map_hardware_buffer(AImage *);
|
||||
|
||||
public:
|
||||
decoder(VkDevice device, VkPhysicalDevice physical_device, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, std::weak_ptr<scenes::stream> scene, shard_accumulator * accumulator);
|
||||
|
||||
decoder(const decoder &) = delete;
|
||||
decoder(decoder &&) = delete;
|
||||
~decoder();
|
||||
|
||||
void push_data(std::span<uint8_t> data, uint64_t frame_index, bool partial);
|
||||
|
||||
void frame_completed(xrt::drivers::wivrn::from_headset::feedback &, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info);
|
||||
|
||||
const auto & desc() const
|
||||
{
|
||||
return description;
|
||||
}
|
||||
|
||||
static const VkImageLayout framebuffer_expected_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
||||
static const VkImageUsageFlagBits framebuffer_usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
|
||||
|
||||
void set_blit_targets(std::vector<blit_target> targets, VkFormat format);
|
||||
void blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> target_indices);
|
||||
void blit_finished(blit_handle & handle);
|
||||
};
|
||||
|
||||
} // namespace wivrn::android
|
||||
@@ -0,0 +1,252 @@
|
||||
/*
|
||||
* 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 "ffmpeg_decoder.h"
|
||||
|
||||
#include "scenes/stream.h"
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "utils/check.h"
|
||||
#include <cassert>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavutil/buffer.h>
|
||||
#include <libavutil/hwcontext.h>
|
||||
#include <libavutil/hwcontext_vulkan.h>
|
||||
#include <libswscale/swscale.h>
|
||||
}
|
||||
|
||||
namespace ffmpeg
|
||||
{
|
||||
static void free_codec_context(AVCodecContext * ctx)
|
||||
{
|
||||
avcodec_free_context(&ctx);
|
||||
}
|
||||
|
||||
static void free_frame(AVFrame * frame)
|
||||
{
|
||||
av_frame_free(&frame);
|
||||
}
|
||||
|
||||
static AVCodecID codec_id(xrt::drivers::wivrn::video_codec codec)
|
||||
{
|
||||
using c = xrt::drivers::wivrn::video_codec;
|
||||
switch (codec)
|
||||
{
|
||||
case c::h264:
|
||||
return AV_CODEC_ID_H264;
|
||||
case c::h265:
|
||||
return AV_CODEC_ID_HEVC;
|
||||
}
|
||||
assert(false);
|
||||
__builtin_unreachable();
|
||||
}
|
||||
|
||||
decoder::blit_handle::~blit_handle()
|
||||
{
|
||||
std::lock_guard lock(self->mutex);
|
||||
if (image_index < 0)
|
||||
return;
|
||||
|
||||
self->free_images.push_back(image_index);
|
||||
}
|
||||
|
||||
decoder::decoder(VkDevice device, VkPhysicalDevice physical_device, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, std::weak_ptr<scenes::stream> scene, shard_accumulator * accumulator) :
|
||||
device(device), description(description), codec(nullptr, free_codec_context), sws(nullptr, sws_freeContext), weak_scene(scene), accumulator(accumulator)
|
||||
{
|
||||
free_images.resize(image_count);
|
||||
|
||||
for (int i = 0; i < image_count; i++)
|
||||
{
|
||||
free_images[i] = i;
|
||||
|
||||
VkImageCreateInfo image_info{};
|
||||
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
|
||||
image_info.imageType = VK_IMAGE_TYPE_2D;
|
||||
image_info.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32;
|
||||
image_info.extent.width = description.width;
|
||||
image_info.extent.height = description.height;
|
||||
image_info.extent.depth = 1;
|
||||
image_info.mipLevels = 1;
|
||||
image_info.arrayLayers = 1;
|
||||
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
|
||||
image_info.tiling = VK_IMAGE_TILING_LINEAR;
|
||||
image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
|
||||
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
image_info.queueFamilyIndexCount = 0;
|
||||
image_info.pQueueFamilyIndices = NULL;
|
||||
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
|
||||
decoded_images[i].image = vk::image(device, image_info);
|
||||
decoded_images[i].memory = vk::device_memory(device, physical_device, decoded_images[i].image, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
|
||||
decoded_images[i].memory.map_memory();
|
||||
|
||||
VkImageSubresource resource{};
|
||||
resource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
|
||||
vkGetImageSubresourceLayout(device, decoded_images[i].image, &resource, &decoded_images[i].layout);
|
||||
}
|
||||
|
||||
auto avcodec = avcodec_find_decoder(codec_id(description.codec));
|
||||
if (avcodec == nullptr)
|
||||
{
|
||||
throw std::runtime_error{"avcodec_find_decoder failed"};
|
||||
}
|
||||
|
||||
codec.reset(avcodec_alloc_context3(avcodec));
|
||||
|
||||
int ret = avcodec_open2(codec.get(), avcodec, nullptr);
|
||||
if (ret < 0)
|
||||
throw std::runtime_error{"avcodec_open2 failed"};
|
||||
}
|
||||
|
||||
void decoder::set_blit_targets(std::vector<blit_target> targets, VkFormat format)
|
||||
{
|
||||
blit_targets = std::move(targets);
|
||||
}
|
||||
|
||||
void decoder::blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> blit_indices)
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
|
||||
// Transition layout to VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL
|
||||
// TODO: transition only if needed
|
||||
VkImageMemoryBarrier barrier{};
|
||||
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
|
||||
barrier.image = handle.image;
|
||||
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
barrier.subresourceRange.levelCount = 1;
|
||||
barrier.subresourceRange.layerCount = 1;
|
||||
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||||
|
||||
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
|
||||
|
||||
for (int blit_index: blit_indices)
|
||||
{
|
||||
uint32_t left = blit_targets[blit_index].offset.x;
|
||||
uint32_t right = left + blit_targets[blit_index].extent.width;
|
||||
|
||||
uint32_t width = blit_targets[blit_index].extent.width;
|
||||
uint32_t height = blit_targets[blit_index].extent.height;
|
||||
|
||||
// check for intersection
|
||||
if (description.offset_x >= right or description.offset_x + description.width <= left)
|
||||
continue;
|
||||
|
||||
VkImageBlit blit{};
|
||||
|
||||
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
blit.srcSubresource.layerCount = 1;
|
||||
blit.srcOffsets[0].x = std::max<int32_t>(0, left - description.offset_x);
|
||||
blit.srcOffsets[0].y = 0;
|
||||
blit.srcOffsets[1].x = std::min<int32_t>(description.width, right - description.offset_x);
|
||||
blit.srcOffsets[1].y = std::min<int32_t>(description.height, height - description.offset_y);
|
||||
blit.srcOffsets[1].z = 1;
|
||||
|
||||
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
blit.dstSubresource.layerCount = 1;
|
||||
blit.dstOffsets[0].x = std::max<int32_t>(0, description.offset_x - left);
|
||||
blit.dstOffsets[0].y = description.offset_y;
|
||||
blit.dstOffsets[1].x = std::min<int32_t>(width, description.offset_x + description.width - left);
|
||||
blit.dstOffsets[1].y = std::min<int32_t>(height, description.offset_y + description.height);
|
||||
blit.dstOffsets[1].z = 1;
|
||||
vkCmdBlitImage(command_buffer, handle.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, blit_targets[blit_index].image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR);
|
||||
}
|
||||
}
|
||||
|
||||
void decoder::push_data(std::span<uint8_t> data, uint64_t frame_index, bool partial)
|
||||
{
|
||||
packet.insert(packet.end(), data.begin(), data.end());
|
||||
this->frame_index = frame_index;
|
||||
}
|
||||
|
||||
void decoder::frame_completed(const xrt::drivers::wivrn::from_headset::feedback & feedback, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info)
|
||||
{
|
||||
spdlog::trace("ffmpeg decoder:frame_completed {}", frame_index);
|
||||
AVPacket packet{};
|
||||
packet.pts = AV_NOPTS_VALUE;
|
||||
packet.dts = AV_NOPTS_VALUE;
|
||||
packet.data = this->packet.data();
|
||||
packet.size = this->packet.size();
|
||||
packet.pos = -1;
|
||||
|
||||
int res = AVERROR(EAGAIN);
|
||||
while (res == AVERROR(EAGAIN))
|
||||
{
|
||||
res = avcodec_send_packet(codec.get(), &packet);
|
||||
if (res == AVERROR(EAGAIN))
|
||||
{
|
||||
spdlog::warn("EAGAIN in avcodec_send_packet");
|
||||
frame_completed(feedback, view_info);
|
||||
}
|
||||
}
|
||||
if (res < 0)
|
||||
throw std::runtime_error{"avcodec_send_packet failed"};
|
||||
|
||||
std::unique_ptr<AVFrame, void (*)(AVFrame *)> frame(av_frame_alloc(), free_frame);
|
||||
res = avcodec_receive_frame(codec.get(), frame.get());
|
||||
if (res == AVERROR(EAGAIN))
|
||||
return;
|
||||
if (res != 0)
|
||||
throw std::runtime_error{"avcodec_receive_frame failed"};
|
||||
|
||||
this->packet.clear();
|
||||
|
||||
if (!sws)
|
||||
{
|
||||
sws.reset(sws_getContext(frame->width, frame->height, (AVPixelFormat)frame->format, description.width, description.height, AV_PIX_FMT_RGB0, SWS_BILINEAR, nullptr, nullptr, nullptr));
|
||||
}
|
||||
|
||||
std::unique_lock lock(mutex);
|
||||
if (free_images.empty())
|
||||
{
|
||||
spdlog::warn("No free image");
|
||||
return;
|
||||
}
|
||||
|
||||
int index = free_images.back();
|
||||
free_images.pop_back();
|
||||
lock.unlock();
|
||||
|
||||
decoded_images[index].frame_index = frame_index;
|
||||
int dstStride = decoded_images[index].layout.rowPitch;
|
||||
uint8_t * out = (uint8_t *)decoded_images[index].memory.data();
|
||||
res = sws_scale(sws.get(), frame->data, frame->linesize, 0, frame->height, &out, &dstStride);
|
||||
if (res == 0)
|
||||
throw std::runtime_error{"sws_scale failed"};
|
||||
|
||||
auto handle = std::make_shared<decoder::blit_handle>();
|
||||
handle->feedback = feedback;
|
||||
handle->view_info = view_info;
|
||||
handle->image = decoded_images[index].image;
|
||||
handle->image_index = index;
|
||||
handle->self = this;
|
||||
|
||||
if (auto scene = weak_scene.lock())
|
||||
scene->push_blit_handle(accumulator, std::move(handle));
|
||||
}
|
||||
|
||||
} // namespace ffmpeg
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* 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 "vk/device_memory.h"
|
||||
#include "vk/image.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
class shard_accumulator;
|
||||
|
||||
extern "C"
|
||||
{
|
||||
struct AVBufferRef;
|
||||
struct AVCodecContext;
|
||||
struct SwsContext;
|
||||
}
|
||||
|
||||
namespace scenes
|
||||
{
|
||||
class stream;
|
||||
}
|
||||
|
||||
namespace ffmpeg
|
||||
{
|
||||
class decoder
|
||||
{
|
||||
public:
|
||||
struct blit_target
|
||||
{
|
||||
VkImage image;
|
||||
VkImageView image_view;
|
||||
VkOffset2D offset;
|
||||
VkExtent2D extent;
|
||||
};
|
||||
|
||||
private:
|
||||
static const int image_count = 3;
|
||||
struct image
|
||||
{
|
||||
vk::image image;
|
||||
vk::device_memory memory;
|
||||
VkSubresourceLayout layout;
|
||||
uint64_t frame_index;
|
||||
};
|
||||
|
||||
VkDevice device;
|
||||
std::array<image, image_count> decoded_images;
|
||||
std::vector<int> free_images;
|
||||
|
||||
xrt::drivers::wivrn::to_headset::video_stream_description::item description;
|
||||
|
||||
std::unique_ptr<AVCodecContext, void (*)(AVCodecContext *)> codec;
|
||||
std::unique_ptr<SwsContext, void (*)(SwsContext *)> sws;
|
||||
std::vector<uint8_t> packet;
|
||||
uint64_t frame_index;
|
||||
std::weak_ptr<scenes::stream> weak_scene;
|
||||
shard_accumulator * accumulator;
|
||||
|
||||
std::vector<blit_target> blit_targets;
|
||||
std::mutex mutex;
|
||||
|
||||
public:
|
||||
decoder(VkDevice device, VkPhysicalDevice physical_device, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, std::weak_ptr<scenes::stream> scene, shard_accumulator * accumulator);
|
||||
|
||||
void push_data(std::span<uint8_t> data, uint64_t frame_index, bool partial);
|
||||
|
||||
void frame_completed(const xrt::drivers::wivrn::from_headset::feedback &, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info);
|
||||
|
||||
const auto & desc() const
|
||||
{
|
||||
return description;
|
||||
}
|
||||
|
||||
struct blit_handle
|
||||
{
|
||||
xrt::drivers::wivrn::from_headset::feedback feedback;
|
||||
xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t view_info;
|
||||
int image_index;
|
||||
VkImage image;
|
||||
decoder * self;
|
||||
|
||||
~blit_handle();
|
||||
};
|
||||
|
||||
static const VkImageLayout framebuffer_expected_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
||||
static const VkImageUsageFlagBits framebuffer_usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||
|
||||
void set_blit_targets(std::vector<blit_target> targets, VkFormat format);
|
||||
void blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> target_indices);
|
||||
};
|
||||
} // namespace ffmpeg
|
||||
@@ -0,0 +1,349 @@
|
||||
/*
|
||||
* 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 "shard_accumulator.h"
|
||||
#include "application.h"
|
||||
#include "external/rs.h"
|
||||
#include "scenes/stream.h"
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "utils/typename.h"
|
||||
#include "wivrn_serialization.h"
|
||||
|
||||
using namespace xrt::drivers::wivrn::to_headset;
|
||||
using shard_set = shard_accumulator::shard_set;
|
||||
using data_shard = shard_accumulator::data_shard;
|
||||
using parity_shard = shard_accumulator::parity_shard;
|
||||
|
||||
shard_set::shard_set(uint8_t stream_index)
|
||||
{
|
||||
feedback.stream_index = stream_index;
|
||||
}
|
||||
|
||||
void shard_set::reset(uint64_t frame_index)
|
||||
{
|
||||
num_shards = 0;
|
||||
min_for_reconstruction = -1;
|
||||
data.clear();
|
||||
parity.clear();
|
||||
|
||||
uint8_t stream_index = feedback.stream_index;
|
||||
feedback = {};
|
||||
feedback.frame_index = frame_index;
|
||||
feedback.stream_index = stream_index;
|
||||
}
|
||||
|
||||
bool shard_set::empty() const
|
||||
{
|
||||
return num_shards == 0;
|
||||
}
|
||||
|
||||
static bool is_complete(const shard_set & shards)
|
||||
{
|
||||
const auto & frame = shards.data;
|
||||
if (frame.empty())
|
||||
return false;
|
||||
if (not(frame.back() and frame.back()->flags & video_stream_data_shard::end_of_frame))
|
||||
return false;
|
||||
for (const auto & shard: frame)
|
||||
if (not shard)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
uint16_t shard_set::insert(data_shard && shard)
|
||||
{
|
||||
XrTime now = application::now();
|
||||
if (empty())
|
||||
feedback.received_first_packet = now;
|
||||
feedback.received_last_packet = now;
|
||||
|
||||
auto idx = shard.shard_idx;
|
||||
if (idx >= data.size())
|
||||
data.resize(idx + 1);
|
||||
if (not data[idx])
|
||||
++num_shards;
|
||||
data[idx] = std::move(shard);
|
||||
if (auto i = try_reconstruct())
|
||||
return *i;
|
||||
return idx;
|
||||
}
|
||||
|
||||
std::optional<uint16_t> shard_set::insert(parity_shard && shard)
|
||||
{
|
||||
XrTime now = application::now();
|
||||
if (empty())
|
||||
feedback.received_first_packet = now;
|
||||
feedback.received_last_packet = now;
|
||||
|
||||
auto idx = shard.parity_element;
|
||||
min_for_reconstruction = shard.data_shard_count;
|
||||
if (idx >= parity.size())
|
||||
parity.resize(idx + 1);
|
||||
if (not parity[idx])
|
||||
++num_shards;
|
||||
parity[idx] = std::move(shard);
|
||||
|
||||
return try_reconstruct();
|
||||
}
|
||||
|
||||
parity_shard & shard_set::get_parity()
|
||||
{
|
||||
for (auto & shard: parity)
|
||||
{
|
||||
if (shard)
|
||||
return *shard;
|
||||
}
|
||||
// this function shall be called only when at least one parity shard exists
|
||||
assert(false);
|
||||
|
||||
__builtin_unreachable();
|
||||
}
|
||||
|
||||
std::optional<uint16_t> shard_set::try_reconstruct()
|
||||
{
|
||||
if (parity.empty())
|
||||
return {};
|
||||
if (num_shards < min_for_reconstruction)
|
||||
return {};
|
||||
|
||||
static std::once_flag once;
|
||||
std::call_once(once, reed_solomon_init);
|
||||
auto & p = get_parity();
|
||||
std::unique_ptr<reed_solomon, void (*)(reed_solomon *)> rs(
|
||||
reed_solomon_new(p.data_shard_count, p.num_parity_elements), reed_solomon_release);
|
||||
|
||||
size_t shard_size = p.payload.size();
|
||||
|
||||
std::vector<uint8_t *> rs_shards;
|
||||
std::vector<uint8_t> rs_marks;
|
||||
|
||||
std::vector<std::vector<uint8_t>> data_raw;
|
||||
data.resize(p.data_shard_count);
|
||||
data_raw.reserve(p.data_shard_count);
|
||||
for (auto & shard: data)
|
||||
{
|
||||
if (shard)
|
||||
{
|
||||
xrt::drivers::wivrn::serialization_packet s;
|
||||
s.serialize(*shard);
|
||||
data_raw.emplace_back(std::move(s)).resize(shard_size);
|
||||
rs_marks.push_back(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
data_raw.emplace_back(shard_size, 0);
|
||||
rs_marks.push_back(1);
|
||||
}
|
||||
rs_shards.push_back(data_raw.back().data());
|
||||
}
|
||||
// WARNING: do not use p after this line, the array it points to has been modified
|
||||
parity.resize(p.num_parity_elements);
|
||||
std::vector<std::vector<uint8_t>> dummy;
|
||||
dummy.reserve(p.num_parity_elements);
|
||||
for (auto & shard: parity)
|
||||
{
|
||||
if (shard)
|
||||
{
|
||||
rs_shards.push_back(shard->payload.data());
|
||||
rs_marks.push_back(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
auto d = dummy.emplace_back(shard_size).data();
|
||||
rs_shards.push_back(d);
|
||||
rs_marks.push_back(1);
|
||||
}
|
||||
}
|
||||
|
||||
int err = reed_solomon_reconstruct(rs.get(), rs_shards.data(), rs_marks.data(), data.size() + parity.size(), shard_size);
|
||||
if (err)
|
||||
{
|
||||
spdlog::info("reed_solomon_reconstruct failed");
|
||||
return {};
|
||||
}
|
||||
std::optional<uint16_t> first_reconstructed;
|
||||
for (size_t i = 0; i < data.size(); ++i)
|
||||
{
|
||||
if (not data[i])
|
||||
{
|
||||
xrt::drivers::wivrn::deserialization_packet d(data_raw[i]);
|
||||
data[i] = d.deserialize<data_shard>();
|
||||
if (not first_reconstructed)
|
||||
first_reconstructed = i;
|
||||
}
|
||||
}
|
||||
assert(first_reconstructed);
|
||||
spdlog::info("reed_solomon_reconstruct success frame {}, reconstructed {} (out of {} shards)",
|
||||
data[0]->frame_idx,
|
||||
*first_reconstructed,
|
||||
data.size());
|
||||
|
||||
feedback.reconstructed = application::now();
|
||||
return first_reconstructed;
|
||||
}
|
||||
|
||||
static void debug_why_not_sent(const shard_set & shards)
|
||||
{
|
||||
const auto & frame = shards.data;
|
||||
if (frame.empty())
|
||||
{
|
||||
spdlog::info("frame {} was not sent because no shard was received", shards.frame_index());
|
||||
return;
|
||||
}
|
||||
int frame_idx = -1;
|
||||
int expected_data = -1;
|
||||
int expected_parity = -1;
|
||||
size_t data = 0;
|
||||
size_t parity = 0;
|
||||
for (const auto & shard: frame)
|
||||
{
|
||||
if (shard)
|
||||
{
|
||||
frame_idx = shard->frame_idx;
|
||||
++data;
|
||||
}
|
||||
}
|
||||
for (const auto & shard: shards.parity)
|
||||
{
|
||||
if (shard)
|
||||
{
|
||||
frame_idx = shard->frame_idx;
|
||||
expected_data = shard->data_shard_count;
|
||||
expected_parity = shard->num_parity_elements;
|
||||
++parity;
|
||||
}
|
||||
}
|
||||
|
||||
spdlog::info("frame {} was not sent with {}/{} data, {}/{} parity shards)", frame_idx, data, expected_data, parity, expected_parity);
|
||||
}
|
||||
|
||||
void shard_accumulator::advance()
|
||||
{
|
||||
std::swap(current, next);
|
||||
next.reset(current.frame_index() + 1);
|
||||
}
|
||||
|
||||
template <typename Shard>
|
||||
void shard_accumulator::push_shard(Shard && shard)
|
||||
{
|
||||
assert(current.frame_index() + 1 == next.frame_index());
|
||||
|
||||
uint8_t frame_diff = shard.frame_idx - current.frame_index();
|
||||
if (shard.frame_idx < current.frame_index())
|
||||
{
|
||||
// frame is in the past, drop it
|
||||
}
|
||||
else if (frame_diff == 0)
|
||||
{
|
||||
// Due to error correction, inserting a shard might create a valid one before
|
||||
auto shard_idx = current.insert(std::move(shard));
|
||||
try_submit_frame(shard_idx);
|
||||
}
|
||||
else if (frame_diff == 1)
|
||||
{
|
||||
next.insert(std::move(shard));
|
||||
if (is_complete(next))
|
||||
{
|
||||
debug_why_not_sent(current);
|
||||
send_feedback(current.feedback);
|
||||
|
||||
advance();
|
||||
|
||||
try_submit_frame(0);
|
||||
}
|
||||
}
|
||||
else if (frame_diff == 2)
|
||||
{
|
||||
debug_why_not_sent(current);
|
||||
send_feedback(current.feedback);
|
||||
|
||||
advance();
|
||||
|
||||
push_shard(std::move(shard));
|
||||
}
|
||||
else
|
||||
{
|
||||
// We have lost more than one frame
|
||||
send_feedback(current.feedback);
|
||||
send_feedback(next.feedback);
|
||||
|
||||
current.reset(shard.frame_idx);
|
||||
next.reset(shard.frame_idx + 1);
|
||||
|
||||
push_shard(std::move(shard));
|
||||
}
|
||||
}
|
||||
|
||||
template void shard_accumulator::push_shard<parity_shard>(parity_shard && shard);
|
||||
template void shard_accumulator::push_shard<video_stream_data_shard>(video_stream_data_shard && shard);
|
||||
|
||||
void shard_accumulator::try_submit_frame(std::optional<uint16_t> shard_idx)
|
||||
{
|
||||
if (shard_idx)
|
||||
try_submit_frame(*shard_idx);
|
||||
}
|
||||
|
||||
void shard_accumulator::try_submit_frame(uint16_t shard_idx)
|
||||
{
|
||||
auto & data_shards = current.data;
|
||||
// Do not submit if the frame is not complete
|
||||
for (const auto & shard: data_shards)
|
||||
{
|
||||
if (not shard)
|
||||
return;
|
||||
}
|
||||
if (not(data_shards.back()->flags & video_stream_data_shard::end_of_frame))
|
||||
return;
|
||||
|
||||
uint64_t frame_index = data_shards[0]->frame_idx;
|
||||
if (data_shards.size() == 1)
|
||||
decoder->push_data(data_shards[shard_idx]->payload, frame_index, false);
|
||||
else
|
||||
{
|
||||
// Slice is over multiple shards, concatenate them
|
||||
std::vector<uint8_t> payload;
|
||||
size_t size = 0;
|
||||
for (const auto & shard: data_shards)
|
||||
{
|
||||
size += shard->payload.size();
|
||||
}
|
||||
payload.reserve(size);
|
||||
for (const auto & shard: data_shards)
|
||||
{
|
||||
payload.insert(payload.end(), shard->payload.begin(), shard->payload.end());
|
||||
}
|
||||
decoder->push_data(payload, frame_index, false);
|
||||
}
|
||||
|
||||
auto feedback = current.feedback;
|
||||
assert(data_shards.back()->view_info);
|
||||
feedback.received_pose = data_shards.back()->view_info->pose;
|
||||
|
||||
// Try to extract a frame
|
||||
decoder->frame_completed(feedback, *data_shards.back()->view_info);
|
||||
|
||||
advance();
|
||||
}
|
||||
|
||||
void shard_accumulator::send_feedback(const xrt::drivers::wivrn::from_headset::feedback & feedback)
|
||||
{
|
||||
auto scene = weak_scene.lock();
|
||||
if (scene)
|
||||
scene->send_feedback(feedback);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* 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 "xr/instance.h"
|
||||
#include <memory>
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#include "decoder/android/android_decoder.h"
|
||||
using decoder_impl = ::wivrn::android::decoder;
|
||||
#else
|
||||
#include "decoder/ffmpeg/ffmpeg_decoder.h"
|
||||
using decoder_impl = ::ffmpeg::decoder;
|
||||
#endif
|
||||
|
||||
#include "wivrn_packets.h"
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
class shard_accumulator
|
||||
{
|
||||
std::shared_ptr<decoder_impl> decoder;
|
||||
|
||||
public:
|
||||
using data_shard = xrt::drivers::wivrn::to_headset::video_stream_data_shard;
|
||||
using parity_shard = xrt::drivers::wivrn::to_headset::video_stream_parity_shard;
|
||||
struct shard_set
|
||||
{
|
||||
size_t num_shards = 0;
|
||||
size_t min_for_reconstruction = -1;
|
||||
std::vector<std::optional<data_shard>> data;
|
||||
std::vector<std::optional<parity_shard>> parity;
|
||||
void reset(uint64_t frame_index);
|
||||
bool empty() const;
|
||||
|
||||
uint16_t insert(data_shard &&);
|
||||
std::optional<uint16_t> insert(parity_shard &&);
|
||||
|
||||
parity_shard & get_parity();
|
||||
std::optional<uint16_t> try_reconstruct();
|
||||
|
||||
xrt::drivers::wivrn::from_headset::feedback feedback{};
|
||||
|
||||
explicit shard_set(uint8_t stream_index);
|
||||
shard_set(const shard_set &) = default;
|
||||
shard_set(shard_set &&) = default;
|
||||
shard_set & operator=(const shard_set &) = default;
|
||||
shard_set & operator=(shard_set &&) = default;
|
||||
|
||||
uint64_t frame_index() const
|
||||
{
|
||||
return feedback.frame_index;
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
shard_set current;
|
||||
shard_set next;
|
||||
std::weak_ptr<scenes::stream> weak_scene;
|
||||
|
||||
public:
|
||||
explicit shard_accumulator(
|
||||
VkDevice device,
|
||||
VkPhysicalDevice physical_device,
|
||||
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
|
||||
std::weak_ptr<scenes::stream> scene,
|
||||
uint8_t stream_index) :
|
||||
decoder(std::make_shared<decoder_impl>(device, physical_device, description, scene, this)),
|
||||
current(stream_index),
|
||||
next(stream_index),
|
||||
weak_scene(scene)
|
||||
{
|
||||
next.reset(1);
|
||||
}
|
||||
|
||||
template <typename Shard>
|
||||
void push_shard(Shard &&);
|
||||
|
||||
auto & desc() const
|
||||
{
|
||||
return decoder->desc();
|
||||
}
|
||||
|
||||
using blit_handle = decoder_impl::blit_handle;
|
||||
using blit_target = decoder_impl::blit_target;
|
||||
|
||||
static const VkImageLayout framebuffer_expected_layout = decoder_impl::framebuffer_expected_layout;
|
||||
static const VkImageUsageFlagBits framebuffer_usage = decoder_impl::framebuffer_usage;
|
||||
|
||||
void set_blit_targets(std::vector<blit_target> targets, VkFormat format)
|
||||
{
|
||||
decoder->set_blit_targets(std::move(targets), format);
|
||||
}
|
||||
|
||||
void blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> blit_target_indices)
|
||||
{
|
||||
return decoder->blit(command_buffer, handle, blit_target_indices);
|
||||
}
|
||||
|
||||
private:
|
||||
void try_submit_frame(std::optional<uint16_t> shard_idx);
|
||||
void try_submit_frame(uint16_t shard_idx);
|
||||
void send_feedback(const xrt::drivers::wivrn::from_headset::feedback & feedback);
|
||||
void advance();
|
||||
};
|
||||
Vendored
+1387
File diff suppressed because it is too large
Load Diff
Vendored
+632
@@ -0,0 +1,632 @@
|
||||
/*
|
||||
* fec.c -- forward error correction based on Vandermonde matrices
|
||||
*
|
||||
* (C) 1997-98 Luigi Rizzo (luigi@iet.unipi.it)
|
||||
* (C) 2001 Alain Knaff (alain@knaff.lu)
|
||||
* (C) 2017 Iwan Timmer (irtimmer@gmail.com)
|
||||
*
|
||||
* Portions derived from code by Phil Karn (karn@ka9q.ampr.org),
|
||||
* Robert Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) and Hari
|
||||
* Thirumoorthy (harit@spectra.eng.hawaii.edu), Aug 1995
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials
|
||||
* provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
||||
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
|
||||
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
|
||||
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
|
||||
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
|
||||
* OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <assert.h>
|
||||
#include "rs.h"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#define alloca(x) _alloca(x)
|
||||
#endif
|
||||
|
||||
typedef unsigned char gf;
|
||||
|
||||
#define GF_BITS 8
|
||||
#define GF_PP "101110001"
|
||||
#define GF_SIZE ((1 << GF_BITS) - 1)
|
||||
|
||||
#define SWAP(a,b,t) {t tmp; tmp=a; a=b; b=tmp;}
|
||||
|
||||
/*
|
||||
* USE_GF_MULC, GF_MULC0(c) and GF_ADDMULC(x) can be used when multiplying
|
||||
* many numbers by the same constant. In this case the first
|
||||
* call sets the constant, and others perform the multiplications.
|
||||
* A value related to the multiplication is held in a local variable
|
||||
* declared with USE_GF_MULC . See usage in addmul1().
|
||||
*/
|
||||
#define USE_GF_MULC gf * __gf_mulc_
|
||||
#define GF_MULC0(c) __gf_mulc_ = &gf_mul_table[(c)<<8]
|
||||
#define GF_ADDMULC(dst, x) dst ^= __gf_mulc_[x]
|
||||
#define GF_MULC(dst, x) dst = __gf_mulc_[x]
|
||||
|
||||
#define gf_mul(x,y) gf_mul_table[(x<<8)+y]
|
||||
|
||||
/*
|
||||
* To speed up computations, we have tables for logarithm, exponent
|
||||
* multiplication and inverse of a number.
|
||||
*/
|
||||
static gf gf_exp[2*GF_SIZE];
|
||||
static int gf_log[GF_SIZE + 1];
|
||||
static gf inverse[GF_SIZE+1];
|
||||
#ifdef _MSC_VER
|
||||
static gf __declspec(align (256)) gf_mul_table[(GF_SIZE + 1)*(GF_SIZE + 1)];
|
||||
#else
|
||||
static gf gf_mul_table[(GF_SIZE + 1)*(GF_SIZE + 1)] __attribute__((aligned (256)));
|
||||
#endif
|
||||
|
||||
/*
|
||||
* modnn(x) computes x % GF_SIZE, where GF_SIZE is 2**GF_BITS - 1,
|
||||
* without a slow divide.
|
||||
*/
|
||||
static inline gf modnn(int x) {
|
||||
while (x >= GF_SIZE) {
|
||||
x -= GF_SIZE;
|
||||
x = (x >> GF_BITS) + (x & GF_SIZE);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
static void addmul(gf *dst1, gf *src1, gf c, int sz) {
|
||||
USE_GF_MULC;
|
||||
if (c != 0) {
|
||||
gf *dst = dst1, *src = src1;
|
||||
gf *lim = &dst[sz];
|
||||
|
||||
GF_MULC0(c);
|
||||
for (; dst < lim; dst++, src++)
|
||||
GF_ADDMULC(*dst, *src);
|
||||
}
|
||||
}
|
||||
|
||||
static void mul(gf *dst1, gf *src1, gf c, int sz) {
|
||||
USE_GF_MULC;
|
||||
if (c != 0) {
|
||||
gf *dst = dst1, *src = src1;
|
||||
gf *lim = &dst[sz];
|
||||
GF_MULC0(c);
|
||||
for (; dst < lim; dst++, src++)
|
||||
GF_MULC(*dst , *src);
|
||||
} else
|
||||
memset(dst1, 0, c);
|
||||
}
|
||||
|
||||
/* y = a.dot(b) */
|
||||
static gf* multiply1(gf *a, int ar, int ac, gf *b, int br, int bc) {
|
||||
gf *new_m, tg;
|
||||
int r, c, i, ptr = 0;
|
||||
|
||||
assert(ac == br);
|
||||
new_m = (gf*) calloc(1, ar*bc);
|
||||
if (NULL != new_m) {
|
||||
|
||||
/* this multiply is slow */
|
||||
for (r = 0; r < ar; r++) {
|
||||
for (c = 0; c < bc; c++) {
|
||||
tg = 0;
|
||||
for (i = 0; i < ac; i++)
|
||||
tg ^= gf_mul(a[r*ac+i], b[i*bc+c]);
|
||||
|
||||
new_m[ptr++] = tg;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new_m;
|
||||
}
|
||||
|
||||
static void init_mul_table(void) {
|
||||
int i, j;
|
||||
for (i=0; i< GF_SIZE+1; i++)
|
||||
for (j=0; j< GF_SIZE+1; j++)
|
||||
gf_mul_table[(i<<8)+j] = gf_exp[modnn(gf_log[i] + gf_log[j]) ] ;
|
||||
|
||||
for (j=0; j< GF_SIZE+1; j++)
|
||||
gf_mul_table[j] = gf_mul_table[j<<8] = 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* initialize the data structures used for computations in GF.
|
||||
*/
|
||||
static void generate_gf(void) {
|
||||
int i;
|
||||
gf mask;
|
||||
|
||||
mask = 1;
|
||||
gf_exp[GF_BITS] = 0;
|
||||
/*
|
||||
* first, generate the (polynomial representation of) powers of \alpha,
|
||||
* which are stored in gf_exp[i] = \alpha ** i .
|
||||
* At the same time build gf_log[gf_exp[i]] = i .
|
||||
* The first GF_BITS powers are simply bits shifted to the left.
|
||||
*/
|
||||
for (i = 0; i < GF_BITS; i++, mask <<= 1) {
|
||||
gf_exp[i] = mask;
|
||||
gf_log[gf_exp[i]] = i;
|
||||
/*
|
||||
* If GF_PP[i] == 1 then \alpha ** i occurs in poly-repr
|
||||
* gf_exp[GF_BITS] = \alpha ** GF_BITS
|
||||
*/
|
||||
if (GF_PP[i] == '1')
|
||||
gf_exp[GF_BITS] ^= mask;
|
||||
}
|
||||
/*
|
||||
* now gf_exp[GF_BITS] = \alpha ** GF_BITS is complete, so can als
|
||||
* compute its inverse.
|
||||
*/
|
||||
gf_log[gf_exp[GF_BITS]] = GF_BITS;
|
||||
/*
|
||||
* Poly-repr of \alpha ** (i+1) is given by poly-repr of
|
||||
* \alpha ** i shifted left one-bit and accounting for any
|
||||
* \alpha ** GF_BITS term that may occur when poly-repr of
|
||||
* \alpha ** i is shifted.
|
||||
*/
|
||||
mask = 1 << (GF_BITS - 1) ;
|
||||
for (i = GF_BITS + 1; i < GF_SIZE; i++) {
|
||||
if (gf_exp[i - 1] >= mask)
|
||||
gf_exp[i] = gf_exp[GF_BITS] ^ ((gf_exp[i - 1] ^ mask) << 1);
|
||||
else
|
||||
gf_exp[i] = gf_exp[i - 1] << 1;
|
||||
|
||||
gf_log[gf_exp[i]] = i;
|
||||
}
|
||||
/*
|
||||
* log(0) is not defined, so use a special value
|
||||
*/
|
||||
gf_log[0] = GF_SIZE;
|
||||
/* set the extended gf_exp values for fast multiply */
|
||||
for (i = 0; i < GF_SIZE; i++)
|
||||
gf_exp[i + GF_SIZE] = gf_exp[i];
|
||||
|
||||
/*
|
||||
* again special cases. 0 has no inverse. This used to
|
||||
* be initialized to GF_SIZE, but it should make no difference
|
||||
* since noone is supposed to read from here.
|
||||
*/
|
||||
inverse[0] = 0;
|
||||
inverse[1] = 1;
|
||||
for (i=2; i<=GF_SIZE; i++)
|
||||
inverse[i] = gf_exp[GF_SIZE-gf_log[i]];
|
||||
}
|
||||
|
||||
/*
|
||||
* invert_mat() takes a matrix and produces its inverse
|
||||
* k is the size of the matrix.
|
||||
* (Gauss-Jordan, adapted from Numerical Recipes in C)
|
||||
* Return non-zero if singular.
|
||||
*/
|
||||
static int invert_mat(gf *src, int k) {
|
||||
gf c, *p;
|
||||
int irow, icol, row, col, i, ix;
|
||||
|
||||
int error = 1;
|
||||
int *indxc = (int*)alloca(k*sizeof(int));
|
||||
int *indxr = (int*)alloca(k*sizeof(int));
|
||||
int *ipiv = (int*)alloca(k*sizeof(int));
|
||||
gf *id_row = (gf*)alloca(k*sizeof(gf));
|
||||
|
||||
memset(id_row, 0, k*sizeof(gf));
|
||||
/*
|
||||
* ipiv marks elements already used as pivots.
|
||||
*/
|
||||
for (i = 0; i < k; i++)
|
||||
ipiv[i] = 0;
|
||||
|
||||
for (col = 0; col < k; col++) {
|
||||
gf *pivot_row;
|
||||
/*
|
||||
* Zeroing column 'col', look for a non-zero element.
|
||||
* First try on the diagonal, if it fails, look elsewhere.
|
||||
*/
|
||||
irow = icol = -1;
|
||||
if (ipiv[col] != 1 && src[col*k + col] != 0) {
|
||||
irow = col;
|
||||
icol = col;
|
||||
goto found_piv;
|
||||
}
|
||||
for (row = 0; row < k; row++) {
|
||||
if (ipiv[row] != 1) {
|
||||
for (ix = 0; ix < k; ix++) {
|
||||
if (ipiv[ix] == 0) {
|
||||
if (src[row*k + ix] != 0) {
|
||||
irow = row;
|
||||
icol = ix;
|
||||
goto found_piv;
|
||||
}
|
||||
} else if (ipiv[ix] > 1) {
|
||||
fprintf(stderr, "singular matrix\n");
|
||||
goto fail;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (icol == -1) {
|
||||
fprintf(stderr, "XXX pivot not found!\n");
|
||||
goto fail ;
|
||||
}
|
||||
|
||||
found_piv:
|
||||
++(ipiv[icol]);
|
||||
/*
|
||||
* swap rows irow and icol, so afterwards the diagonal
|
||||
* element will be correct. Rarely done, not worth
|
||||
* optimizing.
|
||||
*/
|
||||
if (irow != icol) {
|
||||
for (ix = 0; ix < k; ix++) {
|
||||
SWAP(src[irow*k + ix], src[icol*k + ix], gf);
|
||||
}
|
||||
}
|
||||
indxr[col] = irow;
|
||||
indxc[col] = icol;
|
||||
pivot_row = &src[icol*k];
|
||||
c = pivot_row[icol];
|
||||
if (c == 0) {
|
||||
fprintf(stderr, "singular matrix 2\n");
|
||||
goto fail;
|
||||
} else if (c != 1 ) {
|
||||
/*
|
||||
* this is done often , but optimizing is not so
|
||||
* fruitful, at least in the obvious ways (unrolling)
|
||||
*/
|
||||
c = inverse[ c ];
|
||||
pivot_row[icol] = 1;
|
||||
for (ix = 0; ix < k; ix++)
|
||||
pivot_row[ix] = gf_mul(c, pivot_row[ix]);
|
||||
}
|
||||
/*
|
||||
* from all rows, remove multiples of the selected row
|
||||
* to zero the relevant entry (in fact, the entry is not zero
|
||||
* because we know it must be zero).
|
||||
* (Here, if we know that the pivot_row is the identity,
|
||||
* we can optimize the addmul).
|
||||
*/
|
||||
id_row[icol] = 1;
|
||||
if (memcmp(pivot_row, id_row, k*sizeof(gf)) != 0) {
|
||||
for (p = src, ix = 0 ; ix < k ; ix++, p += k) {
|
||||
if (ix != icol) {
|
||||
c = p[icol];
|
||||
p[icol] = 0;
|
||||
addmul(p, pivot_row, c, k);
|
||||
}
|
||||
}
|
||||
}
|
||||
id_row[icol] = 0;
|
||||
}
|
||||
for (col = k-1 ; col >= 0 ; col-- ) {
|
||||
if (indxr[col] <0 || indxr[col] >= k)
|
||||
fprintf(stderr, "AARGH, indxr[col] %d\n", indxr[col]);
|
||||
else if (indxc[col] <0 || indxc[col] >= k)
|
||||
fprintf(stderr, "AARGH, indxc[col] %d\n", indxc[col]);
|
||||
else
|
||||
if (indxr[col] != indxc[col] ) {
|
||||
for (row = 0 ; row < k ; row++ )
|
||||
SWAP( src[row*k + indxr[col]], src[row*k + indxc[col]], gf);
|
||||
}
|
||||
}
|
||||
error = 0;
|
||||
|
||||
fail:
|
||||
return error ;
|
||||
}
|
||||
|
||||
/*
|
||||
* Not check for input params
|
||||
* */
|
||||
static gf* sub_matrix(gf* matrix, int rmin, int cmin, int rmax, int cmax, int nrows, int ncols) {
|
||||
(void)nrows;
|
||||
int i, j, ptr = 0;
|
||||
gf* new_m = (gf*) malloc((rmax-rmin) * (cmax-cmin));
|
||||
if (NULL != new_m) {
|
||||
for (i = rmin; i < rmax; i++) {
|
||||
for (j = cmin; j < cmax; j++) {
|
||||
new_m[ptr++] = matrix[i*ncols + j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new_m;
|
||||
}
|
||||
|
||||
/* copy from golang rs version */
|
||||
static inline int code_some_shards(gf* matrixRows, gf** inputs, gf** outputs, int dataShards, int outputCount, int byteCount) {
|
||||
gf* in;
|
||||
int iRow, c;
|
||||
for (c = 0; c < dataShards; c++) {
|
||||
in = inputs[c];
|
||||
for (iRow = 0; iRow < outputCount; iRow++) {
|
||||
if (0 == c)
|
||||
mul(outputs[iRow], in, matrixRows[iRow*dataShards+c], byteCount);
|
||||
else
|
||||
addmul(outputs[iRow], in, matrixRows[iRow*dataShards+c], byteCount);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void reed_solomon_init(void) {
|
||||
generate_gf();
|
||||
init_mul_table();
|
||||
}
|
||||
|
||||
reed_solomon* reed_solomon_new(int data_shards, int parity_shards) {
|
||||
gf* vm = NULL;
|
||||
gf* top = NULL;
|
||||
int err = 0;
|
||||
reed_solomon* rs = NULL;
|
||||
|
||||
do {
|
||||
rs = (reed_solomon *)malloc(sizeof(reed_solomon));
|
||||
if (NULL == rs)
|
||||
return NULL;
|
||||
|
||||
rs->data_shards = data_shards;
|
||||
rs->parity_shards = parity_shards;
|
||||
rs->shards = (data_shards + parity_shards);
|
||||
rs->m = NULL;
|
||||
rs->parity = NULL;
|
||||
|
||||
if (rs->shards > DATA_SHARDS_MAX || data_shards <= 0 || parity_shards <= 0) {
|
||||
err = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
vm = (gf*)malloc(data_shards * rs->shards);
|
||||
|
||||
if (NULL == vm) {
|
||||
err = 2;
|
||||
break;
|
||||
}
|
||||
|
||||
int ptr = 0;
|
||||
for (int row = 0; row < rs->shards; row++) {
|
||||
for (int col = 0; col < data_shards; col++)
|
||||
vm[ptr++] = row == col ? 1 : 0;
|
||||
}
|
||||
|
||||
top = sub_matrix(vm, 0, 0, data_shards, data_shards, rs->shards, data_shards);
|
||||
if (NULL == top) {
|
||||
err = 3;
|
||||
break;
|
||||
}
|
||||
|
||||
err = invert_mat(top, data_shards);
|
||||
assert(0 == err);
|
||||
|
||||
rs->m = multiply1(vm, rs->shards, data_shards, top, data_shards, data_shards);
|
||||
if (NULL == rs->m) {
|
||||
err = 4;
|
||||
break;
|
||||
}
|
||||
|
||||
for (int j = 0; j < parity_shards; j++) {
|
||||
for (int i = 0; i < data_shards; i++)
|
||||
rs->m[(data_shards + j)*data_shards + i] = inverse[(parity_shards + i) ^ j];
|
||||
}
|
||||
|
||||
rs->parity = sub_matrix(rs->m, data_shards, 0, rs->shards, data_shards, rs->shards, data_shards);
|
||||
if (NULL == rs->parity) {
|
||||
err = 5;
|
||||
break;
|
||||
}
|
||||
|
||||
free(vm);
|
||||
free(top);
|
||||
vm = NULL;
|
||||
top = NULL;
|
||||
return rs;
|
||||
|
||||
} while(0);
|
||||
|
||||
fprintf(stderr, "err=%d\n", err);
|
||||
if (NULL != vm)
|
||||
free(vm);
|
||||
|
||||
if (NULL != top)
|
||||
free(top);
|
||||
|
||||
if (NULL != rs) {
|
||||
if (NULL != rs->m)
|
||||
free(rs->m);
|
||||
|
||||
if (NULL != rs->parity)
|
||||
free(rs->parity);
|
||||
|
||||
free(rs);
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void reed_solomon_release(reed_solomon* rs) {
|
||||
if (NULL != rs) {
|
||||
if (NULL != rs->m)
|
||||
free(rs->m);
|
||||
|
||||
if (NULL != rs->parity)
|
||||
free(rs->parity);
|
||||
|
||||
free(rs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* decode one shard
|
||||
* input:
|
||||
* rs
|
||||
* gf[DATA_SHARDS_MAX*DATA_SHARDS_MAX] array for temporary data
|
||||
* original data_blocks[rs->data_shards][block_size]
|
||||
* dec_fec_blocks[nr_fec_blocks][block_size]
|
||||
* fec_block_nos: fec pos number in original fec_blocks
|
||||
* erased_blocks: erased blocks in original data_blocks
|
||||
* nr_fec_blocks: the number of erased blocks
|
||||
* */
|
||||
static int reed_solomon_decode(reed_solomon* rs, gf *dataDecodeMatrix, unsigned char **data_blocks, int block_size, unsigned char **dec_fec_blocks, unsigned int *fec_block_nos, unsigned int *erased_blocks, int nr_fec_blocks) {
|
||||
unsigned char* subShards[DATA_SHARDS_MAX];
|
||||
unsigned char* outputs[DATA_SHARDS_MAX];
|
||||
gf* m = rs->m;
|
||||
int i, j, c, swap, subMatrixRow, dataShards;
|
||||
|
||||
/* the erased_blocks should always sorted
|
||||
* if sorted, nr_fec_blocks times to check it
|
||||
* if not, sort it here
|
||||
* */
|
||||
for (i = 0; i < nr_fec_blocks; i++) {
|
||||
swap = 0;
|
||||
for (j = i+1; j < nr_fec_blocks; j++) {
|
||||
if (erased_blocks[i] > erased_blocks[j]) {
|
||||
/* the prefix is bigger than the following, swap */
|
||||
c = erased_blocks[i];
|
||||
erased_blocks[i] = erased_blocks[j];
|
||||
erased_blocks[j] = c;
|
||||
|
||||
swap = 1;
|
||||
}
|
||||
}
|
||||
if (!swap)
|
||||
break;
|
||||
}
|
||||
|
||||
j = 0;
|
||||
subMatrixRow = 0;
|
||||
dataShards = rs->data_shards;
|
||||
for (i = 0; i < dataShards; i++) {
|
||||
if (j < nr_fec_blocks && i == (int)erased_blocks[j])
|
||||
j++;
|
||||
else {
|
||||
/* this row is ok */
|
||||
for (c = 0; c < dataShards; c++)
|
||||
dataDecodeMatrix[subMatrixRow*dataShards + c] = m[i*dataShards + c];
|
||||
|
||||
subShards[subMatrixRow] = data_blocks[i];
|
||||
subMatrixRow++;
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < nr_fec_blocks && subMatrixRow < dataShards; i++) {
|
||||
subShards[subMatrixRow] = dec_fec_blocks[i];
|
||||
j = dataShards + fec_block_nos[i];
|
||||
for (c = 0; c < dataShards; c++)
|
||||
dataDecodeMatrix[subMatrixRow*dataShards + c] = m[j*dataShards + c];
|
||||
|
||||
subMatrixRow++;
|
||||
}
|
||||
|
||||
if (subMatrixRow < dataShards)
|
||||
return -1;
|
||||
|
||||
invert_mat(dataDecodeMatrix, dataShards);
|
||||
|
||||
for (i = 0; i < nr_fec_blocks; i++) {
|
||||
j = erased_blocks[i];
|
||||
outputs[i] = data_blocks[j];
|
||||
memmove(dataDecodeMatrix+i*dataShards, dataDecodeMatrix+j*dataShards, dataShards);
|
||||
}
|
||||
|
||||
return code_some_shards(dataDecodeMatrix, subShards, outputs, dataShards, nr_fec_blocks, block_size);
|
||||
}
|
||||
|
||||
/**
|
||||
* encode a big size of buffer
|
||||
* input:
|
||||
* rs
|
||||
* nr_shards: assert(0 == nr_shards % rs->shards)
|
||||
* shards[nr_shards][block_size]
|
||||
* */
|
||||
int reed_solomon_encode(reed_solomon* rs, unsigned char** shards, int nr_shards, int block_size) {
|
||||
unsigned char** data_blocks;
|
||||
unsigned char** fec_blocks;
|
||||
int i, ds = rs->data_shards, ps = rs->parity_shards, ss = rs->shards;
|
||||
i = nr_shards / ss;
|
||||
data_blocks = shards;
|
||||
fec_blocks = &shards[(i*ds)];
|
||||
|
||||
for (i = 0; i < nr_shards; i += ss) {
|
||||
code_some_shards(rs->parity, data_blocks, fec_blocks, rs->data_shards, rs->parity_shards, block_size);
|
||||
data_blocks += ds;
|
||||
fec_blocks += ps;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* reconstruct a big size of buffer
|
||||
* input:
|
||||
* rs
|
||||
* nr_shards: assert(0 == nr_shards % rs->data_shards)
|
||||
* shards[nr_shards][block_size]
|
||||
* marks[nr_shards] marks as errors
|
||||
* */
|
||||
int reed_solomon_reconstruct(reed_solomon* rs, unsigned char** shards, unsigned char* marks, int nr_shards, int block_size) {
|
||||
unsigned char *dec_fec_blocks[DATA_SHARDS_MAX];
|
||||
unsigned int fec_block_nos[DATA_SHARDS_MAX];
|
||||
unsigned int erased_blocks[DATA_SHARDS_MAX];
|
||||
unsigned char* fec_marks;
|
||||
unsigned char **data_blocks, **fec_blocks;
|
||||
gf * dataDecodeMatrix = malloc(DATA_SHARDS_MAX*DATA_SHARDS_MAX * sizeof(gf));
|
||||
int i, j, dn, pn, n;
|
||||
int ds = rs->data_shards;
|
||||
int ps = rs->parity_shards;
|
||||
int err = 0;
|
||||
|
||||
data_blocks = shards;
|
||||
n = nr_shards / rs->shards;
|
||||
fec_marks = marks + n*ds; //after all data, is't fec marks
|
||||
fec_blocks = shards + n*ds;
|
||||
|
||||
for (j = 0; j < n; j++) {
|
||||
dn = 0;
|
||||
for (i = 0; i < ds; i++) {
|
||||
if (marks[i])
|
||||
erased_blocks[dn++] = i;
|
||||
}
|
||||
if (dn > 0) {
|
||||
pn = 0;
|
||||
for (i = 0; i < ps && pn < dn; i++) {
|
||||
if (!fec_marks[i]) {
|
||||
//got valid fec row
|
||||
fec_block_nos[pn] = i;
|
||||
dec_fec_blocks[pn] = fec_blocks[i];
|
||||
pn++;
|
||||
}
|
||||
}
|
||||
|
||||
if (dn == pn) {
|
||||
reed_solomon_decode(rs, dataDecodeMatrix, data_blocks, block_size, dec_fec_blocks, fec_block_nos, erased_blocks, dn);
|
||||
} else
|
||||
err = -1;
|
||||
}
|
||||
data_blocks += ds;
|
||||
marks += ds;
|
||||
fec_blocks += ps;
|
||||
fec_marks += ps;
|
||||
}
|
||||
|
||||
return err;
|
||||
}
|
||||
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
#ifndef __RS_H_
|
||||
#define __RS_H_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* use small value to save memory */
|
||||
#define DATA_SHARDS_MAX 2048
|
||||
|
||||
typedef struct _reed_solomon {
|
||||
int data_shards;
|
||||
int parity_shards;
|
||||
int shards;
|
||||
unsigned char* m;
|
||||
unsigned char* parity;
|
||||
} reed_solomon;
|
||||
|
||||
/**
|
||||
* MUST initial one time
|
||||
* */
|
||||
void reed_solomon_init(void);
|
||||
|
||||
reed_solomon* reed_solomon_new(int data_shards, int parity_shards);
|
||||
void reed_solomon_release(reed_solomon* rs);
|
||||
|
||||
/**
|
||||
* encode a big size of buffer
|
||||
* input:
|
||||
* rs
|
||||
* nr_shards: assert(0 == nr_shards % rs->data_shards)
|
||||
* shards[nr_shards][block_size]
|
||||
* */
|
||||
int reed_solomon_encode(reed_solomon* rs, unsigned char** shards, int nr_shards, int block_size);
|
||||
|
||||
/**
|
||||
* reconstruct a big size of buffer
|
||||
* input:
|
||||
* rs
|
||||
* nr_shards: assert(0 == nr_shards % rs->data_shards)
|
||||
* shards[nr_shards][block_size]
|
||||
* marks[nr_shards] marks as errors
|
||||
* */
|
||||
int reed_solomon_reconstruct(reed_solomon* rs, unsigned char** shards, unsigned char* marks, int nr_shards, int block_size);
|
||||
|
||||
#ifdef __cplusplus
|
||||
};
|
||||
#endif
|
||||
#endif
|
||||
|
||||
Vendored
+9984
File diff suppressed because it is too large
Load Diff
+116
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* 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 "application.h"
|
||||
#include "scenes/lobby.h"
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#include "spdlog/sinks/android_sink.h"
|
||||
#include <android/native_window.h>
|
||||
#include <android_native_app_glue.h>
|
||||
#else
|
||||
#include "spdlog/sinks/stdout_color_sinks.h"
|
||||
#endif
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
void real_main(android_app * native_app)
|
||||
#else
|
||||
void real_main()
|
||||
#endif
|
||||
{
|
||||
try
|
||||
{
|
||||
application_info info;
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
info.native_app = native_app;
|
||||
#endif
|
||||
info.name = "WiVRn";
|
||||
info.version = VK_MAKE_VERSION(1, 0, 0);
|
||||
application app(info);
|
||||
|
||||
app.push_scene<scenes::lobby>();
|
||||
|
||||
app.run();
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::error("Caught exception: \"{}\"", e.what());
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
spdlog::error("Caught unknown exception");
|
||||
}
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
ANativeActivity_finish(native_app->activity);
|
||||
|
||||
// Read all pending events.
|
||||
while (!native_app->destroyRequested)
|
||||
{
|
||||
int events;
|
||||
struct android_poll_source * source;
|
||||
|
||||
while (ALooper_pollAll(-1, nullptr, &events, (void **)&source) >= 0)
|
||||
{
|
||||
// Process this event.
|
||||
if (source != nullptr)
|
||||
source->process(native_app, source);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
void android_main(android_app * native_app) __attribute__((visibility("default")));
|
||||
void android_main(android_app * native_app)
|
||||
{
|
||||
spdlog::set_default_logger(spdlog::android_logger_mt("WiVRn", "WiVRn"));
|
||||
|
||||
real_main(native_app);
|
||||
}
|
||||
#else
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
spdlog::set_default_logger(spdlog::stdout_color_mt("WiVRn"));
|
||||
|
||||
char * loglevel = getenv("WIVRN_LOGLEVEL");
|
||||
if (loglevel)
|
||||
{
|
||||
if (!strcasecmp(loglevel, "trace"))
|
||||
spdlog::set_level(spdlog::level::trace);
|
||||
else if (!strcasecmp(loglevel, "debug"))
|
||||
spdlog::set_level(spdlog::level::debug);
|
||||
else if (!strcasecmp(loglevel, "info"))
|
||||
spdlog::set_level(spdlog::level::info);
|
||||
else if (!strcasecmp(loglevel, "warning"))
|
||||
spdlog::set_level(spdlog::level::warn);
|
||||
else if (!strcasecmp(loglevel, "error"))
|
||||
spdlog::set_level(spdlog::level::err);
|
||||
else if (!strcasecmp(loglevel, "critical"))
|
||||
spdlog::set_level(spdlog::level::critical);
|
||||
else if (!strcasecmp(loglevel, "off"))
|
||||
spdlog::set_level(spdlog::level::off);
|
||||
else
|
||||
spdlog::warn("Invalid value for WIVRN_LOGLEVEL environment variable");
|
||||
}
|
||||
|
||||
real_main();
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,799 @@
|
||||
/*
|
||||
* 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 "scene_renderer.h"
|
||||
#include "application.h"
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "utils/strings.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
VkFormat gltf_to_vkformat(int component, int bits, int pixel_type, bool srgb)
|
||||
{
|
||||
switch (pixel_type)
|
||||
{
|
||||
case TINYGLTF_COMPONENT_TYPE_BYTE:
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
|
||||
assert(bits == 8);
|
||||
break;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_SHORT:
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
|
||||
assert(bits == 32);
|
||||
break;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_INT:
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
|
||||
case TINYGLTF_COMPONENT_TYPE_FLOAT:
|
||||
assert(bits == 32);
|
||||
break;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_DOUBLE:
|
||||
assert(bits == 64);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
switch (component)
|
||||
{
|
||||
case 1:
|
||||
switch (pixel_type)
|
||||
{
|
||||
case TINYGLTF_COMPONENT_TYPE_BYTE:
|
||||
return VK_FORMAT_R8_SNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
|
||||
return srgb ? VK_FORMAT_R8_SRGB : VK_FORMAT_R8_UNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_SHORT:
|
||||
return VK_FORMAT_R16_SNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
|
||||
return VK_FORMAT_R16_UNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_INT:
|
||||
return VK_FORMAT_R32_SINT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
|
||||
return VK_FORMAT_R32_UINT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_FLOAT:
|
||||
return VK_FORMAT_R32_SFLOAT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_DOUBLE:
|
||||
return VK_FORMAT_R64_SFLOAT;
|
||||
|
||||
default:
|
||||
return VK_FORMAT_UNDEFINED;
|
||||
}
|
||||
case 2:
|
||||
switch (pixel_type)
|
||||
{
|
||||
case TINYGLTF_COMPONENT_TYPE_BYTE:
|
||||
return VK_FORMAT_R8G8_SNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
|
||||
return srgb ? VK_FORMAT_R8G8_SRGB : VK_FORMAT_R8G8_UNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_SHORT:
|
||||
return VK_FORMAT_R16G16_SNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
|
||||
return VK_FORMAT_R16G16_UNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_INT:
|
||||
return VK_FORMAT_R32G32_SINT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
|
||||
return VK_FORMAT_R32G32_UINT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_FLOAT:
|
||||
return VK_FORMAT_R32G32_SFLOAT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_DOUBLE:
|
||||
return VK_FORMAT_R64G64_SFLOAT;
|
||||
|
||||
default:
|
||||
return VK_FORMAT_UNDEFINED;
|
||||
}
|
||||
case 3:
|
||||
switch (pixel_type)
|
||||
{
|
||||
case TINYGLTF_COMPONENT_TYPE_BYTE:
|
||||
return VK_FORMAT_R8G8B8_SNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
|
||||
return srgb ? VK_FORMAT_R8G8B8_SRGB : VK_FORMAT_R8G8B8_UNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_SHORT:
|
||||
return VK_FORMAT_R16G16B16_SNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
|
||||
return VK_FORMAT_R16G16B16_UNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_INT:
|
||||
return VK_FORMAT_R32G32B32_SINT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
|
||||
return VK_FORMAT_R32G32B32_UINT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_FLOAT:
|
||||
return VK_FORMAT_R32G32B32_SFLOAT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_DOUBLE:
|
||||
return VK_FORMAT_R64G64B64_SFLOAT;
|
||||
|
||||
default:
|
||||
return VK_FORMAT_UNDEFINED;
|
||||
}
|
||||
case 4:
|
||||
switch (pixel_type)
|
||||
{
|
||||
case TINYGLTF_COMPONENT_TYPE_BYTE:
|
||||
return VK_FORMAT_R8G8B8A8_SNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
|
||||
return srgb ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_SHORT:
|
||||
return VK_FORMAT_R16G16B16A16_SNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
|
||||
return VK_FORMAT_R16G16B16A16_UNORM;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_INT:
|
||||
return VK_FORMAT_R32G32B32A32_SINT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
|
||||
return VK_FORMAT_R32G32B32A32_UINT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_FLOAT:
|
||||
return VK_FORMAT_R32G32B32A32_SFLOAT;
|
||||
|
||||
case TINYGLTF_COMPONENT_TYPE_DOUBLE:
|
||||
return VK_FORMAT_R64G64B64A64_SFLOAT;
|
||||
|
||||
default:
|
||||
return VK_FORMAT_UNDEFINED;
|
||||
}
|
||||
default:
|
||||
return VK_FORMAT_UNDEFINED;
|
||||
}
|
||||
}
|
||||
|
||||
int bytes_per_pixel(VkFormat format)
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case VK_FORMAT_R8_SINT:
|
||||
case VK_FORMAT_R8_UINT:
|
||||
case VK_FORMAT_R8_SNORM:
|
||||
case VK_FORMAT_R8_UNORM:
|
||||
case VK_FORMAT_R8_SSCALED:
|
||||
case VK_FORMAT_R8_USCALED:
|
||||
case VK_FORMAT_R8_SRGB:
|
||||
return 1;
|
||||
|
||||
case VK_FORMAT_R16_SINT:
|
||||
case VK_FORMAT_R16_UINT:
|
||||
case VK_FORMAT_R16_SNORM:
|
||||
case VK_FORMAT_R16_UNORM:
|
||||
case VK_FORMAT_R16_SSCALED:
|
||||
case VK_FORMAT_R16_USCALED:
|
||||
return 2;
|
||||
|
||||
case VK_FORMAT_R32_SINT:
|
||||
case VK_FORMAT_R32_UINT:
|
||||
case VK_FORMAT_R32_SFLOAT:
|
||||
return 4;
|
||||
|
||||
case VK_FORMAT_R64_SFLOAT:
|
||||
return 8;
|
||||
|
||||
case VK_FORMAT_R8G8_SINT:
|
||||
case VK_FORMAT_R8G8_UINT:
|
||||
case VK_FORMAT_R8G8_SNORM:
|
||||
case VK_FORMAT_R8G8_UNORM:
|
||||
case VK_FORMAT_R8G8_SSCALED:
|
||||
case VK_FORMAT_R8G8_USCALED:
|
||||
case VK_FORMAT_R8G8_SRGB:
|
||||
return 2;
|
||||
|
||||
case VK_FORMAT_R16G16_SINT:
|
||||
case VK_FORMAT_R16G16_UINT:
|
||||
case VK_FORMAT_R16G16_SNORM:
|
||||
case VK_FORMAT_R16G16_UNORM:
|
||||
case VK_FORMAT_R16G16_SSCALED:
|
||||
case VK_FORMAT_R16G16_USCALED:
|
||||
return 4;
|
||||
|
||||
case VK_FORMAT_R32G32_SINT:
|
||||
case VK_FORMAT_R32G32_UINT:
|
||||
case VK_FORMAT_R32G32_SFLOAT:
|
||||
return 8;
|
||||
|
||||
case VK_FORMAT_R64G64_SFLOAT:
|
||||
return 16;
|
||||
|
||||
case VK_FORMAT_R8G8B8_SINT:
|
||||
case VK_FORMAT_R8G8B8_UINT:
|
||||
case VK_FORMAT_R8G8B8_SNORM:
|
||||
case VK_FORMAT_R8G8B8_UNORM:
|
||||
case VK_FORMAT_R8G8B8_SSCALED:
|
||||
case VK_FORMAT_R8G8B8_USCALED:
|
||||
case VK_FORMAT_R8G8B8_SRGB:
|
||||
return 3;
|
||||
|
||||
case VK_FORMAT_R16G16B16_SINT:
|
||||
case VK_FORMAT_R16G16B16_UINT:
|
||||
case VK_FORMAT_R16G16B16_SNORM:
|
||||
case VK_FORMAT_R16G16B16_UNORM:
|
||||
case VK_FORMAT_R16G16B16_SSCALED:
|
||||
case VK_FORMAT_R16G16B16_USCALED:
|
||||
return 6;
|
||||
|
||||
case VK_FORMAT_R32G32B32_SINT:
|
||||
case VK_FORMAT_R32G32B32_UINT:
|
||||
case VK_FORMAT_R32G32B32_SFLOAT:
|
||||
return 12;
|
||||
|
||||
case VK_FORMAT_R64G64B64_SFLOAT:
|
||||
return 24;
|
||||
|
||||
case VK_FORMAT_R8G8B8A8_SINT:
|
||||
case VK_FORMAT_R8G8B8A8_UINT:
|
||||
case VK_FORMAT_R8G8B8A8_SNORM:
|
||||
case VK_FORMAT_R8G8B8A8_UNORM:
|
||||
case VK_FORMAT_R8G8B8A8_SSCALED:
|
||||
case VK_FORMAT_R8G8B8A8_USCALED:
|
||||
case VK_FORMAT_R8G8B8A8_SRGB:
|
||||
return 4;
|
||||
|
||||
case VK_FORMAT_R16G16B16A16_SINT:
|
||||
case VK_FORMAT_R16G16B16A16_UINT:
|
||||
case VK_FORMAT_R16G16B16A16_SNORM:
|
||||
case VK_FORMAT_R16G16B16A16_UNORM:
|
||||
case VK_FORMAT_R16G16B16A16_SSCALED:
|
||||
case VK_FORMAT_R16G16B16A16_USCALED:
|
||||
return 8;
|
||||
|
||||
case VK_FORMAT_R32G32B32A32_SINT:
|
||||
case VK_FORMAT_R32G32B32A32_UINT:
|
||||
case VK_FORMAT_R32G32B32A32_SFLOAT:
|
||||
return 16;
|
||||
|
||||
case VK_FORMAT_R64G64B64A64_SFLOAT:
|
||||
return 32;
|
||||
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
scene_renderer::scene_renderer(VkDevice device, VkPhysicalDevice physical_device, VkQueue queue) :
|
||||
device(device), physical_device(physical_device), queue(queue)
|
||||
{
|
||||
try
|
||||
{
|
||||
vkGetPhysicalDeviceProperties(physical_device, &physical_device_properties);
|
||||
|
||||
command_pool = vk::command_pool(device, application::queue_family_index());
|
||||
|
||||
VkFenceCreateInfo fence_info{
|
||||
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
|
||||
};
|
||||
CHECK_VK(vkCreateFence(device, &fence_info, nullptr, &staging_fence));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
if (device && staging_fence)
|
||||
vkDestroyFence(device, staging_fence, nullptr);
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
scene_renderer::~scene_renderer()
|
||||
{
|
||||
if (device && staging_fence)
|
||||
vkDestroyFence(device, staging_fence, nullptr);
|
||||
}
|
||||
|
||||
void scene_renderer::reserve(size_t size)
|
||||
{
|
||||
if (size > staging_buffer_size)
|
||||
{
|
||||
VkBufferCreateInfo buffer_info{};
|
||||
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
buffer_info.size = size;
|
||||
buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
|
||||
|
||||
staging_buffer = vk::buffer(device, buffer_info);
|
||||
staging_memory = vk::device_memory(device, physical_device, staging_buffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
staging_buffer_size = size;
|
||||
staging_memory.map_memory();
|
||||
}
|
||||
}
|
||||
|
||||
void scene_renderer::load_buffer(VkBuffer b, const void * data, size_t size)
|
||||
{
|
||||
reserve(size);
|
||||
|
||||
memcpy(staging_memory.data(), data, size);
|
||||
|
||||
VkCommandBuffer staging_command_buffer = command_pool.allocate_command_buffer();
|
||||
try
|
||||
{
|
||||
CHECK_VK(vkResetCommandBuffer(staging_command_buffer, 0));
|
||||
VkCommandBufferBeginInfo begin_info{};
|
||||
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
||||
CHECK_VK(vkBeginCommandBuffer(staging_command_buffer, &begin_info));
|
||||
|
||||
VkBufferCopy copy_info{
|
||||
.srcOffset = 0,
|
||||
.dstOffset = 0,
|
||||
.size = size};
|
||||
vkCmdCopyBuffer(staging_command_buffer, staging_buffer, b, 1, ©_info);
|
||||
|
||||
CHECK_VK(vkEndCommandBuffer(staging_command_buffer));
|
||||
|
||||
VkSubmitInfo submit_info{};
|
||||
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
submit_info.commandBufferCount = 1;
|
||||
submit_info.pCommandBuffers = &staging_command_buffer;
|
||||
CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, staging_fence));
|
||||
|
||||
CHECK_VK(vkWaitForFences(device, 1, &staging_fence, VK_TRUE, -1));
|
||||
CHECK_VK(vkResetFences(device, 1, &staging_fence));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
command_pool.free_command_buffer(staging_command_buffer);
|
||||
throw;
|
||||
}
|
||||
|
||||
command_pool.free_command_buffer(staging_command_buffer);
|
||||
}
|
||||
|
||||
void scene_renderer::load_image(VkImage i, void * data, VkExtent2D size, VkFormat format, uint32_t mipmap_count, VkImageLayout final_layout)
|
||||
{
|
||||
reserve(size.height * size.width * bytes_per_pixel(format));
|
||||
|
||||
VkCommandBuffer staging_command_buffer = command_pool.allocate_command_buffer();
|
||||
|
||||
try
|
||||
{
|
||||
CHECK_VK(vkResetCommandBuffer(staging_command_buffer, 0));
|
||||
VkCommandBufferBeginInfo begin_info{};
|
||||
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
||||
CHECK_VK(vkBeginCommandBuffer(staging_command_buffer, &begin_info));
|
||||
|
||||
VkImageMemoryBarrier barrier{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.srcAccessMask = 0,
|
||||
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
|
||||
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = i,
|
||||
.subresourceRange = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = mipmap_count,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
};
|
||||
vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
|
||||
|
||||
VkBufferImageCopy copy_info{
|
||||
.bufferOffset = 0,
|
||||
.bufferRowLength = 0,
|
||||
.bufferImageHeight = 0,
|
||||
.imageSubresource = VkImageSubresourceLayers{
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.mipLevel = 0,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
.imageOffset = {0, 0, 0},
|
||||
.imageExtent = {size.width, size.height, 1}};
|
||||
vkCmdCopyBufferToImage(staging_command_buffer, staging_buffer, i, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_info);
|
||||
|
||||
VkOffset3D size_src = {(int32_t)size.width, (int32_t)size.height, 1};
|
||||
for (uint32_t mipmap = 1; mipmap < mipmap_count; mipmap++)
|
||||
{
|
||||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||||
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
||||
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||||
barrier.subresourceRange.baseMipLevel = mipmap - 1;
|
||||
barrier.subresourceRange.levelCount = 1;
|
||||
vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
|
||||
|
||||
VkOffset3D size_dst = {std::max(1, size_src.x / 2), std::max(1, size_src.y / 2), 1};
|
||||
VkImageBlit blit_info{
|
||||
.srcSubresource = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.mipLevel = mipmap - 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
.srcOffsets = {{0, 0, 0}, size_src},
|
||||
.dstSubresource = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.mipLevel = mipmap,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
.dstOffsets = {{0, 0, 0}, size_dst},
|
||||
};
|
||||
vkCmdBlitImage(staging_command_buffer, i, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, i, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit_info, VK_FILTER_LINEAR);
|
||||
|
||||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||||
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
|
||||
barrier.newLayout = final_layout;
|
||||
barrier.subresourceRange.baseMipLevel = mipmap - 1;
|
||||
vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
|
||||
|
||||
size_src = size_dst;
|
||||
}
|
||||
|
||||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
|
||||
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
||||
barrier.newLayout = final_layout;
|
||||
barrier.subresourceRange.baseMipLevel = mipmap_count - 1;
|
||||
vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
|
||||
|
||||
CHECK_VK(vkEndCommandBuffer(staging_command_buffer));
|
||||
|
||||
VkSubmitInfo submit_info{};
|
||||
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
submit_info.commandBufferCount = 1;
|
||||
submit_info.pCommandBuffers = &staging_command_buffer;
|
||||
CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, staging_fence));
|
||||
|
||||
CHECK_VK(vkWaitForFences(device, 1, &staging_fence, VK_TRUE, -1));
|
||||
CHECK_VK(vkResetFences(device, 1, &staging_fence));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
command_pool.free_command_buffer(staging_command_buffer);
|
||||
throw;
|
||||
}
|
||||
|
||||
command_pool.free_command_buffer(staging_command_buffer);
|
||||
}
|
||||
|
||||
void scene_renderer::cleanup()
|
||||
{
|
||||
for (auto & i: shaders)
|
||||
cleanup_shader(*i);
|
||||
shaders.clear();
|
||||
|
||||
for (auto & i: images)
|
||||
cleanup_image(*i);
|
||||
images.clear();
|
||||
|
||||
for (auto & i: buffers)
|
||||
cleanup_buffer(*i);
|
||||
buffers.clear();
|
||||
|
||||
cleanup_output_images();
|
||||
}
|
||||
|
||||
void scene_renderer::cleanup_output_images()
|
||||
{
|
||||
output_images.clear();
|
||||
|
||||
for (VkImageView image_view: output_image_views)
|
||||
vkDestroyImageView(device, image_view, nullptr);
|
||||
output_image_views.clear();
|
||||
|
||||
for (VkFramebuffer framebuffer: output_framebuffers)
|
||||
vkDestroyFramebuffer(device, framebuffer, nullptr);
|
||||
output_framebuffers.clear();
|
||||
}
|
||||
|
||||
void scene_renderer::set_output_images(std::vector<VkImage> output_images_, VkExtent2D output_size_, VkFormat output_format_)
|
||||
{
|
||||
output_images = std::move(output_images_);
|
||||
output_size = output_size_;
|
||||
output_format = output_format_;
|
||||
|
||||
// Create renderpass
|
||||
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
|
||||
|
||||
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{
|
||||
.format = output_format,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
|
||||
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
}},
|
||||
.subpasses = {VkSubpassDescription{
|
||||
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||||
.colorAttachmentCount = 1,
|
||||
.pColorAttachments = &color_ref,
|
||||
}},
|
||||
.dependencies = {}};
|
||||
|
||||
renderpass = vk::renderpass(device, renderpass_info);
|
||||
|
||||
// Create image views and framebuffers
|
||||
output_image_views.reserve(output_images.size());
|
||||
output_framebuffers.reserve(output_images.size());
|
||||
for (VkImage image: output_images)
|
||||
{
|
||||
VkImageViewCreateInfo iv_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
|
||||
.image = image,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D,
|
||||
.format = output_format,
|
||||
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
|
||||
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1}};
|
||||
|
||||
VkImageView image_view;
|
||||
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &image_view));
|
||||
output_image_views.push_back(image_view);
|
||||
|
||||
VkFramebufferCreateInfo fb_create_info{
|
||||
.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
|
||||
.renderPass = renderpass,
|
||||
.attachmentCount = 1,
|
||||
.pAttachments = &image_view,
|
||||
.width = output_size.width,
|
||||
.height = output_size.height,
|
||||
.layers = 1,
|
||||
};
|
||||
|
||||
VkFramebuffer framebuffer;
|
||||
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &framebuffer));
|
||||
output_framebuffers.push_back(framebuffer);
|
||||
}
|
||||
}
|
||||
|
||||
void scene_renderer::cleanup_shader(shader & s)
|
||||
{
|
||||
for (auto & i: s.descriptor_pools)
|
||||
vkDestroyDescriptorPool(device, i, nullptr);
|
||||
|
||||
if (s.pipeline)
|
||||
vkDestroyPipeline(device, s.pipeline, nullptr);
|
||||
if (s.pipeline_layout)
|
||||
vkDestroyPipelineLayout(device, s.pipeline_layout, nullptr);
|
||||
if (s.descriptor_set_layout)
|
||||
vkDestroyDescriptorSetLayout(device, s.descriptor_set_layout, nullptr);
|
||||
|
||||
s.descriptor_pools.clear();
|
||||
s.pipeline = VK_NULL_HANDLE;
|
||||
s.pipeline_layout = VK_NULL_HANDLE;
|
||||
s.descriptor_set_layout = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
scene_renderer::shader * scene_renderer::create_shader(std::string name, VkPrimitiveTopology topology, std::vector<VkDescriptorSetLayoutBinding> uniform_bindings, std::vector<VkVertexInputBindingDescription> vertex_bindings, std::vector<VkVertexInputAttributeDescription> vertex_attributes)
|
||||
{
|
||||
auto s = std::make_unique<shader>();
|
||||
|
||||
try
|
||||
{
|
||||
// Create graphics pipeline
|
||||
s->vertex_shader = vk::shader(device, name + ".vert").release();
|
||||
s->fragment_shader = vk::shader(device, name + ".frag").release();
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo layout_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.bindingCount = (uint32_t)uniform_bindings.size(),
|
||||
.pBindings = uniform_bindings.data(),
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &s->descriptor_set_layout));
|
||||
|
||||
VkPipelineLayoutCreateInfo pipeline_layout_create_info{
|
||||
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
|
||||
.setLayoutCount = 1,
|
||||
.pSetLayouts = &s->descriptor_set_layout,
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &s->pipeline_layout));
|
||||
|
||||
VkPipelineColorBlendAttachmentState pcbas{.colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
|
||||
VK_COLOR_COMPONENT_G_BIT |
|
||||
VK_COLOR_COMPONENT_B_BIT};
|
||||
|
||||
vk::pipeline::graphics_info pipeline_info{
|
||||
.shader_stages =
|
||||
{{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = s->vertex_shader, .pName = "main"},
|
||||
{.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = s->fragment_shader, .pName = "main"}},
|
||||
.vertex_input_bindings = vertex_bindings,
|
||||
.vertex_input_attributes = vertex_attributes,
|
||||
.InputAssemblyState = {.topology = topology},
|
||||
.viewports = {VkViewport{.x = 0,
|
||||
.y = 0,
|
||||
.width = (float)output_size.width,
|
||||
.height = (float)output_size.height,
|
||||
.minDepth = 0,
|
||||
.maxDepth = 1}},
|
||||
.scissors = {VkRect2D{
|
||||
.offset = {0, 0},
|
||||
.extent = output_size,
|
||||
}},
|
||||
.RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1},
|
||||
.MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT},
|
||||
.ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas},
|
||||
.dynamic_states = {},
|
||||
.renderPass = renderpass,
|
||||
.subpass = 0,
|
||||
};
|
||||
|
||||
s->pipeline = vk::pipeline(device, pipeline_info, s->pipeline_layout).release();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
cleanup_shader(*s);
|
||||
throw;
|
||||
}
|
||||
|
||||
return shaders.emplace_back(std::move(s)).get();
|
||||
}
|
||||
|
||||
void scene_renderer::cleanup_image(scene_renderer::image & i)
|
||||
{
|
||||
if (i.image)
|
||||
vkDestroyImage(device, i.image, nullptr);
|
||||
|
||||
if (i.memory)
|
||||
vkFreeMemory(device, i.memory, nullptr);
|
||||
|
||||
i.image = VK_NULL_HANDLE;
|
||||
i.memory = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
scene_renderer::image * scene_renderer::create_image(void * data, VkExtent2D size, VkFormat format)
|
||||
{
|
||||
auto i = std::make_unique<image>();
|
||||
|
||||
try
|
||||
{
|
||||
uint32_t mipmaps = std::log2(std::max(size.width, size.height)) + 1;
|
||||
|
||||
VkImageCreateInfo image_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
|
||||
.flags = 0,
|
||||
.imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = format,
|
||||
.extent = {size.width, size.height, 1},
|
||||
.mipLevels = mipmaps,
|
||||
.arrayLayers = 1,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
};
|
||||
|
||||
i->image = vk::image(device, image_info).release();
|
||||
i->memory = vk::device_memory(device, physical_device, i->image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release();
|
||||
|
||||
load_image(i->image, data, size, format, mipmaps);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
cleanup_image(*i);
|
||||
throw;
|
||||
}
|
||||
|
||||
return images.emplace_back(std::move(i)).get();
|
||||
}
|
||||
|
||||
void scene_renderer::cleanup_buffer(scene_renderer::buffer & b)
|
||||
{
|
||||
if (b.buffer)
|
||||
vkDestroyBuffer(device, b.buffer, nullptr);
|
||||
if (b.memory)
|
||||
vkFreeMemory(device, b.memory, nullptr);
|
||||
|
||||
b.buffer = VK_NULL_HANDLE;
|
||||
b.memory = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
scene_renderer::buffer * scene_renderer::create_buffer(const void * data, size_t size, VkBufferUsageFlags usage)
|
||||
{
|
||||
auto b = std::make_unique<buffer>();
|
||||
|
||||
try
|
||||
{
|
||||
VkBufferCreateInfo buffer_info{
|
||||
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
|
||||
.size = size,
|
||||
.usage = usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
};
|
||||
|
||||
b->buffer = vk::buffer(device, buffer_info).release();
|
||||
b->memory = vk::device_memory(device, physical_device, b->buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release();
|
||||
|
||||
load_buffer(b->buffer, data, size);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
cleanup_buffer(*b);
|
||||
throw;
|
||||
}
|
||||
|
||||
return buffers.emplace_back(std::move(b)).get();
|
||||
}
|
||||
|
||||
scene_renderer::model * scene_renderer::load_gltf(const std::string & filename)
|
||||
{
|
||||
std::string err, warn;
|
||||
|
||||
auto m = std::make_unique<model>();
|
||||
|
||||
bool success = false;
|
||||
|
||||
if (filename.ends_with(".glb"))
|
||||
success = gltf_loader.LoadBinaryFromFile(&m->gltf_model, &err, &warn, filename);
|
||||
else if (filename.ends_with(".gltf"))
|
||||
success = gltf_loader.LoadASCIIFromFile(&m->gltf_model, &err, &warn, filename);
|
||||
else
|
||||
err = "Wrong file extension, must be .gltf or .glb";
|
||||
|
||||
if (warn != "")
|
||||
spdlog::warn("Loading {}: {}", filename, utils::trim(warn));
|
||||
|
||||
if (err != "")
|
||||
spdlog::error("Loading {}: {}", filename, utils::trim(err));
|
||||
|
||||
if (!success)
|
||||
throw std::runtime_error("GLTF error: " + utils::trim(err));
|
||||
|
||||
for (tinygltf::Buffer & i: m->gltf_model.buffers)
|
||||
{
|
||||
m->buffers.push_back(create_buffer(i.data, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT));
|
||||
}
|
||||
|
||||
std::vector<bool> srgb(m->gltf_model.images.size(), false);
|
||||
for (tinygltf::Material & i: m->gltf_model.materials)
|
||||
{
|
||||
if (i.emissiveTexture.index >= 0 && i.emissiveTexture.index < (int)srgb.size())
|
||||
srgb[i.emissiveTexture.index] = true;
|
||||
|
||||
if (i.pbrMetallicRoughness.baseColorTexture.index >= 0 && i.pbrMetallicRoughness.baseColorTexture.index < (int)srgb.size())
|
||||
srgb[i.pbrMetallicRoughness.baseColorTexture.index] = true;
|
||||
}
|
||||
|
||||
int n = 0;
|
||||
for (tinygltf::Image & i: m->gltf_model.images)
|
||||
{
|
||||
VkFormat format = gltf_to_vkformat(i.component, i.bits, i.pixel_type, srgb[n++]);
|
||||
m->images.push_back(create_image(i.image.data(), {(uint32_t)i.width, (uint32_t)i.height}, format));
|
||||
}
|
||||
|
||||
return models.emplace_back(std::move(m)).get();
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* 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 <memory>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#include "tiny_gltf.h"
|
||||
#include "vk/buffer.h"
|
||||
#include "vk/command_pool.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/image.h"
|
||||
#include "vk/pipeline.h"
|
||||
#include "vk/renderpass.h"
|
||||
|
||||
class scene_renderer
|
||||
{
|
||||
public:
|
||||
class shader
|
||||
{
|
||||
friend class scene_renderer;
|
||||
|
||||
VkDescriptorSetLayout descriptor_set_layout{};
|
||||
std::vector<VkDescriptorPool> descriptor_pools;
|
||||
VkPipelineLayout pipeline_layout{};
|
||||
VkPipeline pipeline{};
|
||||
VkShaderModule vertex_shader;
|
||||
VkShaderModule fragment_shader;
|
||||
};
|
||||
|
||||
class image
|
||||
{
|
||||
friend class scene_renderer;
|
||||
|
||||
VkDeviceMemory memory{};
|
||||
VkSampler sampler{};
|
||||
VkImage image{};
|
||||
VkImageView image_view{};
|
||||
VkDescriptorSet descriptor_set{};
|
||||
};
|
||||
|
||||
class buffer
|
||||
{
|
||||
friend class scene_renderer;
|
||||
|
||||
VkDeviceMemory memory{};
|
||||
VkBuffer buffer{};
|
||||
};
|
||||
|
||||
struct mesh_primitive
|
||||
{
|
||||
shader * s;
|
||||
};
|
||||
|
||||
class model
|
||||
{
|
||||
friend class scene_renderer;
|
||||
|
||||
tinygltf::Model gltf_model;
|
||||
std::vector<image *> images;
|
||||
std::vector<buffer *> buffers;
|
||||
};
|
||||
|
||||
class model_instance
|
||||
{
|
||||
friend class scene_renderer;
|
||||
|
||||
model * gltf_model;
|
||||
|
||||
void * ubo;
|
||||
};
|
||||
|
||||
private:
|
||||
VkDevice device;
|
||||
VkPhysicalDevice physical_device;
|
||||
VkPhysicalDeviceProperties physical_device_properties;
|
||||
VkQueue queue;
|
||||
vk::command_pool command_pool;
|
||||
|
||||
tinygltf::TinyGLTF gltf_loader;
|
||||
|
||||
// Staging buffer
|
||||
size_t staging_buffer_size = 0;
|
||||
vk::buffer staging_buffer;
|
||||
vk::device_memory staging_memory;
|
||||
VkFence staging_fence{};
|
||||
void reserve(size_t size);
|
||||
|
||||
void load_buffer(VkBuffer b, const void * data, size_t size);
|
||||
|
||||
template <typename T>
|
||||
void load_buffer(VkBuffer b, std::span<T> data)
|
||||
{
|
||||
load_buffer(b, data.data(), data.size() * sizeof(T));
|
||||
}
|
||||
|
||||
void load_image(VkImage i, void * data, VkExtent2D size, VkFormat format, uint32_t mipmap_count, VkImageLayout final_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
|
||||
|
||||
// Scene data
|
||||
std::vector<std::unique_ptr<shader>> shaders;
|
||||
std::vector<std::unique_ptr<image>> images;
|
||||
std::vector<std::unique_ptr<buffer>> buffers;
|
||||
std::vector<std::unique_ptr<mesh_primitive>> primitives;
|
||||
std::vector<std::unique_ptr<model>> models;
|
||||
std::vector<model_instance> instances;
|
||||
|
||||
// Destination images
|
||||
std::vector<VkImage> output_images;
|
||||
std::vector<VkImageView> output_image_views;
|
||||
std::vector<VkFramebuffer> output_framebuffers;
|
||||
VkExtent2D output_size{};
|
||||
VkFormat output_format{};
|
||||
|
||||
// Render pass
|
||||
vk::renderpass renderpass;
|
||||
|
||||
void cleanup();
|
||||
void cleanup_output_images();
|
||||
void cleanup_shader(shader &);
|
||||
void cleanup_buffer(buffer &);
|
||||
void cleanup_image(image &);
|
||||
|
||||
public:
|
||||
scene_renderer(VkDevice device, VkPhysicalDevice physical_device, VkQueue queue);
|
||||
~scene_renderer();
|
||||
scene_renderer(const scene_renderer &) = delete;
|
||||
scene_renderer(scene_renderer &&) = delete;
|
||||
|
||||
void set_output_images(std::vector<VkImage> output_images, VkExtent2D output_size, VkFormat output_format);
|
||||
|
||||
shader * create_shader(std::string name, VkPrimitiveTopology topology, std::vector<VkDescriptorSetLayoutBinding> uniform_bindings, std::vector<VkVertexInputBindingDescription> vertex_bindings, std::vector<VkVertexInputAttributeDescription> vertex_attributes);
|
||||
|
||||
image * create_image(void * data, VkExtent2D size, VkFormat format);
|
||||
|
||||
buffer * create_buffer(const void * data, size_t size, VkBufferUsageFlags usage);
|
||||
|
||||
template <typename T>
|
||||
// requires(std::contiguous_iterator<typename T::iterator>)
|
||||
buffer * create_buffer(const T & data,
|
||||
VkBufferUsageFlags usage)
|
||||
{
|
||||
return create_buffer(data.data(), data.size() * sizeof(T), usage);
|
||||
}
|
||||
|
||||
model * load_gltf(const std::string & filename);
|
||||
};
|
||||
@@ -0,0 +1,367 @@
|
||||
/*
|
||||
* 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 "text_rasterizer.h"
|
||||
#include <cassert>
|
||||
#include <limits>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
#include <hb-ft.h>
|
||||
#include <hb.h>
|
||||
|
||||
#include "utils/check.h"
|
||||
#include "vk/buffer.h"
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#include <android/font.h>
|
||||
#include <android/font_matcher.h>
|
||||
#include <android/system_fonts.h>
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
struct : std::error_category
|
||||
{
|
||||
const char * name() const noexcept override
|
||||
{
|
||||
return "freetype";
|
||||
}
|
||||
|
||||
std::string message(int condition) const override
|
||||
{
|
||||
return FT_Error_String(condition);
|
||||
}
|
||||
} error_category;
|
||||
} // namespace
|
||||
|
||||
std::error_category & freetype_error_category()
|
||||
{
|
||||
return error_category;
|
||||
}
|
||||
|
||||
// namespace {
|
||||
// const hb_tag_t KernTag = HB_TAG('k', 'e', 'r', 'n'); // kerning operations
|
||||
// const hb_tag_t LigaTag = HB_TAG('l', 'i', 'g', 'a'); // standard ligature substitution
|
||||
// const hb_tag_t CligTag = HB_TAG('c', 'l', 'i', 'g'); // contextual ligature substitution
|
||||
//
|
||||
// static hb_feature_t LigatureOff = { LigaTag, 0, 0, std::numeric_limits<unsigned int>::max() };
|
||||
// static hb_feature_t LigatureOn = { LigaTag, 1, 0, std::numeric_limits<unsigned int>::max() };
|
||||
// static hb_feature_t KerningOff = { KernTag, 0, 0, std::numeric_limits<unsigned int>::max() };
|
||||
// static hb_feature_t KerningOn = { KernTag, 1, 0, std::numeric_limits<unsigned int>::max() };
|
||||
// static hb_feature_t CligOff = { CligTag, 0, 0, std::numeric_limits<unsigned int>::max() };
|
||||
// static hb_feature_t CligOn = { CligTag, 1, 0, std::numeric_limits<unsigned int>::max() };
|
||||
// }
|
||||
|
||||
text_rasterizer::text_rasterizer(VkDevice device, VkPhysicalDevice physical_device, VkCommandPool command_pool, VkQueue queue) :
|
||||
device(device), physical_device(physical_device), command_pool(command_pool), queue(queue)
|
||||
{
|
||||
std::string font_filename;
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
{
|
||||
std::u16string ws = u"hello";
|
||||
AFontMatcher * font_matcher = AFontMatcher_create();
|
||||
|
||||
AFontMatcher_setFamilyVariant(font_matcher, AFAMILY_VARIANT_DEFAULT);
|
||||
AFontMatcher_setLocales(font_matcher, "fr-FR,en-GB");
|
||||
AFontMatcher_setStyle(font_matcher, AFONT_WEIGHT_NORMAL, false);
|
||||
|
||||
AFont * font = AFontMatcher_match(font_matcher, "sans-serif", (uint16_t *)ws.c_str(), ws.size(), nullptr);
|
||||
|
||||
font_filename = AFont_getFontFilePath(font);
|
||||
|
||||
AFont_close(font);
|
||||
AFontMatcher_destroy(font_matcher);
|
||||
}
|
||||
#else
|
||||
font_filename = "/usr/share/fonts/TTF/DejaVuSans.ttf";
|
||||
#endif
|
||||
try
|
||||
{
|
||||
FT_Error err = FT_Init_FreeType(&freetype);
|
||||
if (err)
|
||||
throw std::system_error(err, error_category);
|
||||
|
||||
err = FT_New_Face(freetype, font_filename.c_str(), 0, &face);
|
||||
if (err)
|
||||
throw std::system_error(err, error_category);
|
||||
|
||||
err = FT_Set_Char_Size(face, 0, 200 * 64, 72, 72);
|
||||
if (err)
|
||||
throw std::system_error(err, error_category);
|
||||
|
||||
font = hb_ft_font_create(face, nullptr);
|
||||
|
||||
buffer = hb_buffer_create();
|
||||
|
||||
if (!hb_buffer_allocation_successful(buffer))
|
||||
throw std::runtime_error("hb_buffer_allocation_successful returned false");
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
if (buffer)
|
||||
hb_buffer_destroy(buffer);
|
||||
|
||||
if (font)
|
||||
hb_font_destroy(font);
|
||||
|
||||
if (freetype)
|
||||
FT_Done_FreeType(freetype);
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
VkFenceCreateInfo fence_info{.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
|
||||
CHECK_VK(vkCreateFence(device, &fence_info, nullptr, &fence));
|
||||
}
|
||||
|
||||
text_rasterizer::~text_rasterizer()
|
||||
{
|
||||
if (device && fence)
|
||||
vkDestroyFence(device, fence, nullptr);
|
||||
|
||||
hb_buffer_destroy(buffer);
|
||||
hb_font_destroy(font);
|
||||
FT_Done_FreeType(freetype);
|
||||
}
|
||||
|
||||
text text_rasterizer::render(std::string_view s)
|
||||
{
|
||||
hb_buffer_reset(buffer);
|
||||
|
||||
hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);
|
||||
hb_buffer_set_script(buffer, HB_SCRIPT_LATIN);
|
||||
hb_buffer_set_language(buffer, hb_language_from_string(s.data(), s.size()));
|
||||
|
||||
hb_buffer_add_utf8(buffer, s.data(), s.size(), 0, s.size());
|
||||
|
||||
// std::vector<hb_feature_t> features;
|
||||
// hb_shape(font, buffer, features.data(), features.size());
|
||||
|
||||
hb_shape(font, buffer, nullptr, 0);
|
||||
|
||||
unsigned int glyphCount;
|
||||
hb_glyph_info_t * glyphInfo = hb_buffer_get_glyph_infos(buffer, &glyphCount);
|
||||
hb_glyph_position_t * glyphPos = hb_buffer_get_glyph_positions(buffer, &glyphCount);
|
||||
|
||||
int x_min = std::numeric_limits<int>::max();
|
||||
int x_max = std::numeric_limits<int>::min();
|
||||
int y_min = std::numeric_limits<int>::max();
|
||||
int y_max = std::numeric_limits<int>::min();
|
||||
|
||||
FT_Int32 flags = FT_LOAD_DEFAULT;
|
||||
|
||||
std::vector<uint8_t> rendered_text;
|
||||
|
||||
for (int pass = 0; pass < 2; pass++)
|
||||
{
|
||||
FT_F26Dot6 x = 0;
|
||||
FT_F26Dot6 y = 0;
|
||||
for (size_t i = 0; i < glyphCount; ++i)
|
||||
{
|
||||
FT_Error err = FT_Load_Glyph(face, glyphInfo[i].codepoint, flags);
|
||||
if (err)
|
||||
throw std::system_error(err, error_category);
|
||||
|
||||
err = FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
|
||||
if (err)
|
||||
throw std::system_error(err, error_category);
|
||||
|
||||
FT_GlyphSlot slot = face->glyph;
|
||||
FT_Bitmap bitmap = face->glyph->bitmap;
|
||||
|
||||
int x0 = (x + glyphPos[i].x_offset) / 64 + slot->bitmap_left;
|
||||
int y0 = (y + glyphPos[i].y_offset) / 64 + slot->bitmap_top;
|
||||
int x1 = x0 + bitmap.width;
|
||||
int y1 = y0 - bitmap.rows;
|
||||
|
||||
assert(x1 >= x0);
|
||||
assert(y1 <= y0);
|
||||
|
||||
switch (pass)
|
||||
{
|
||||
case 0:
|
||||
x_min = std::min(x_min, x0);
|
||||
x_max = std::max(x_max, x1);
|
||||
y_min = std::min(y_min, y1);
|
||||
y_max = std::max(y_max, y0);
|
||||
break;
|
||||
|
||||
case 1: {
|
||||
uint8_t * src = bitmap.buffer;
|
||||
for (unsigned int iy = 0; iy < bitmap.rows; iy++)
|
||||
{
|
||||
uint8_t * dst = rendered_text.data() +
|
||||
(y_max - y0 + iy) * (x_max - x_min) + (x0 - x_min);
|
||||
|
||||
for (unsigned int ix = 0; ix < bitmap.width; ix++)
|
||||
{
|
||||
*dst = std::max(*dst, *src);
|
||||
dst++;
|
||||
src++;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
x += glyphPos[i].x_advance;
|
||||
y += glyphPos[i].y_advance;
|
||||
}
|
||||
|
||||
if (pass == 0)
|
||||
{
|
||||
assert(x_max > x_min);
|
||||
assert(y_max > y_min);
|
||||
rendered_text.resize((x_max - x_min) * (y_max - y_min), 0);
|
||||
}
|
||||
}
|
||||
#ifdef TEST
|
||||
return {.bitmap = std::move(rendered_text),
|
||||
.size = {
|
||||
.width = uint32_t(x_max - x_min),
|
||||
.height = uint32_t(y_max - y_min),
|
||||
}};
|
||||
#else
|
||||
|
||||
VkImageCreateInfo image_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
|
||||
.imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = text::format,
|
||||
.extent = {
|
||||
.width = uint32_t(x_max - x_min),
|
||||
.height = uint32_t(y_max - y_min),
|
||||
.depth = 1},
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 1,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
vk::image image(device, image_info);
|
||||
vk::device_memory memory(device, physical_device, image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
|
||||
VkBufferCreateInfo buffer_info{
|
||||
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
|
||||
.size = rendered_text.size(),
|
||||
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
};
|
||||
vk::buffer staging_buffer(device, buffer_info);
|
||||
vk::device_memory staging_memory(device, physical_device, staging_buffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
staging_memory.map_memory();
|
||||
memcpy(staging_memory.data(), rendered_text.data(), rendered_text.size());
|
||||
|
||||
VkCommandBufferAllocateInfo cmdbufinfo{
|
||||
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
|
||||
.commandPool = command_pool,
|
||||
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
|
||||
.commandBufferCount = 1,
|
||||
};
|
||||
VkCommandBuffer cmdbuf;
|
||||
CHECK_VK(vkAllocateCommandBuffers(device, &cmdbufinfo, &cmdbuf));
|
||||
|
||||
VkCommandBufferBeginInfo cmdbufbegininfo{
|
||||
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
};
|
||||
vkBeginCommandBuffer(cmdbuf, &cmdbufbegininfo);
|
||||
|
||||
VkImageMemoryBarrier barrier{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.srcAccessMask = 0,
|
||||
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
|
||||
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = image,
|
||||
.subresourceRange =
|
||||
{
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
};
|
||||
vkCmdPipelineBarrier(cmdbuf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
|
||||
|
||||
VkBufferImageCopy copy_info{.bufferOffset = 0,
|
||||
.bufferRowLength = 0,
|
||||
.bufferImageHeight = 0,
|
||||
.imageSubresource =
|
||||
VkImageSubresourceLayers{
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.mipLevel = 0,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
.imageOffset = {0, 0, 0},
|
||||
.imageExtent = image_info.extent};
|
||||
|
||||
vkCmdCopyBufferToImage(cmdbuf, staging_buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_info);
|
||||
|
||||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
|
||||
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
|
||||
barrier.newLayout = text::layout;
|
||||
barrier.subresourceRange.baseMipLevel = 0;
|
||||
vkCmdPipelineBarrier(cmdbuf, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
|
||||
|
||||
CHECK_VK(vkEndCommandBuffer(cmdbuf));
|
||||
|
||||
VkSubmitInfo submit_info{};
|
||||
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
submit_info.commandBufferCount = 1;
|
||||
submit_info.pCommandBuffers = &cmdbuf;
|
||||
CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, fence));
|
||||
|
||||
CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, -1));
|
||||
CHECK_VK(vkResetFences(device, 1, &fence));
|
||||
|
||||
return {
|
||||
.image = std::move(image),
|
||||
.memory = std::move(memory),
|
||||
.size = {image_info.extent.width, image_info.extent.height}};
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef TEST
|
||||
#include <fstream>
|
||||
|
||||
int main(int argc, char ** argv)
|
||||
{
|
||||
std::string s;
|
||||
for (int i = 1; i < argc; i++)
|
||||
{
|
||||
s = s + argv[i];
|
||||
}
|
||||
|
||||
text_renderer r(VK_NULL_HANDLE, VK_NULL_HANDLE);
|
||||
|
||||
auto text = r.render(s);
|
||||
|
||||
std::ofstream f("text.pgm");
|
||||
|
||||
f << "P5 " << text.size.width << " " << text.size.height << " 255 ";
|
||||
f.write((char *)text.bitmap.data(), text.bitmap.size());
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* 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
|
||||
|
||||
#ifndef TEST
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/image.h"
|
||||
#endif
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#include <freetype/freetype.h>
|
||||
#include <ft2build.h>
|
||||
#include <hb.h>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
struct text
|
||||
{
|
||||
#ifndef TEST
|
||||
static inline const VkFormat format = VK_FORMAT_R8_UNORM;
|
||||
static inline const VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||||
static inline const VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL;
|
||||
vk::image image;
|
||||
vk::device_memory memory;
|
||||
#else
|
||||
std::vector<uint8_t> bitmap;
|
||||
#endif
|
||||
|
||||
VkExtent2D size;
|
||||
};
|
||||
|
||||
class text_rasterizer
|
||||
{
|
||||
VkDevice device{};
|
||||
VkPhysicalDevice physical_device{};
|
||||
VkCommandPool command_pool{};
|
||||
VkQueue queue{};
|
||||
VkFence fence{};
|
||||
|
||||
FT_Library freetype{};
|
||||
FT_Face face{};
|
||||
|
||||
hb_font_t * font{};
|
||||
hb_buffer_t * buffer{};
|
||||
|
||||
public:
|
||||
text_rasterizer(VkDevice device, VkPhysicalDevice physical_device, VkCommandPool command_pool, VkQueue queue);
|
||||
~text_rasterizer();
|
||||
|
||||
text render(std::string_view s);
|
||||
};
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* 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 "scene.h"
|
||||
#include "application.h"
|
||||
#include <cassert>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
scene::~scene() {}
|
||||
|
||||
scene::scene() :
|
||||
instance(application::instance_->xr_instance),
|
||||
session(application::instance_->xr_session),
|
||||
world_space(application::instance_->world_space),
|
||||
viewconfig(application::instance_->app_info.viewconfig),
|
||||
swapchains(application::instance_->xr_swapchains),
|
||||
|
||||
commandpool(application::instance_->vk_cmdpool)
|
||||
{
|
||||
vk_instance = application::instance_->vk_instance;
|
||||
device = application::instance_->vk_device;
|
||||
physical_device = application::instance_->vk_physical_device;
|
||||
queue = application::instance_->vk_queue;
|
||||
}
|
||||
|
||||
void scene::render()
|
||||
{
|
||||
XrFrameState framestate = session.wait_frame();
|
||||
session.begin_frame();
|
||||
std::vector<XrCompositionLayerBaseHeader *> layers_base;
|
||||
std::vector<XrCompositionLayerProjectionView> layer_view;
|
||||
XrCompositionLayerProjection layer{};
|
||||
|
||||
if (framestate.shouldRender)
|
||||
{
|
||||
auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space);
|
||||
|
||||
assert(views.size() == swapchains.size());
|
||||
|
||||
layer_view.resize(views.size());
|
||||
|
||||
before_render_view(flags, framestate.predictedDisplayTime);
|
||||
for (size_t swapchain_index = 0; swapchain_index < views.size(); swapchain_index++)
|
||||
{
|
||||
int image_index = swapchains[swapchain_index].acquire();
|
||||
swapchains[swapchain_index].wait();
|
||||
|
||||
render_view(flags, framestate.predictedDisplayTime, views[swapchain_index], swapchain_index, image_index);
|
||||
|
||||
swapchains[swapchain_index].release();
|
||||
|
||||
layer_view[swapchain_index].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
|
||||
layer_view[swapchain_index].pose = views[swapchain_index].pose;
|
||||
layer_view[swapchain_index].fov = views[swapchain_index].fov;
|
||||
layer_view[swapchain_index].subImage.swapchain = swapchains[swapchain_index];
|
||||
layer_view[swapchain_index].subImage.imageRect.offset = {0, 0};
|
||||
layer_view[swapchain_index].subImage.imageRect.extent.width =
|
||||
swapchains[swapchain_index].width();
|
||||
layer_view[swapchain_index].subImage.imageRect.extent.height =
|
||||
swapchains[swapchain_index].height();
|
||||
}
|
||||
|
||||
layer.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION;
|
||||
layer.space = world_space;
|
||||
layer.layerFlags = 0;
|
||||
layer.viewCount = layer_view.size();
|
||||
layer.views = layer_view.data();
|
||||
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
|
||||
}
|
||||
|
||||
session.end_frame(framestate.predictedDisplayTime, layers_base);
|
||||
}
|
||||
|
||||
void scene::before_render_view(XrViewStateFlags flags, XrTime predicted_display_time) {}
|
||||
|
||||
void scene::render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index)
|
||||
{}
|
||||
|
||||
void scene::on_unfocused() {}
|
||||
void scene::on_focused() {}
|
||||
|
||||
VkFence scene::create_fence(bool signaled)
|
||||
{
|
||||
// TODO: RAII
|
||||
VkFenceCreateInfo fence_info{};
|
||||
fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
|
||||
fence_info.flags = signaled ? VK_FENCE_CREATE_SIGNALED_BIT : 0;
|
||||
|
||||
VkFence fence;
|
||||
CHECK_VK(vkCreateFence(device, &fence_info, nullptr, &fence));
|
||||
|
||||
return fence;
|
||||
}
|
||||
|
||||
VkSemaphore scene::create_semaphore()
|
||||
{
|
||||
// TODO: RAII
|
||||
VkSemaphoreCreateInfo sem_info{};
|
||||
sem_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
|
||||
|
||||
VkSemaphore semaphore;
|
||||
CHECK_VK(vkCreateSemaphore(device, &sem_info, nullptr, &semaphore));
|
||||
|
||||
return semaphore;
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* 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 <cstdint>
|
||||
|
||||
#include "application.h"
|
||||
#include "xr/session.h"
|
||||
#include "xr/swapchain.h"
|
||||
|
||||
class scene
|
||||
{
|
||||
protected:
|
||||
xr::instance & instance;
|
||||
xr::session & session;
|
||||
xr::space & world_space;
|
||||
XrViewConfigurationType viewconfig;
|
||||
std::vector<xr::swapchain> & swapchains;
|
||||
|
||||
VkInstance vk_instance;
|
||||
VkDevice device;
|
||||
VkPhysicalDevice physical_device;
|
||||
VkQueue queue;
|
||||
vk::command_pool & commandpool;
|
||||
|
||||
VkFence create_fence(bool signaled = true);
|
||||
VkSemaphore create_semaphore();
|
||||
|
||||
public:
|
||||
scene();
|
||||
|
||||
virtual ~scene();
|
||||
virtual void before_render_view(XrViewStateFlags flags, XrTime predicted_display_time);
|
||||
virtual void render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index);
|
||||
|
||||
virtual void render();
|
||||
virtual void on_unfocused();
|
||||
virtual void on_focused();
|
||||
};
|
||||
@@ -0,0 +1,390 @@
|
||||
/*
|
||||
* 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 "lobby.h"
|
||||
#include "glm/glm.hpp"
|
||||
#include "render/text_rasterizer.h"
|
||||
#include "stream.h"
|
||||
#include "utils/ranges.h"
|
||||
#include "utils/strings.h"
|
||||
#include "vk/vk.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <glm/gtc/quaternion.hpp>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <tiny_gltf.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
|
||||
|
||||
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
|
||||
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
}},
|
||||
.subpasses = {VkSubpassDescription{
|
||||
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||||
.colorAttachmentCount = 1,
|
||||
.pColorAttachments = &color_ref,
|
||||
}},
|
||||
.dependencies = {}};
|
||||
} // namespace
|
||||
|
||||
scenes::lobby::~lobby() {}
|
||||
|
||||
scenes::lobby::lobby() :
|
||||
status_string_rasterizer(device, physical_device, commandpool, queue), renderer(device, physical_device, queue)
|
||||
{
|
||||
// renderer.load_gltf("Lobby.gltf");
|
||||
|
||||
uint32_t width = swapchains[0].width();
|
||||
uint32_t height = swapchains[0].height();
|
||||
|
||||
// Create renderpass
|
||||
renderpass_info.attachments[0].format = swapchains[0].format();
|
||||
renderpass = vk::renderpass(device, renderpass_info);
|
||||
|
||||
VkSamplerCreateInfo sampler_info{
|
||||
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
|
||||
.magFilter = VK_FILTER_LINEAR,
|
||||
.minFilter = VK_FILTER_LINEAR,
|
||||
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
|
||||
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.mipLodBias = 0.0f,
|
||||
.anisotropyEnable = VK_FALSE,
|
||||
.maxAnisotropy = 1,
|
||||
.compareEnable = VK_FALSE,
|
||||
.compareOp = VK_COMPARE_OP_NEVER,
|
||||
.minLod = 0.0f,
|
||||
.maxLod = 0.0f,
|
||||
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
|
||||
.unnormalizedCoordinates = VK_FALSE,
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateSampler(device, &sampler_info, nullptr, &status_string_sampler));
|
||||
|
||||
// Create VkDescriptorSetLayout
|
||||
VkDescriptorSetLayoutBinding layout_binding{
|
||||
.binding = 0,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
};
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo layout_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.bindingCount = 1,
|
||||
.pBindings = &layout_binding,
|
||||
};
|
||||
|
||||
CHECK_VK(
|
||||
vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &status_string_image_descriptor_set_layout));
|
||||
|
||||
VkDescriptorPoolSize status_string_image_descriptor_set_pool_size{
|
||||
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1,
|
||||
};
|
||||
|
||||
VkDescriptorPoolCreateInfo pool_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
|
||||
.flags = 0,
|
||||
.maxSets = 1,
|
||||
.poolSizeCount = 1,
|
||||
.pPoolSizes = &status_string_image_descriptor_set_pool_size,
|
||||
};
|
||||
CHECK_VK(vkCreateDescriptorPool(device, &pool_info, nullptr, &status_string_descriptor_pool));
|
||||
|
||||
VkDescriptorSetAllocateInfo ds_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
|
||||
.descriptorPool = status_string_descriptor_pool,
|
||||
.descriptorSetCount = 1,
|
||||
.pSetLayouts = &status_string_image_descriptor_set_layout,
|
||||
};
|
||||
CHECK_VK(vkAllocateDescriptorSets(device, &ds_info, &status_string_image_descriptor_set));
|
||||
|
||||
// Create graphics pipeline
|
||||
vk::shader vertex_shader(device, "text.vert");
|
||||
vk::shader fragment_shader(device, "text.frag");
|
||||
|
||||
vk::pipeline::graphics_info pipeline_info;
|
||||
|
||||
pipeline_info.shader_stages.resize(2);
|
||||
|
||||
pipeline_info.shader_stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
|
||||
pipeline_info.shader_stages[0].module = vertex_shader;
|
||||
pipeline_info.shader_stages[0].pName = "main";
|
||||
|
||||
pipeline_info.shader_stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||||
pipeline_info.shader_stages[1].module = fragment_shader;
|
||||
pipeline_info.shader_stages[1].pName = "main";
|
||||
|
||||
pipeline_info.InputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||||
|
||||
pipeline_info.viewports.push_back(VkViewport{0, 0, (float)width, (float)height, 0.0f, 1.0f});
|
||||
|
||||
pipeline_info.scissors.push_back(VkRect2D{{0, 0}, {width, height}});
|
||||
|
||||
pipeline_info.RasterizationState.polygonMode = VK_POLYGON_MODE_FILL;
|
||||
pipeline_info.RasterizationState.lineWidth = 1;
|
||||
|
||||
pipeline_info.MultisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
|
||||
|
||||
VkPipelineColorBlendAttachmentState pcbas{};
|
||||
pcbas.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT;
|
||||
|
||||
pipeline_info.ColorBlendState.attachmentCount = 1;
|
||||
pipeline_info.ColorBlendState.pAttachments = &pcbas;
|
||||
|
||||
pipeline_info.renderPass = renderpass;
|
||||
pipeline_info.subpass = 0;
|
||||
layout = vk::pipeline_layout(
|
||||
device, {.descriptor_set_layouts = {status_string_image_descriptor_set_layout}, .push_constant_ranges = {VkPushConstantRange{.stageFlags = VK_SHADER_STAGE_VERTEX_BIT, .offset = 0, .size = sizeof(glm::mat4)}}});
|
||||
pipeline = vk::pipeline(device, pipeline_info, layout);
|
||||
|
||||
images_data.resize(swapchains.size());
|
||||
for (size_t i = 0; i < swapchains.size(); i++)
|
||||
{
|
||||
auto & images = swapchains[i].images();
|
||||
images_data[i].resize(images.size());
|
||||
|
||||
for (size_t j = 0; j < images.size(); j++)
|
||||
{
|
||||
VkFramebufferCreateInfo fb_create_info{};
|
||||
fb_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
||||
fb_create_info.renderPass = renderpass;
|
||||
fb_create_info.attachmentCount = 1;
|
||||
fb_create_info.pAttachments = &images[j].view;
|
||||
fb_create_info.width = swapchains[i].width();
|
||||
fb_create_info.height = swapchains[i].height();
|
||||
fb_create_info.layers = 1;
|
||||
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &images_data[i][j].framebuffer));
|
||||
|
||||
images_data[i][j].render_finished = create_semaphore();
|
||||
}
|
||||
}
|
||||
|
||||
command_buffer = commandpool.allocate_command_buffer();
|
||||
fence = create_fence(false);
|
||||
}
|
||||
|
||||
void scenes::lobby::rasterize_status_string()
|
||||
{
|
||||
if (status_string_image_view)
|
||||
vkDestroyImageView(device, status_string_image_view, nullptr);
|
||||
|
||||
status_string_rasterized_text = status_string_rasterizer.render(status_string);
|
||||
|
||||
assert(status_string_rasterized_text.image != VK_NULL_HANDLE);
|
||||
assert(status_string_rasterized_text.memory != VK_NULL_HANDLE);
|
||||
|
||||
VkImageViewCreateInfo iv_info{.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
|
||||
.image = status_string_rasterized_text.image,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D,
|
||||
.format = status_string_rasterized_text.format,
|
||||
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
|
||||
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1}};
|
||||
|
||||
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &status_string_image_view));
|
||||
|
||||
VkDescriptorImageInfo image_info{
|
||||
.sampler = status_string_sampler,
|
||||
.imageView = status_string_image_view,
|
||||
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
};
|
||||
|
||||
VkWriteDescriptorSet descriptor_write{
|
||||
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
|
||||
.dstSet = status_string_image_descriptor_set,
|
||||
.dstBinding = 0,
|
||||
.dstArrayElement = 0,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.pImageInfo = &image_info,
|
||||
};
|
||||
|
||||
vkUpdateDescriptorSets(device, 1, &descriptor_write, 0, nullptr);
|
||||
|
||||
last_status_string = status_string;
|
||||
}
|
||||
|
||||
void scenes::lobby::render()
|
||||
{
|
||||
if (auto session = client.poll())
|
||||
{
|
||||
next_scene.reset();
|
||||
|
||||
next_scene = stream::create(std::move(session));
|
||||
}
|
||||
|
||||
if (next_scene && !next_scene->alive())
|
||||
next_scene.reset();
|
||||
|
||||
if (next_scene)
|
||||
{
|
||||
if (next_scene->ready())
|
||||
{
|
||||
application::push_scene(next_scene);
|
||||
next_scene.reset();
|
||||
}
|
||||
else
|
||||
{
|
||||
status_string = "Waiting for video stream";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
status_string = "Waiting for connection";
|
||||
}
|
||||
|
||||
if (status_string != last_status_string)
|
||||
rasterize_status_string();
|
||||
|
||||
XrFrameState framestate = session.wait_frame();
|
||||
|
||||
if (!framestate.shouldRender)
|
||||
{
|
||||
session.begin_frame();
|
||||
session.end_frame(framestate.predictedDisplayTime, {});
|
||||
return;
|
||||
}
|
||||
|
||||
session.begin_frame();
|
||||
|
||||
CHECK_VK(vkResetCommandBuffer(command_buffer, 0));
|
||||
|
||||
VkCommandBufferBeginInfo beginInfo{};
|
||||
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
||||
CHECK_VK(vkBeginCommandBuffer(command_buffer, &beginInfo));
|
||||
|
||||
auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space);
|
||||
assert(views.size() == swapchains.size());
|
||||
std::vector<XrCompositionLayerProjectionView> layer_view(views.size());
|
||||
|
||||
for (size_t swapchain_index = 0; swapchain_index < views.size(); swapchain_index++)
|
||||
{
|
||||
int image_index = swapchains[swapchain_index].acquire();
|
||||
swapchains[swapchain_index].wait();
|
||||
|
||||
render_view(flags, framestate.predictedDisplayTime, views[swapchain_index], swapchain_index, image_index);
|
||||
|
||||
swapchains[swapchain_index].release();
|
||||
|
||||
layer_view[swapchain_index].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
|
||||
layer_view[swapchain_index].pose = views[swapchain_index].pose;
|
||||
layer_view[swapchain_index].fov = views[swapchain_index].fov;
|
||||
layer_view[swapchain_index].subImage.swapchain = swapchains[swapchain_index];
|
||||
layer_view[swapchain_index].subImage.imageRect.offset = {0, 0};
|
||||
layer_view[swapchain_index].subImage.imageRect.extent.width = swapchains[swapchain_index].width();
|
||||
layer_view[swapchain_index].subImage.imageRect.extent.height = swapchains[swapchain_index].height();
|
||||
}
|
||||
|
||||
CHECK_VK(vkEndCommandBuffer(command_buffer));
|
||||
|
||||
VkSubmitInfo submitInfo{};
|
||||
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
submitInfo.commandBufferCount = 1;
|
||||
submitInfo.pCommandBuffers = &command_buffer;
|
||||
|
||||
CHECK_VK(vkQueueSubmit(queue, 1, &submitInfo, fence));
|
||||
|
||||
XrCompositionLayerProjection layer{
|
||||
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION,
|
||||
.layerFlags = 0,
|
||||
.space = world_space,
|
||||
.viewCount = (uint32_t)layer_view.size(),
|
||||
.views = layer_view.data(),
|
||||
};
|
||||
|
||||
std::vector<XrCompositionLayerBaseHeader *> layers_base;
|
||||
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
|
||||
|
||||
session.end_frame(framestate.predictedDisplayTime, layers_base);
|
||||
|
||||
CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX));
|
||||
CHECK_VK(vkResetFences(device, 1, &fence));
|
||||
}
|
||||
|
||||
void scenes::lobby::render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index)
|
||||
{
|
||||
xr::swapchain & swapchain = swapchains[swapchain_index];
|
||||
xr::swapchain::image & swapchain_image = swapchain.images()[image_index];
|
||||
image_data & data = images_data[swapchain_index][image_index];
|
||||
|
||||
VkClearValue clearColor = {{{0.0f, 0.0f, 0.0f, 1.0f}}};
|
||||
|
||||
VkRenderPassBeginInfo renderPassInfo{};
|
||||
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
||||
renderPassInfo.renderPass = renderpass;
|
||||
renderPassInfo.framebuffer = data.framebuffer;
|
||||
renderPassInfo.renderArea.offset = {0, 0};
|
||||
renderPassInfo.renderArea.extent = {swapchain.width(), swapchain.height()};
|
||||
renderPassInfo.clearValueCount = 1;
|
||||
renderPassInfo.pClearValues = &clearColor;
|
||||
|
||||
vkCmdBeginRenderPass(command_buffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
|
||||
|
||||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
|
||||
|
||||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &status_string_image_descriptor_set, 0, nullptr);
|
||||
|
||||
float zn = 0.1;
|
||||
float r = tan(view.fov.angleRight);
|
||||
float l = tan(view.fov.angleLeft);
|
||||
float t = tan(view.fov.angleUp);
|
||||
float b = tan(view.fov.angleDown);
|
||||
|
||||
// clang-format off
|
||||
glm::mat4 proj{
|
||||
{ 2/(r-l), 0, 0, 0 },
|
||||
{ 0, 2/(b-t), 0, 0 },
|
||||
{ (l+r)/(r-l), (t+b)/(b-t), -1, -1 },
|
||||
{ 0, 0, -2*zn, 0 }
|
||||
};
|
||||
// clang-format on
|
||||
|
||||
glm::mat4 view_matrix = glm::mat4_cast(glm::quat(view.pose.orientation.w, view.pose.orientation.x, view.pose.orientation.y, view.pose.orientation.z));
|
||||
|
||||
view_matrix = glm::translate(glm::mat4(1),
|
||||
glm::vec3(view.pose.position.x, view.pose.position.y, view.pose.position.z)) *
|
||||
view_matrix;
|
||||
|
||||
float aspect_ratio = (float)status_string_rasterized_text.size.width / (float)status_string_rasterized_text.size.height;
|
||||
glm::mat4 model_matrix{
|
||||
{aspect_ratio, 0, 0, 0},
|
||||
{0, 1, 0, 0},
|
||||
{0, 0, 1, 0},
|
||||
{-0.5 * aspect_ratio, -0.5, -10, 1}};
|
||||
|
||||
glm::mat4 mvp = proj * glm::inverse(view_matrix) * model_matrix;
|
||||
vkCmdPushConstants(command_buffer, layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(glm::mat4), &mvp);
|
||||
|
||||
vkCmdDraw(command_buffer, 6, 1, 0, 0);
|
||||
|
||||
vkCmdEndRenderPass(command_buffer);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* 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 "scene.h"
|
||||
#include "vk/buffer.h"
|
||||
#include "vk/image.h"
|
||||
#include "vk/renderpass.h"
|
||||
#include "wivrn_client.h"
|
||||
#include <tiny_gltf.h>
|
||||
|
||||
#include "render/scene_renderer.h"
|
||||
#include "render/text_rasterizer.h"
|
||||
|
||||
namespace scenes
|
||||
{
|
||||
class stream;
|
||||
|
||||
class lobby : public scene
|
||||
{
|
||||
std::string status_string;
|
||||
std::string last_status_string;
|
||||
VkSampler status_string_sampler{};
|
||||
text status_string_rasterized_text;
|
||||
VkImageView status_string_image_view{};
|
||||
VkDescriptorPool status_string_descriptor_pool{};
|
||||
VkDescriptorSetLayout status_string_image_descriptor_set_layout{};
|
||||
VkDescriptorSet status_string_image_descriptor_set{};
|
||||
text_rasterizer status_string_rasterizer;
|
||||
|
||||
vk::renderpass renderpass;
|
||||
vk::pipeline_layout layout;
|
||||
vk::pipeline pipeline;
|
||||
|
||||
VkFence fence{};
|
||||
VkCommandBuffer command_buffer{};
|
||||
|
||||
struct image_data
|
||||
{
|
||||
VkFramebuffer framebuffer{};
|
||||
VkSemaphore render_finished{};
|
||||
};
|
||||
|
||||
std::vector<std::vector<image_data>> images_data;
|
||||
|
||||
wivrn_client client;
|
||||
|
||||
tinygltf::Model model;
|
||||
std::vector<vk::device_memory> model_memory;
|
||||
std::vector<vk::buffer> model_buffers;
|
||||
std::vector<vk::image> model_images;
|
||||
|
||||
void load_model(const std::string & filename);
|
||||
|
||||
std::shared_ptr<stream> next_scene;
|
||||
|
||||
scene_renderer renderer;
|
||||
|
||||
void rasterize_status_string();
|
||||
|
||||
public:
|
||||
virtual ~lobby();
|
||||
lobby();
|
||||
|
||||
virtual void render() override;
|
||||
virtual void render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index) override;
|
||||
};
|
||||
} // namespace scenes
|
||||
@@ -0,0 +1,568 @@
|
||||
/*
|
||||
* 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 GLM_FORCE_RADIANS
|
||||
|
||||
#include "stream.h"
|
||||
|
||||
#include "application.h"
|
||||
#include "decoder/shard_accumulator.h"
|
||||
#include "external/magic_enum.hpp"
|
||||
#include "glm/fwd.hpp"
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "utils/check.h"
|
||||
#include "utils/ranges.h"
|
||||
#include "utils/sync_queue.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/image.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include "xr/details/enumerate.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
using namespace xrt::drivers::wivrn;
|
||||
|
||||
// clang-format off
|
||||
static const std::unordered_map<std::string, device_id> device_ids = {
|
||||
{"/user/hand/left/input/x/click", device_id::X_CLICK},
|
||||
{"/user/hand/left/input/x/touch", device_id::X_TOUCH},
|
||||
{"/user/hand/left/input/y/click", device_id::Y_CLICK},
|
||||
{"/user/hand/left/input/y/touch", device_id::Y_TOUCH},
|
||||
{"/user/hand/left/input/menu/click", device_id::MENU_CLICK},
|
||||
{"/user/hand/left/input/squeeze/value", device_id::LEFT_SQUEEZE_VALUE},
|
||||
{"/user/hand/left/input/trigger/value", device_id::LEFT_TRIGGER_VALUE},
|
||||
{"/user/hand/left/input/trigger/touch", device_id::LEFT_TRIGGER_TOUCH},
|
||||
{"/user/hand/left/input/thumbstick", device_id::LEFT_THUMBSTICK_X},
|
||||
{"/user/hand/left/input/thumbstick/click", device_id::LEFT_THUMBSTICK_CLICK},
|
||||
{"/user/hand/left/input/thumbstick/touch", device_id::LEFT_THUMBSTICK_TOUCH},
|
||||
{"/user/hand/left/input/thumbrest/touch", device_id::LEFT_THUMBREST_TOUCH},
|
||||
{"/user/hand/right/input/a/click", device_id::A_CLICK},
|
||||
{"/user/hand/right/input/a/touch", device_id::A_TOUCH},
|
||||
{"/user/hand/right/input/b/click", device_id::B_CLICK},
|
||||
{"/user/hand/right/input/b/touch", device_id::B_TOUCH},
|
||||
{"/user/hand/right/input/system/click", device_id::SYSTEM_CLICK},
|
||||
{"/user/hand/right/input/squeeze/value", device_id::RIGHT_SQUEEZE_VALUE},
|
||||
{"/user/hand/right/input/trigger/value", device_id::RIGHT_TRIGGER_VALUE},
|
||||
{"/user/hand/right/input/trigger/touch", device_id::RIGHT_TRIGGER_TOUCH},
|
||||
{"/user/hand/right/input/thumbstick", device_id::RIGHT_THUMBSTICK_X},
|
||||
{"/user/hand/right/input/thumbstick/click", device_id::RIGHT_THUMBSTICK_CLICK},
|
||||
{"/user/hand/right/input/thumbstick/touch", device_id::RIGHT_THUMBSTICK_TOUCH},
|
||||
{"/user/hand/right/input/thumbrest/touch", device_id::RIGHT_THUMBREST_TOUCH},
|
||||
};
|
||||
// clang-format on
|
||||
|
||||
std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_session> network_session)
|
||||
{
|
||||
std::shared_ptr<stream> self{new stream};
|
||||
|
||||
self->network_session = std::move(network_session);
|
||||
|
||||
from_headset::headset_info_packet info{};
|
||||
|
||||
info.recommended_eye_width = self->swapchains[0].width();
|
||||
info.recommended_eye_height = self->swapchains[0].height();
|
||||
|
||||
if (self->instance.has_extension(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME))
|
||||
{
|
||||
info.available_refresh_rates = self->session.get_refresh_rates();
|
||||
info.preferred_refresh_rate = self->session.get_current_refresh_rate();
|
||||
}
|
||||
|
||||
if (info.available_refresh_rates.empty())
|
||||
spdlog::warn("Unable to detect refresh rates");
|
||||
|
||||
self->network_session->send_control(info);
|
||||
|
||||
self->network_thread = std::thread(&stream::process_packets, self.get());
|
||||
pthread_setname_np(self->network_thread.native_handle(), "network_thread");
|
||||
|
||||
self->tracking_thread = std::thread(&stream::tracking, self.get());
|
||||
pthread_setname_np(self->tracking_thread.native_handle(), "tracking_thread");
|
||||
|
||||
self->video_thread = std::thread(&stream::video, self.get());
|
||||
pthread_setname_np(self->video_thread.native_handle(), "video_thread");
|
||||
|
||||
self->command_buffer = self->commandpool.allocate_command_buffer();
|
||||
self->fence = self->create_fence(false);
|
||||
|
||||
// Look up the XrActions for haptics
|
||||
self->haptics_actions[0].first = application::get_action("/user/hand/left/output/haptic").first;
|
||||
self->haptics_actions[0].second = application::string_to_path("/user/hand/left");
|
||||
|
||||
self->haptics_actions[1].first = application::get_action("/user/hand/right/output/haptic").first;
|
||||
self->haptics_actions[1].second = application::string_to_path("/user/hand/right");
|
||||
|
||||
// Look up the XrActions for input
|
||||
for (const auto & [action, action_type, name]: application::inputs())
|
||||
{
|
||||
auto it = device_ids.find(name);
|
||||
|
||||
if (it == device_ids.end())
|
||||
continue;
|
||||
|
||||
self->input_actions.emplace_back(it->second, action, action_type);
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
scenes::stream::~stream()
|
||||
{
|
||||
cleanup();
|
||||
exiting = true;
|
||||
shard_queue.close();
|
||||
|
||||
video_thread.join();
|
||||
tracking_thread.join();
|
||||
network_thread.join();
|
||||
}
|
||||
|
||||
void scenes::stream::push_blit_handle(shard_accumulator * decoder, std::shared_ptr<shard_accumulator::blit_handle> handle)
|
||||
{
|
||||
std::lock_guard lock(decoder_mutex);
|
||||
|
||||
if (!application::is_visible())
|
||||
return;
|
||||
|
||||
for (auto & i: decoders)
|
||||
{
|
||||
if (i.decoder.get() == decoder)
|
||||
{
|
||||
static_assert(std::tuple_size_v<decltype(i.latest_frames)> == 2);
|
||||
std::swap(i.latest_frames[0], i.latest_frames[1]);
|
||||
i.latest_frames[1] = handle;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!ready_ && std::all_of(decoders.begin(), decoders.end(), [](accumulator_images & i) {
|
||||
return i.latest_frames.back();
|
||||
}))
|
||||
{
|
||||
ready_ = true;
|
||||
first_frame_time = application::now();
|
||||
spdlog::info("Stream scene ready at t={}", first_frame_time);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<uint64_t> scenes::stream::accumulator_images::frames() const
|
||||
{
|
||||
std::vector<uint64_t> result;
|
||||
for (const auto & frame: latest_frames)
|
||||
{
|
||||
if (frame)
|
||||
result.push_back(frame->feedback.frame_index);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<uint64_t> scenes::stream::accumulator_images::common_frame(const std::vector<accumulator_images> & sets)
|
||||
{
|
||||
if (sets.empty())
|
||||
return {};
|
||||
auto common_frames = sets[0].frames();
|
||||
for (const auto & set: sets)
|
||||
{
|
||||
std::vector<uint64_t> tmp;
|
||||
auto x = set.frames();
|
||||
std::set_intersection(
|
||||
x.begin(), x.end(), common_frames.begin(), common_frames.end(), std::back_inserter(tmp));
|
||||
common_frames = tmp;
|
||||
if (common_frames.empty())
|
||||
return {};
|
||||
}
|
||||
assert(not common_frames.empty());
|
||||
return common_frames.back();
|
||||
}
|
||||
|
||||
std::shared_ptr<shard_accumulator::blit_handle> scenes::stream::accumulator_images::frame(std::optional<uint64_t> id)
|
||||
{
|
||||
for (auto it = latest_frames.rbegin(); it != latest_frames.rend(); ++it)
|
||||
{
|
||||
if (not *it)
|
||||
continue;
|
||||
if (id and (*it)->feedback.frame_index != *id)
|
||||
continue;
|
||||
return *it;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void scenes::stream::render()
|
||||
{
|
||||
if (exiting)
|
||||
application::pop_scene();
|
||||
|
||||
XrFrameState framestate = session.wait_frame();
|
||||
auto t0 = application::now();
|
||||
|
||||
if (decoders.empty())
|
||||
framestate.shouldRender = false;
|
||||
|
||||
if (!framestate.shouldRender)
|
||||
{
|
||||
// TODO: stop/restart video stream
|
||||
session.begin_frame();
|
||||
session.end_frame(framestate.predictedDisplayTime, {});
|
||||
|
||||
std::unique_lock lock(decoder_mutex);
|
||||
for (auto & i: decoders)
|
||||
{
|
||||
for (auto & frame: i.latest_frames)
|
||||
frame.reset();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
session.begin_frame();
|
||||
auto dt2 = application::now() - t0;
|
||||
|
||||
auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space);
|
||||
assert(views.size() == swapchains.size());
|
||||
|
||||
std::array<int, view_count> image_indices;
|
||||
assert(views.size() == view_count);
|
||||
for (size_t swapchain_index = 0; swapchain_index < views.size(); swapchain_index++)
|
||||
{
|
||||
int image_index = swapchains[swapchain_index].acquire();
|
||||
swapchains[swapchain_index].wait();
|
||||
|
||||
image_indices[swapchain_index] = image_index;
|
||||
}
|
||||
|
||||
CHECK_VK(vkResetCommandBuffer(command_buffer, 0));
|
||||
|
||||
VkCommandBufferBeginInfo begin_info{
|
||||
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
|
||||
};
|
||||
CHECK_VK(vkBeginCommandBuffer(command_buffer, &begin_info));
|
||||
|
||||
// Transition the layout of the decoder framebuffer to the one the decoders expect
|
||||
std::vector<VkImageMemoryBarrier> image_barriers;
|
||||
for (size_t i = 0; i < decoder_output.size(); i++)
|
||||
{
|
||||
image_barriers.push_back(VkImageMemoryBarrier{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.srcAccessMask = 0,
|
||||
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
|
||||
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = shard_accumulator::framebuffer_expected_layout,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = decoder_output[i].image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, image_barriers.size(), image_barriers.data());
|
||||
|
||||
// Keep a reference to the resources needed to blit the images until vkWaitForFences
|
||||
std::vector<std::shared_ptr<shard_accumulator::blit_handle>> current_blit_handles;
|
||||
|
||||
std::array<XrPosef, 2> pose = {views[0].pose, views[1].pose};
|
||||
std::array<XrFovf, 2> fov = {views[0].fov, views[1].fov};
|
||||
{
|
||||
std::lock_guard lock(decoder_mutex);
|
||||
// Search for the most recent frame available on all decoders.
|
||||
// If no such frame exists, use the most latest frame for each decoder
|
||||
auto common_frame = accumulator_images::common_frame(decoders);
|
||||
// Blit images from the decoders
|
||||
// TODO be smarter: group blits per eye, so that the framebuffer can use OP_DONT_CARE instead of OP_LOAD and use the same renderpass if possible
|
||||
for (auto & i: decoders)
|
||||
{
|
||||
auto blit_handle = i.frame(common_frame);
|
||||
if (not blit_handle)
|
||||
continue;
|
||||
|
||||
current_blit_handles.push_back(blit_handle);
|
||||
|
||||
blit_handle->feedback.blitted = application::now();
|
||||
blit_handle->feedback.displayed = framestate.predictedDisplayTime;
|
||||
blit_handle->feedback.real_pose[0] = views[0].pose;
|
||||
blit_handle->feedback.real_pose[1] = views[1].pose;
|
||||
|
||||
pose = blit_handle->view_info.pose;
|
||||
fov = blit_handle->view_info.fov;
|
||||
|
||||
send_feedback(blit_handle->feedback);
|
||||
|
||||
int indices[] = {0, 1};
|
||||
i.decoder->blit(command_buffer, *blit_handle, indices); // TODO blit indices no longer needed here
|
||||
}
|
||||
}
|
||||
|
||||
// Transition the output of the decoder to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
|
||||
image_barriers.clear();
|
||||
for (size_t i = 0; i < decoder_output.size(); i++)
|
||||
{
|
||||
image_barriers.push_back(VkImageMemoryBarrier{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.srcAccessMask = 0,
|
||||
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
|
||||
.oldLayout = shard_accumulator::framebuffer_expected_layout,
|
||||
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = decoder_output[i].image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, image_barriers.size(), image_barriers.data());
|
||||
|
||||
// Reproject the image to the real pose
|
||||
for (size_t view = 0; view < view_count; view++)
|
||||
{
|
||||
size_t destination_index = view * swapchains[0].images().size() + image_indices[view];
|
||||
reprojector.reproject(command_buffer, view, destination_index, pose[view].orientation, fov[view], views[view].pose.orientation, views[view].fov);
|
||||
}
|
||||
|
||||
CHECK_VK(vkEndCommandBuffer(command_buffer));
|
||||
VkSubmitInfo submit_info{
|
||||
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
|
||||
.commandBufferCount = 1,
|
||||
.pCommandBuffers = &command_buffer,
|
||||
};
|
||||
CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, fence));
|
||||
auto dt4 = application::now() - t0;
|
||||
|
||||
std::vector<XrCompositionLayerBaseHeader *> layers_base;
|
||||
std::vector<XrCompositionLayerProjectionView> layer_view;
|
||||
layer_view.resize(views.size());
|
||||
|
||||
for (size_t swapchain_index = 0; swapchain_index < views.size(); swapchain_index++)
|
||||
{
|
||||
swapchains[swapchain_index].release();
|
||||
|
||||
layer_view[swapchain_index].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
|
||||
|
||||
layer_view[swapchain_index].pose = views[swapchain_index].pose;
|
||||
layer_view[swapchain_index].fov = views[swapchain_index].fov;
|
||||
|
||||
layer_view[swapchain_index].subImage.swapchain = swapchains[swapchain_index];
|
||||
layer_view[swapchain_index].subImage.imageRect.offset = {0, 0};
|
||||
layer_view[swapchain_index].subImage.imageRect.extent.width = swapchains[swapchain_index].width();
|
||||
layer_view[swapchain_index].subImage.imageRect.extent.height = swapchains[swapchain_index].height();
|
||||
}
|
||||
|
||||
float brightness = std::clamp<float>(dbrightness * (framestate.predictedDisplayTime - first_frame_time) / 1.e9, 0, 1);
|
||||
|
||||
XrCompositionLayerColorScaleBiasKHR color_scale_bias{
|
||||
.type = XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR,
|
||||
.colorScale = {brightness, brightness, brightness, 1},
|
||||
.colorBias = {}};
|
||||
|
||||
XrCompositionLayerProjection layer{
|
||||
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION,
|
||||
.layerFlags = 0,
|
||||
.space = world_space,
|
||||
.viewCount = (uint32_t)layer_view.size(),
|
||||
.views = layer_view.data(),
|
||||
};
|
||||
|
||||
if (instance.has_extension(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME))
|
||||
layer.next = &color_scale_bias;
|
||||
|
||||
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
|
||||
session.end_frame(/*timestamp*/ framestate.predictedDisplayTime, layers_base);
|
||||
|
||||
auto dt5 = application::now() - t0;
|
||||
CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX));
|
||||
CHECK_VK(vkResetFences(device, 1, &fence));
|
||||
|
||||
// We don't need those after vkWaitForFences
|
||||
current_blit_handles.clear();
|
||||
|
||||
auto dt6 = application::now() - t0;
|
||||
read_actions();
|
||||
|
||||
// spdlog::info("Render timing: begin frame {:.3f}ms, submit commands {:.3f}ms, end frame {:.3f}ms, wait fence {:.3f}ms, predicted display time {:.3f}ms", dt2/1.e6, dt4/1.e6, dt5/1.e6, dt6/1.e6, (framestate.predictedDisplayTime - t0) / 1.e6);
|
||||
}
|
||||
|
||||
void scenes::stream::cleanup()
|
||||
{
|
||||
// Assumes decoder_mutex is locked
|
||||
ready_ = false;
|
||||
decoders.clear();
|
||||
|
||||
for (auto & output: decoder_output)
|
||||
{
|
||||
if (output.image)
|
||||
vkDestroyImage(device, output.image, nullptr);
|
||||
|
||||
if (output.image_view)
|
||||
vkDestroyImageView(device, output.image_view, nullptr);
|
||||
|
||||
if (output.memory)
|
||||
vkFreeMemory(device, output.memory, nullptr);
|
||||
|
||||
output.image = VK_NULL_HANDLE;
|
||||
output.image_view = VK_NULL_HANDLE;
|
||||
output.memory = VK_NULL_HANDLE;
|
||||
}
|
||||
}
|
||||
|
||||
void scenes::stream::setup(const to_headset::video_stream_description & description)
|
||||
{
|
||||
std::unique_lock lock(decoder_mutex);
|
||||
|
||||
cleanup();
|
||||
|
||||
if (description.items.empty())
|
||||
{
|
||||
spdlog::info("Stopping video stream");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create outputs for the decoders
|
||||
const uint32_t width = description.width / view_count;
|
||||
const uint32_t height = description.height;
|
||||
|
||||
VkExtent3D decoder_out_size{width, height, 1};
|
||||
for (size_t i = 0; i < view_count; i++)
|
||||
{
|
||||
decoder_output[i].format = VK_FORMAT_A8B8G8R8_SRGB_PACK32;
|
||||
decoder_output[i].size = {
|
||||
.width = width,
|
||||
.height = height};
|
||||
|
||||
VkImageCreateInfo image_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
|
||||
.flags = 0,
|
||||
.imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32,
|
||||
.extent = decoder_out_size,
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 1,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_SAMPLED_BIT | shard_accumulator::framebuffer_usage,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
};
|
||||
|
||||
decoder_output[i].image = vk::image{device, image_info}.release();
|
||||
|
||||
decoder_output[i].memory = vk::device_memory{device, physical_device, decoder_output[i].image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT}.release();
|
||||
|
||||
VkImageViewCreateInfo image_view_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
|
||||
.image = decoder_output[i].image,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D,
|
||||
.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32,
|
||||
.components = {}, // IDENTITY by default
|
||||
.subresourceRange = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1}};
|
||||
|
||||
CHECK_VK(vkCreateImageView(device, &image_view_info, nullptr, &decoder_output[i].image_view));
|
||||
}
|
||||
|
||||
std::vector<shard_accumulator::blit_target> blit_targets;
|
||||
blit_targets.resize(view_count);
|
||||
|
||||
for (size_t i = 0; i < view_count; i++)
|
||||
{
|
||||
blit_targets[i].image = decoder_output[i].image;
|
||||
blit_targets[i].image_view = decoder_output[i].image_view;
|
||||
blit_targets[i].extent = {width, height};
|
||||
blit_targets[i].offset = {static_cast<int>(width * i), 0};
|
||||
}
|
||||
|
||||
for (const auto & [stream_index, item]: utils::enumerate(description.items))
|
||||
{
|
||||
spdlog::info("Creating decoder size {}x{} offset {},{}", item.width, item.height, item.offset_x, item.offset_y);
|
||||
|
||||
accumulator_images dec;
|
||||
dec.decoder = std::make_unique<shard_accumulator>(device, physical_device, item, shared_from_this(), stream_index);
|
||||
dec.decoder->set_blit_targets(blit_targets, VK_FORMAT_A8B8G8R8_SRGB_PACK32);
|
||||
|
||||
decoders.push_back(std::move(dec));
|
||||
}
|
||||
|
||||
spdlog::info("Initializing reprojector");
|
||||
VkExtent2D extent = {swapchains[0].width(), swapchains[0].height()};
|
||||
std::vector<VkImage> swapchain_images;
|
||||
for (auto & swapchain: swapchains)
|
||||
{
|
||||
for (auto & image: swapchain.images())
|
||||
swapchain_images.push_back(image.image);
|
||||
}
|
||||
|
||||
std::vector<VkImage> images;
|
||||
for (renderpass_output & i: decoder_output)
|
||||
{
|
||||
images.push_back(i.image);
|
||||
}
|
||||
|
||||
reprojector.init(device, physical_device, images, swapchain_images, extent, swapchains[0].format());
|
||||
}
|
||||
|
||||
void scenes::stream::video()
|
||||
{
|
||||
jni_thread jni;
|
||||
|
||||
while (not exiting)
|
||||
{
|
||||
try
|
||||
{
|
||||
auto shard = shard_queue.pop();
|
||||
|
||||
std::visit(
|
||||
[this](auto & shard) {
|
||||
if (shard.stream_item_idx >= decoders.size())
|
||||
{
|
||||
// We don't know (yet?) about this stream, ignore packet
|
||||
return;
|
||||
}
|
||||
auto idx = shard.stream_item_idx;
|
||||
decoders[idx].decoder->push_shard(std::move(shard));
|
||||
},
|
||||
shard);
|
||||
}
|
||||
catch (utils::sync_queue_closed &)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::error("Exception in video thread: {}", e.what());
|
||||
exiting = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* 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 "decoder/shard_accumulator.h"
|
||||
#include "scene.h"
|
||||
#include "stream_reprojection.h"
|
||||
#include "utils/sync_queue.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/renderpass.h"
|
||||
#include "wivrn_client.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
namespace scenes
|
||||
{
|
||||
class stream : public scene, public std::enable_shared_from_this<stream>
|
||||
{
|
||||
static const size_t view_count = 2;
|
||||
|
||||
using stream_description = xrt::drivers::wivrn::to_headset::video_stream_description::item;
|
||||
|
||||
struct accumulator_images
|
||||
{
|
||||
std::unique_ptr<shard_accumulator> decoder;
|
||||
// latest frames from oldest to most recent
|
||||
std::array<std::shared_ptr<shard_accumulator::blit_handle>, 2> latest_frames;
|
||||
|
||||
static std::optional<uint64_t> common_frame(const std::vector<accumulator_images> &);
|
||||
std::shared_ptr<shard_accumulator::blit_handle> frame(std::optional<uint64_t> id);
|
||||
std::vector<uint64_t> frames() const;
|
||||
};
|
||||
|
||||
struct renderpass_output
|
||||
{
|
||||
VkExtent2D size;
|
||||
VkFormat format;
|
||||
VkImage image;
|
||||
VkDeviceMemory memory;
|
||||
VkImageView image_view;
|
||||
};
|
||||
|
||||
std::unique_ptr<wivrn_session> network_session;
|
||||
std::atomic<bool> exiting = false;
|
||||
std::thread network_thread;
|
||||
std::thread tracking_thread;
|
||||
std::thread video_thread;
|
||||
|
||||
utils::sync_queue<std::variant<to_headset::video_stream_data_shard, to_headset::video_stream_parity_shard>> shard_queue;
|
||||
|
||||
std::mutex decoder_mutex;
|
||||
std::vector<accumulator_images> decoders; // Locked by decoder_mutex
|
||||
|
||||
std::array<renderpass_output, view_count> decoder_output{};
|
||||
|
||||
stream_reprojection reprojector;
|
||||
|
||||
VkFence fence;
|
||||
VkCommandBuffer command_buffer;
|
||||
|
||||
std::array<std::pair<XrAction, XrPath>, 2> haptics_actions;
|
||||
std::vector<std::tuple<device_id, XrAction, XrActionType>> input_actions;
|
||||
|
||||
bool ready_ = false;
|
||||
bool video_started_ = false;
|
||||
XrTime first_frame_time{};
|
||||
const float dbrightness = 2;
|
||||
|
||||
stream() = default;
|
||||
|
||||
public:
|
||||
~stream();
|
||||
|
||||
static std::shared_ptr<stream> create(std::unique_ptr<wivrn_session> session);
|
||||
|
||||
virtual void render() override;
|
||||
|
||||
void operator()(to_headset::video_stream_data_shard &&);
|
||||
void operator()(to_headset::video_stream_parity_shard &&);
|
||||
void operator()(to_headset::haptics &&);
|
||||
void operator()(to_headset::timesync_query &&);
|
||||
void operator()(to_headset::video_stream_description &&);
|
||||
|
||||
VkFormat swapchain_format()
|
||||
{
|
||||
return swapchains[0].format();
|
||||
}
|
||||
|
||||
void push_blit_handle(shard_accumulator * decoder, std::shared_ptr<shard_accumulator::blit_handle> handle);
|
||||
|
||||
void send_feedback(const xrt::drivers::wivrn::from_headset::feedback & feedback);
|
||||
|
||||
bool ready() const
|
||||
{
|
||||
return ready_;
|
||||
}
|
||||
|
||||
bool alive() const
|
||||
{
|
||||
return !exiting;
|
||||
}
|
||||
|
||||
private:
|
||||
void process_packets();
|
||||
void tracking();
|
||||
void video();
|
||||
void read_actions();
|
||||
|
||||
void setup(const to_headset::video_stream_description &);
|
||||
void cleanup();
|
||||
};
|
||||
} // namespace scenes
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "stream.h"
|
||||
|
||||
void scenes::stream::read_actions()
|
||||
{
|
||||
from_headset::inputs inputs;
|
||||
application::poll_actions();
|
||||
|
||||
for (const auto & [id, action, action_type]: input_actions)
|
||||
{
|
||||
switch (action_type)
|
||||
{
|
||||
case XR_ACTION_TYPE_BOOLEAN_INPUT: {
|
||||
bool value;
|
||||
if (application::read_action(action, value))
|
||||
inputs.values.push_back({id, (float)value});
|
||||
}
|
||||
break;
|
||||
|
||||
case XR_ACTION_TYPE_FLOAT_INPUT: {
|
||||
float value;
|
||||
if (application::read_action(action, value))
|
||||
inputs.values.push_back({id, value});
|
||||
}
|
||||
break;
|
||||
|
||||
case XR_ACTION_TYPE_VECTOR2F_INPUT: {
|
||||
XrVector2f value;
|
||||
if (application::read_action(action, value))
|
||||
{
|
||||
inputs.values.push_back({id, value.x});
|
||||
inputs.values.push_back({(device_id)((int)id + 1), value.y});
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case XR_ACTION_TYPE_POSE_INPUT:
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
network_session->send_stream(inputs);
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::warn("Exception while sending inputs packet: {}", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::haptics && haptics)
|
||||
{
|
||||
XrAction action;
|
||||
XrPath subpath;
|
||||
|
||||
if (haptics.id == device_id::LEFT_CONTROLLER_HAPTIC)
|
||||
{
|
||||
action = haptics_actions[0].first;
|
||||
subpath = haptics_actions[0].second;
|
||||
}
|
||||
else if (haptics.id == device_id::RIGHT_CONTROLLER_HAPTIC)
|
||||
{
|
||||
action = haptics_actions[1].first;
|
||||
subpath = haptics_actions[1].second;
|
||||
}
|
||||
else
|
||||
return;
|
||||
|
||||
if (haptics.amplitude > 0)
|
||||
application::haptic_start(action, subpath, haptics.duration.count(), haptics.frequency, haptics.amplitude);
|
||||
else
|
||||
application::haptic_stop(action, subpath);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "stream.h"
|
||||
|
||||
void scenes::stream::process_packets()
|
||||
{
|
||||
while (not exiting)
|
||||
{
|
||||
try
|
||||
{
|
||||
int n = network_session->poll(*this, std::chrono::milliseconds(5000));
|
||||
if (n == 0 && video_started_)
|
||||
throw std::runtime_error("Timeout waiting for network packets");
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::info("Exception in network thread, exiting: {}", e.what());
|
||||
exiting = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::video_stream_data_shard && shard)
|
||||
{
|
||||
video_started_ = true;
|
||||
shard_queue.push(std::move(shard));
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::video_stream_parity_shard && shard)
|
||||
{
|
||||
video_started_ = true;
|
||||
shard_queue.push(std::move(shard));
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::video_stream_description && desc)
|
||||
{
|
||||
setup(desc);
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::timesync_query && query)
|
||||
{
|
||||
from_headset::timesync_response response{};
|
||||
response.query = query.query;
|
||||
response.response = instance.now();
|
||||
network_session->send_stream(response);
|
||||
}
|
||||
|
||||
void scenes::stream::send_feedback(const xrt::drivers::wivrn::from_headset::feedback & feedback)
|
||||
{
|
||||
try
|
||||
{
|
||||
network_session->send_control(feedback);
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::warn("Exception while sending feedback packet: {}", e.what());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "stream_reprojection.h"
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "utils/check.h"
|
||||
#include <array>
|
||||
#include <glm/glm.hpp>
|
||||
#include <glm/gtx/quaternion.hpp>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
struct stream_reprojection::uniform
|
||||
{
|
||||
alignas(16) glm::mat4 reprojection;
|
||||
};
|
||||
|
||||
stream_reprojection::~stream_reprojection()
|
||||
{
|
||||
cleanup();
|
||||
}
|
||||
|
||||
void stream_reprojection::cleanup()
|
||||
{
|
||||
if (device)
|
||||
{
|
||||
if (descriptor_pool)
|
||||
vkDestroyDescriptorPool(device, descriptor_pool, nullptr);
|
||||
|
||||
if (descriptor_set_layout)
|
||||
vkDestroyDescriptorSetLayout(device, descriptor_set_layout, nullptr);
|
||||
|
||||
for (VkFramebuffer framebuffer: framebuffers)
|
||||
vkDestroyFramebuffer(device, framebuffer, nullptr);
|
||||
|
||||
for (VkImageView image_view: output_image_views)
|
||||
vkDestroyImageView(device, image_view, nullptr);
|
||||
|
||||
for (VkImageView image_view: input_image_views)
|
||||
vkDestroyImageView(device, image_view, nullptr);
|
||||
|
||||
if (sampler)
|
||||
vkDestroySampler(device, sampler, nullptr);
|
||||
|
||||
descriptor_pool = VK_NULL_HANDLE;
|
||||
descriptor_set_layout = VK_NULL_HANDLE;
|
||||
sampler = VK_NULL_HANDLE;
|
||||
framebuffers.clear();
|
||||
output_image_views.clear();
|
||||
input_image_views.clear();
|
||||
ubo.clear();
|
||||
}
|
||||
}
|
||||
|
||||
void stream_reprojection::init(VkDevice device, VkPhysicalDevice physical_device, std::vector<VkImage> input_images_, std::vector<VkImage> output_images_, VkExtent2D extent, VkFormat format)
|
||||
{
|
||||
cleanup();
|
||||
this->device = device;
|
||||
this->physical_device = physical_device,
|
||||
this->input_images = std::move(input_images_);
|
||||
this->output_images = std::move(output_images_);
|
||||
this->extent = extent;
|
||||
this->format = format;
|
||||
|
||||
VkPhysicalDeviceProperties properties;
|
||||
vkGetPhysicalDeviceProperties(physical_device, &properties);
|
||||
|
||||
VkSamplerCreateInfo sampler_info{
|
||||
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
|
||||
.magFilter = VK_FILTER_LINEAR,
|
||||
.minFilter = VK_FILTER_LINEAR,
|
||||
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
|
||||
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.mipLodBias = 0.0f,
|
||||
.anisotropyEnable = VK_FALSE,
|
||||
.maxAnisotropy = 1,
|
||||
.compareEnable = VK_FALSE,
|
||||
.compareOp = VK_COMPARE_OP_NEVER,
|
||||
.minLod = 0.0f,
|
||||
.maxLod = 0.0f,
|
||||
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
|
||||
.unnormalizedCoordinates = VK_FALSE,
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateSampler(device, &sampler_info, nullptr, &sampler));
|
||||
|
||||
size_t uniform_size = sizeof(uniform) + properties.limits.minUniformBufferOffsetAlignment - 1;
|
||||
uniform_size = uniform_size - uniform_size % properties.limits.minUniformBufferOffsetAlignment;
|
||||
|
||||
VkBufferCreateInfo create_info{
|
||||
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
|
||||
.size = uniform_size * input_images.size(),
|
||||
.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
};
|
||||
buffer = vk::buffer(device, create_info);
|
||||
memory = vk::device_memory(device, physical_device, buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
memory.map_memory();
|
||||
for (size_t i = 0; i < input_images.size(); i++)
|
||||
ubo.push_back(reinterpret_cast<uniform *>(reinterpret_cast<uintptr_t>(memory.data()) + i * uniform_size));
|
||||
|
||||
// Create VkDescriptorSetLayout
|
||||
std::array<VkDescriptorSetLayoutBinding, 2> layout_binding{
|
||||
VkDescriptorSetLayoutBinding{
|
||||
.binding = 0,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
},
|
||||
{
|
||||
.binding = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
}};
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo layout_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.bindingCount = layout_binding.size(),
|
||||
.pBindings = layout_binding.data(),
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &descriptor_set_layout));
|
||||
|
||||
std::array<VkDescriptorPoolSize, 2> pool_size{VkDescriptorPoolSize{
|
||||
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1,
|
||||
},
|
||||
VkDescriptorPoolSize{
|
||||
.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
||||
.descriptorCount = 1,
|
||||
}};
|
||||
|
||||
VkDescriptorPoolCreateInfo pool_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
|
||||
.flags = 0,
|
||||
.maxSets = (uint32_t)input_images.size(),
|
||||
.poolSizeCount = pool_size.size(),
|
||||
.pPoolSizes = pool_size.data(),
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateDescriptorPool(device, &pool_info, nullptr, &descriptor_pool));
|
||||
|
||||
// Create image views and descriptor sets
|
||||
input_image_views.reserve(input_images.size());
|
||||
descriptor_sets.reserve(input_images.size());
|
||||
VkDeviceSize offset = 0;
|
||||
for (VkImage image: input_images)
|
||||
{
|
||||
VkImageViewCreateInfo iv_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
|
||||
.image = image,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D,
|
||||
.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32,
|
||||
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
|
||||
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1}};
|
||||
|
||||
VkImageView image_view;
|
||||
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &image_view));
|
||||
input_image_views.push_back(image_view);
|
||||
|
||||
VkDescriptorSetAllocateInfo ds_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
|
||||
.descriptorPool = descriptor_pool,
|
||||
.descriptorSetCount = 1,
|
||||
.pSetLayouts = &descriptor_set_layout,
|
||||
};
|
||||
VkDescriptorSet ds;
|
||||
CHECK_VK(vkAllocateDescriptorSets(device, &ds_info, &ds));
|
||||
descriptor_sets.push_back(ds);
|
||||
|
||||
VkDescriptorImageInfo image_info{
|
||||
.sampler = sampler,
|
||||
.imageView = image_view,
|
||||
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
};
|
||||
|
||||
VkDescriptorBufferInfo buffer_info{
|
||||
.buffer = buffer, .offset = offset, .range = sizeof(uniform)};
|
||||
offset += uniform_size;
|
||||
|
||||
std::array<VkWriteDescriptorSet, 2> write{
|
||||
VkWriteDescriptorSet{
|
||||
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
|
||||
.dstSet = ds,
|
||||
.dstBinding = 0,
|
||||
.dstArrayElement = 0,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.pImageInfo = &image_info,
|
||||
},
|
||||
VkWriteDescriptorSet{
|
||||
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
|
||||
.dstSet = ds,
|
||||
.dstBinding = 1,
|
||||
.dstArrayElement = 0,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
||||
.pBufferInfo = &buffer_info},
|
||||
};
|
||||
|
||||
vkUpdateDescriptorSets(device, write.size(), write.data(), 0, nullptr);
|
||||
}
|
||||
|
||||
// Create renderpass
|
||||
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
|
||||
|
||||
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{
|
||||
.format = format,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
|
||||
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
}},
|
||||
.subpasses = {VkSubpassDescription{
|
||||
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
|
||||
.colorAttachmentCount = 1,
|
||||
.pColorAttachments = &color_ref,
|
||||
}},
|
||||
.dependencies = {}};
|
||||
|
||||
renderpass = vk::renderpass(device, renderpass_info);
|
||||
|
||||
// Create graphics pipeline
|
||||
vk::shader vertex_shader(device, "reprojection.vert");
|
||||
vk::shader fragment_shader(device, "reprojection.frag");
|
||||
|
||||
VkPipelineColorBlendAttachmentState pcbas{.colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
|
||||
VK_COLOR_COMPONENT_G_BIT |
|
||||
VK_COLOR_COMPONENT_B_BIT};
|
||||
|
||||
layout = vk::pipeline_layout(device, {.descriptor_set_layouts = {descriptor_set_layout}});
|
||||
|
||||
vk::pipeline::graphics_info pipeline_info{
|
||||
.shader_stages =
|
||||
{{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vertex_shader, .pName = "main"},
|
||||
{.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fragment_shader, .pName = "main"}},
|
||||
.vertex_input_bindings = {},
|
||||
.vertex_input_attributes = {},
|
||||
.InputAssemblyState = {.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP},
|
||||
.viewports = {VkViewport{.x = 0,
|
||||
.y = 0,
|
||||
.width = (float)extent.width,
|
||||
.height = (float)extent.height,
|
||||
.minDepth = 0,
|
||||
.maxDepth = 1}},
|
||||
.scissors = {VkRect2D{
|
||||
.offset = {0, 0},
|
||||
.extent = extent,
|
||||
}},
|
||||
.RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1},
|
||||
.MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT},
|
||||
.ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas},
|
||||
.dynamic_states = {},
|
||||
.renderPass = renderpass,
|
||||
.subpass = 0,
|
||||
};
|
||||
|
||||
pipeline = vk::pipeline(device, pipeline_info, layout);
|
||||
|
||||
// Create image views and framebuffers
|
||||
output_image_views.reserve(output_images.size());
|
||||
framebuffers.reserve(output_images.size());
|
||||
for (VkImage image: output_images)
|
||||
{
|
||||
VkImageViewCreateInfo iv_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
|
||||
.image = image,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D,
|
||||
.format = format,
|
||||
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
|
||||
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1}};
|
||||
|
||||
VkImageView image_view;
|
||||
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &image_view));
|
||||
output_image_views.push_back(image_view);
|
||||
|
||||
VkFramebufferCreateInfo fb_create_info{
|
||||
.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
|
||||
.renderPass = renderpass,
|
||||
.attachmentCount = 1,
|
||||
.pAttachments = &image_view,
|
||||
.width = extent.width,
|
||||
.height = extent.height,
|
||||
.layers = 1,
|
||||
};
|
||||
|
||||
VkFramebuffer framebuffer;
|
||||
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &framebuffer));
|
||||
framebuffers.push_back(framebuffer);
|
||||
}
|
||||
}
|
||||
|
||||
void stream_reprojection::reproject(VkCommandBuffer command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf dest_pose, XrFovf dest_fov)
|
||||
{
|
||||
if (source < 0 || source >= (int)input_images.size())
|
||||
throw std::runtime_error("Invalid source image index");
|
||||
if (destination < 0 || destination >= (int)output_images.size())
|
||||
throw std::runtime_error("Invalid destination image index");
|
||||
|
||||
// Compute the reprojection matrix
|
||||
float zn = 1;
|
||||
float r = tan(dest_fov.angleRight);
|
||||
float l = tan(dest_fov.angleLeft);
|
||||
float t = tan(dest_fov.angleUp);
|
||||
float b = tan(dest_fov.angleDown);
|
||||
|
||||
// clang-format off
|
||||
glm::mat4 hmd_proj{
|
||||
{ 2*zn/(r-l), 0, 0, 0 },
|
||||
{ 0, 2*zn/(b-t), 0, 0 },
|
||||
{ (l+r)/(r-l), (t+b)/(b-t), -1, -1 },
|
||||
{ 0, 0, -2*zn, 0 }
|
||||
};
|
||||
|
||||
glm::mat4 hmd_unview = glm::mat4_cast(glm::quat(
|
||||
dest_pose.w,
|
||||
dest_pose.x,
|
||||
dest_pose.y,
|
||||
dest_pose.z));
|
||||
|
||||
r = tan(source_fov.angleRight);
|
||||
l = tan(source_fov.angleLeft);
|
||||
t = tan(source_fov.angleUp);
|
||||
b = tan(source_fov.angleDown);
|
||||
|
||||
glm::mat4 video_proj{
|
||||
{ 2*zn/(r-l), 0, 0, 0 },
|
||||
{ 0, 2*zn/(b-t), 0, 0 },
|
||||
{ (l+r)/(r-l), (t+b)/(b-t), -1, -1 },
|
||||
{ 0, 0, -2*zn, 0 }
|
||||
};
|
||||
|
||||
glm::mat4 video_view = glm::mat4_cast(glm::quat(
|
||||
-source_pose.w,
|
||||
source_pose.x,
|
||||
source_pose.y,
|
||||
source_pose.z));
|
||||
// clang-format on
|
||||
|
||||
ubo[source]->reprojection = video_proj * video_view * hmd_unview * glm::inverse(hmd_proj);
|
||||
|
||||
VkClearValue clear_color{};
|
||||
|
||||
VkRenderPassBeginInfo begin_info{
|
||||
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
|
||||
.renderPass = renderpass,
|
||||
.framebuffer = framebuffers[destination],
|
||||
.renderArea =
|
||||
{
|
||||
.offset = {0, 0},
|
||||
.extent = extent,
|
||||
},
|
||||
.clearValueCount = 1,
|
||||
.pClearValues = &clear_color,
|
||||
};
|
||||
|
||||
vkCmdBeginRenderPass(command_buffer, &begin_info, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
|
||||
|
||||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &descriptor_sets[source], 0, nullptr);
|
||||
vkCmdDraw(command_buffer, 3, 1, 0, 0);
|
||||
|
||||
vkCmdEndRenderPass(command_buffer);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* 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 "vk/buffer.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/pipeline.h"
|
||||
#include "vk/pipeline_layout.h"
|
||||
#include "vk/renderpass.h"
|
||||
#include "vk/shader.h"
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
class stream_reprojection
|
||||
{
|
||||
struct uniform;
|
||||
|
||||
VkDevice device;
|
||||
VkPhysicalDevice physical_device;
|
||||
|
||||
// Uniform buffer
|
||||
vk::buffer buffer;
|
||||
vk::device_memory memory;
|
||||
std::vector<uniform *> ubo{};
|
||||
|
||||
// Source images
|
||||
VkSampler sampler{};
|
||||
std::vector<VkImage> input_images;
|
||||
std::vector<VkImageView> input_image_views;
|
||||
std::vector<VkDescriptorSet> descriptor_sets;
|
||||
|
||||
// Destination images
|
||||
std::vector<VkImage> output_images;
|
||||
std::vector<VkImageView> output_image_views;
|
||||
std::vector<VkFramebuffer> framebuffers;
|
||||
VkExtent2D extent{};
|
||||
VkFormat format{};
|
||||
|
||||
// Graphic pipeline
|
||||
VkDescriptorSetLayout descriptor_set_layout{};
|
||||
VkDescriptorPool descriptor_pool{};
|
||||
vk::pipeline_layout layout;
|
||||
vk::pipeline pipeline;
|
||||
vk::renderpass renderpass;
|
||||
|
||||
void cleanup();
|
||||
|
||||
public:
|
||||
stream_reprojection() = default;
|
||||
stream_reprojection(const stream_reprojection &) = delete;
|
||||
void init(VkDevice device, VkPhysicalDevice physical_device, std::vector<VkImage> input_images, std::vector<VkImage> output_images, VkExtent2D extent, VkFormat format);
|
||||
|
||||
~stream_reprojection();
|
||||
|
||||
void reproject(VkCommandBuffer command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf destination_pose, XrFovf destination_fov);
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "stream.h"
|
||||
#include "utils/ranges.h"
|
||||
#include <thread>
|
||||
|
||||
static 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};
|
||||
|
||||
xrLocateSpace(space, reference, time, &location);
|
||||
|
||||
from_headset::tracking::pose res{
|
||||
.device = device,
|
||||
.pose = location.pose,
|
||||
.linear_velocity = velocity.linearVelocity,
|
||||
.angular_velocity = velocity.angularVelocity,
|
||||
.flags = 0,
|
||||
};
|
||||
|
||||
if (location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
|
||||
res.flags |= from_headset::tracking::orientation_valid;
|
||||
|
||||
if (location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT)
|
||||
res.flags |= from_headset::tracking::position_valid;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
void scenes::stream::tracking()
|
||||
{
|
||||
std::vector<std::pair<device_id, XrSpace>> spaces = {
|
||||
{device_id::HEAD, application::view()},
|
||||
{device_id::LEFT_AIM, application::left_aim()},
|
||||
{device_id::LEFT_GRIP, application::left_grip()},
|
||||
{device_id::RIGHT_AIM, application::right_aim()},
|
||||
{device_id::RIGHT_GRIP, application::right_grip()}};
|
||||
|
||||
XrSpace view_space = application::view();
|
||||
const XrDuration tracking_period = 10'000'000; // Send tracking data every 10ms
|
||||
const XrDuration dt = 1'000'000; // Wake up 1ms before measuring the position
|
||||
const XrDuration extrapolation_horizon = 1; // 50'000'000;
|
||||
|
||||
XrTime t0 = instance.now();
|
||||
t0 = t0 - t0 % tracking_period;
|
||||
|
||||
while (not exiting)
|
||||
{
|
||||
try
|
||||
{
|
||||
XrTime now = instance.now();
|
||||
if (now < t0)
|
||||
std::this_thread::sleep_for(std::chrono::nanoseconds(t0 - now - dt));
|
||||
|
||||
for (XrTime Δt = 0; Δt < extrapolation_horizon; Δt += tracking_period)
|
||||
{
|
||||
from_headset::tracking packet{};
|
||||
packet.timestamp = t0 + Δt;
|
||||
|
||||
try
|
||||
{
|
||||
auto [flags, views] = session.locate_views(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, t0 + Δt, view_space);
|
||||
assert(views.size() == packet.views.size());
|
||||
|
||||
for (auto [i, j]: utils::zip(views, packet.views))
|
||||
{
|
||||
j.pose = i.pose;
|
||||
j.fov = i.fov;
|
||||
}
|
||||
|
||||
packet.flags = flags;
|
||||
|
||||
for (auto [device, space]: spaces)
|
||||
{
|
||||
packet.device_poses.push_back(locate_space(device, space, world_space, t0 + Δt));
|
||||
}
|
||||
|
||||
network_session->send_stream(packet);
|
||||
}
|
||||
catch (const std::system_error & e)
|
||||
{
|
||||
if (e.code().category() != xr::error_category() or
|
||||
e.code().value() != XR_ERROR_TIME_INVALID)
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
t0 += tracking_period;
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::info("Exception in tracking thread, exiting: {}", e.what());
|
||||
exiting = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
#version 450
|
||||
|
||||
#ifdef VERT_SHADER
|
||||
|
||||
vec2 positions[3] = vec2[](
|
||||
vec2(-1.0, -1.0),
|
||||
vec2(3.0, -1.0),
|
||||
vec2(-1.0, 3.0));
|
||||
|
||||
layout(location = 0) out vec2 outUV;
|
||||
|
||||
layout(set = 0, binding = 1) uniform UniformBufferObject
|
||||
{
|
||||
mat4 reprojection;
|
||||
}
|
||||
ubo;
|
||||
|
||||
void main()
|
||||
{
|
||||
// outUV = vec2(ubo.reprojection * vec4(positions[gl_VertexIndex], 1.0, 1.0));
|
||||
outUV = positions[gl_VertexIndex];
|
||||
gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef FRAG_SHADER
|
||||
layout(set = 0, binding = 0) uniform sampler2D texSampler;
|
||||
|
||||
layout(set = 0, binding = 1) uniform UniformBufferObject
|
||||
{
|
||||
mat4 reprojection;
|
||||
}
|
||||
ubo;
|
||||
|
||||
layout(location = 0) in vec2 inUV;
|
||||
|
||||
layout(location = 0) out vec4 outColor;
|
||||
|
||||
void main()
|
||||
{
|
||||
vec4 tmp = ubo.reprojection * vec4(inUV, 1.0, 1.0);
|
||||
|
||||
outColor = texture(texSampler, vec2(tmp) / tmp.z * 0.5 + vec2(0.5, 0.5));
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
#version 450
|
||||
|
||||
#ifdef VERT_SHADER
|
||||
vec2 positions[3] = vec2[](
|
||||
vec2(-1.0, -1.0),
|
||||
vec2(3.0, -1.0),
|
||||
vec2(-1.0, 3.0));
|
||||
|
||||
vec2 uvs[3] = vec2[](
|
||||
vec2(0.0, 0.0),
|
||||
vec2(2.0, 0.0),
|
||||
vec2(0.0, 2.0));
|
||||
|
||||
layout(location = 0) out vec2 outUV;
|
||||
|
||||
void main()
|
||||
{
|
||||
outUV = uvs[gl_VertexIndex];
|
||||
gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef FRAG_SHADER
|
||||
layout(binding = 0) uniform sampler2D texSampler;
|
||||
|
||||
layout(location = 0) in vec2 inUV;
|
||||
|
||||
layout(location = 0) out vec4 outColor;
|
||||
|
||||
void main()
|
||||
{
|
||||
outColor = texture(texSampler, inUV);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
#version 450
|
||||
|
||||
#ifdef VERT_SHADER
|
||||
|
||||
layout (std140, push_constant) uniform UBO
|
||||
{
|
||||
mat4 model_view_projection;
|
||||
} instance;
|
||||
|
||||
vec2 uv[6] = vec2[](
|
||||
vec2(0.0, 0.0),
|
||||
vec2(1.0, 0.0),
|
||||
vec2(0.0, 1.0),
|
||||
|
||||
vec2(1.0, 0.0),
|
||||
vec2(0.0, 1.0),
|
||||
vec2(1.0, 1.0)
|
||||
);
|
||||
|
||||
|
||||
layout (location = 0) out vec2 outUV;
|
||||
|
||||
void main()
|
||||
{
|
||||
vec4 position = vec4(uv[gl_VertexIndex], 0.0, 1.0);
|
||||
outUV = vec2(uv[gl_VertexIndex].x, 1.0 - uv[gl_VertexIndex].y);
|
||||
|
||||
gl_Position = instance.model_view_projection * position;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef FRAG_SHADER
|
||||
layout(set = 0, binding = 0) uniform sampler2D texSampler;
|
||||
layout(location = 0) in vec2 texcoord0;
|
||||
|
||||
layout(location = 0) out vec4 outColor;
|
||||
|
||||
void main()
|
||||
{
|
||||
outColor = vec4(texture(texSampler, texcoord0).rrr, 1.0);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
#version 450
|
||||
|
||||
#ifdef VERT_SHADER
|
||||
layout(location = 0) in vec3 in_position;
|
||||
layout(location = 1) in vec3 in_normal;
|
||||
layout(location = 2) in vec2 in_texcoord0;
|
||||
|
||||
layout(set = 1, binding = 0) uniform UBO
|
||||
{
|
||||
mat4 model_view;
|
||||
mat4 projection;
|
||||
}
|
||||
instance;
|
||||
|
||||
layout(location = 0) out vec4 normal;
|
||||
layout(location = 1) out vec2 texcoord0;
|
||||
|
||||
void main()
|
||||
{
|
||||
normal = instance.model_view * vec4(in_normal, 0.0);
|
||||
texcoord0 = texcoord0;
|
||||
gl_Position = instance.projection * instance.model_view * vec4(in_position, 1.0);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef FRAG_SHADER
|
||||
layout(set = 0, binding = 0) uniform sampler2D base_color;
|
||||
|
||||
layout(set = 1, binding = 0) uniform UBO
|
||||
{
|
||||
mat4 model_view;
|
||||
mat4 projection;
|
||||
}
|
||||
instance;
|
||||
|
||||
layout(location = 0) in vec4 normal;
|
||||
layout(location = 1) in vec2 texcoord0;
|
||||
|
||||
void main()
|
||||
{
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
* 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 "backtrace.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cxxabi.h>
|
||||
#include <dlfcn.h>
|
||||
#include <span>
|
||||
#include <spdlog/fmt/fmt.h>
|
||||
#include <stdlib.h>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unwind.h>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _GNU_SOURCE
|
||||
#define _GNU_SOURCE
|
||||
#endif
|
||||
#include <link.h>
|
||||
|
||||
struct bt_state
|
||||
{
|
||||
struct lib_info
|
||||
{
|
||||
std::string name;
|
||||
uintptr_t address;
|
||||
std::span<const Elf64_Phdr> headers;
|
||||
};
|
||||
|
||||
size_t max_size;
|
||||
std::vector<void *> trace;
|
||||
std::unordered_map<std::string, lib_info> libs;
|
||||
};
|
||||
|
||||
static _Unwind_Reason_Code unwind_callback(struct _Unwind_Context * context, void * arg)
|
||||
{
|
||||
bt_state & state = *static_cast<bt_state *>(arg);
|
||||
uintptr_t pc = _Unwind_GetIP(context);
|
||||
if (pc)
|
||||
{
|
||||
if (state.trace.size() >= state.max_size)
|
||||
{
|
||||
return _URC_END_OF_STACK;
|
||||
}
|
||||
else
|
||||
{
|
||||
state.trace.push_back(reinterpret_cast<void *>(pc));
|
||||
}
|
||||
}
|
||||
return _URC_NO_REASON;
|
||||
}
|
||||
|
||||
static int iterate_phdr_callback(dl_phdr_info * info, size_t size, void * arg)
|
||||
{
|
||||
bt_state & state = *static_cast<bt_state *>(arg);
|
||||
|
||||
std::string library = info->dlpi_name;
|
||||
auto slash = library.find_last_of('/');
|
||||
if (slash != std::string::npos)
|
||||
library = library.substr(slash + 1);
|
||||
|
||||
state.libs.emplace(library, bt_state::lib_info{library, info->dlpi_addr, {info->dlpi_phdr, info->dlpi_phdr + info->dlpi_phnum}});
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static std::string unmangle(const char * function)
|
||||
{
|
||||
if (!function)
|
||||
return "(null)";
|
||||
|
||||
int status;
|
||||
char * demangled = abi::__cxa_demangle(function, nullptr, nullptr, &status);
|
||||
|
||||
if (status != 0)
|
||||
return function;
|
||||
|
||||
std::string s = demangled;
|
||||
free(demangled);
|
||||
return s;
|
||||
}
|
||||
|
||||
std::vector<utils::backtrace_entry> utils::backtrace(size_t max)
|
||||
{
|
||||
bt_state state;
|
||||
state.max_size = max;
|
||||
|
||||
dl_iterate_phdr(iterate_phdr_callback, &state);
|
||||
|
||||
_Unwind_Backtrace(unwind_callback, &state);
|
||||
|
||||
std::vector<backtrace_entry> trace;
|
||||
trace.reserve(state.trace.size());
|
||||
for (void * pc: state.trace)
|
||||
{
|
||||
Dl_info info;
|
||||
if (dladdr(pc, &info))
|
||||
{
|
||||
// size_t offset = (size_t)pc - (size_t)info.dli_saddr;
|
||||
// std::string function = unmangle(info.dli_sname);
|
||||
std::string library = info.dli_fname;
|
||||
|
||||
auto slash = library.find_last_of('/');
|
||||
if (slash != std::string::npos)
|
||||
library = library.substr(slash + 1);
|
||||
|
||||
auto it = state.libs.find(library);
|
||||
uintptr_t library_base = 0;
|
||||
if (it != state.libs.end())
|
||||
library_base = it->second.address;
|
||||
|
||||
trace.push_back(backtrace_entry{
|
||||
.library = library,
|
||||
.library_base = library_base,
|
||||
.pc = (uintptr_t)pc,
|
||||
});
|
||||
// fmt::format("{:#016x}: {}, {}+{:#x}", (uintptr_t)pc, library, function, offset));
|
||||
}
|
||||
}
|
||||
|
||||
return trace;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* 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 <string>
|
||||
#include <vector>
|
||||
|
||||
namespace utils
|
||||
{
|
||||
struct backtrace_entry
|
||||
{
|
||||
std::string library;
|
||||
uintptr_t library_base;
|
||||
uintptr_t pc;
|
||||
};
|
||||
|
||||
std::vector<backtrace_entry> backtrace(size_t max = 10);
|
||||
} // namespace utils
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 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 <stdexcept>
|
||||
#include <system_error>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
#if __has_include(<vulkan/vk_enum_string_helper.h>)
|
||||
#include <vulkan/vk_enum_string_helper.h>
|
||||
#else
|
||||
#include "external/magic_enum.hpp"
|
||||
#define string_VkResult(x) std::string(magic_enum::enum_name((VkResult)(x)))
|
||||
#endif
|
||||
|
||||
namespace xr
|
||||
{
|
||||
const std::error_category & error_category();
|
||||
}
|
||||
|
||||
namespace vk
|
||||
{
|
||||
const std::error_category & error_category();
|
||||
}
|
||||
|
||||
static inline VkResult check(VkResult result, const char * statement)
|
||||
{
|
||||
if (result != VK_SUCCESS)
|
||||
throw std::system_error(result, vk::error_category(), statement);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static inline VkResult check(VkResult result, const char * /*statement*/, const char * message)
|
||||
{
|
||||
if (result != VK_SUCCESS)
|
||||
throw std::system_error(result, vk::error_category(), message);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static inline XrResult check(XrResult result, const char * statement)
|
||||
{
|
||||
if (!XR_SUCCEEDED(result))
|
||||
throw std::system_error(result, xr::error_category(), statement);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static inline XrResult check(XrResult result, const char * /*statement*/, const char * message)
|
||||
{
|
||||
if (!XR_SUCCEEDED(result))
|
||||
throw std::system_error(result, xr::error_category(), message);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#define CHECK_VK(result, ...) check(result, #result __VA_OPT__(, ) __VA_ARGS__)
|
||||
#define CHECK_XR(result, ...) check(result, #result __VA_OPT__(, ) __VA_ARGS__)
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* 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 <utility>
|
||||
|
||||
namespace utils
|
||||
{
|
||||
template <typename T>
|
||||
class handle
|
||||
{
|
||||
protected:
|
||||
static const inline T null_value = 0;
|
||||
|
||||
T id = null_value;
|
||||
|
||||
handle() {}
|
||||
~handle() {}
|
||||
|
||||
public:
|
||||
handle(handle && other) noexcept :
|
||||
id(other.id)
|
||||
{
|
||||
other.id = null_value;
|
||||
}
|
||||
|
||||
handle & operator=(handle && other) noexcept
|
||||
{
|
||||
std::swap(id, other.id);
|
||||
return *this;
|
||||
}
|
||||
|
||||
handle(const handle &) = delete;
|
||||
handle & operator=(const handle &) = delete;
|
||||
|
||||
operator T() const
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
operator bool() const
|
||||
{
|
||||
return id != null_value;
|
||||
}
|
||||
|
||||
T release()
|
||||
{
|
||||
T r = id;
|
||||
id = null_value;
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
bool operator==(const handle<T> & lhs, const T & rhs)
|
||||
{
|
||||
return (T)lhs == rhs;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool operator==(const T & lhs, const handle<T> & rhs)
|
||||
{
|
||||
return lhs == (T)rhs;
|
||||
}
|
||||
|
||||
} // namespace utils
|
||||
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* 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 <cstddef>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace utils
|
||||
{
|
||||
template <typename T>
|
||||
struct enumerate_range
|
||||
{
|
||||
struct iterator
|
||||
{
|
||||
using underlying_iterator = std::conditional_t<std::is_const_v<T>, typename T::const_iterator, typename T::iterator>;
|
||||
using underlying_value_type = std::conditional_t<std::is_const_v<T>, const typename T::value_type, typename T::value_type>;
|
||||
|
||||
size_t index;
|
||||
underlying_iterator it;
|
||||
|
||||
std::pair<size_t, underlying_value_type &> operator*() const
|
||||
{
|
||||
return {index, *it};
|
||||
}
|
||||
|
||||
iterator & operator++()
|
||||
{
|
||||
++it;
|
||||
++index;
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool operator==(const iterator & other) const
|
||||
{
|
||||
return it == other.it;
|
||||
}
|
||||
|
||||
bool operator!=(const iterator & other) const
|
||||
{
|
||||
return it != other.it;
|
||||
}
|
||||
};
|
||||
|
||||
T & range;
|
||||
|
||||
iterator begin() const
|
||||
{
|
||||
if constexpr (std::is_const_v<T>)
|
||||
return iterator{0, std::cbegin(range)};
|
||||
else
|
||||
return iterator{0, std::begin(range)};
|
||||
}
|
||||
|
||||
iterator end() const
|
||||
{
|
||||
if constexpr (std::is_const_v<T>)
|
||||
return iterator{0, std::cend(range)};
|
||||
else
|
||||
return iterator{0, std::end(range)};
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
enumerate_range<const T> enumerate(const T & t)
|
||||
{
|
||||
return {t};
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
enumerate_range<T> enumerate(T & t)
|
||||
{
|
||||
return {t};
|
||||
}
|
||||
|
||||
template <typename T1, typename T2>
|
||||
struct zip_range
|
||||
{
|
||||
struct iterator
|
||||
{
|
||||
using iterator1 = decltype(std::begin(std::declval<T1 &>()));
|
||||
using iterator2 = decltype(std::begin(std::declval<T2 &>()));
|
||||
|
||||
using value1 = decltype(*std::declval<iterator1>());
|
||||
using value2 = decltype(*std::declval<iterator2>());
|
||||
|
||||
iterator1 iter1;
|
||||
iterator2 iter2;
|
||||
|
||||
std::pair<value1 &, value2 &> operator*() const
|
||||
{
|
||||
return {*iter1, *iter2};
|
||||
}
|
||||
|
||||
iterator & operator++()
|
||||
{
|
||||
++iter1;
|
||||
++iter2;
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool operator==(const iterator & other) const
|
||||
{
|
||||
return iter1 == other.iter1 || iter2 == other.iter2;
|
||||
}
|
||||
|
||||
bool operator!=(const iterator & other) const
|
||||
{
|
||||
return !(*this == other);
|
||||
}
|
||||
};
|
||||
|
||||
T1 & range1;
|
||||
T2 & range2;
|
||||
|
||||
iterator begin() const
|
||||
{
|
||||
return iterator{std::begin(range1), std::begin(range2)};
|
||||
}
|
||||
|
||||
iterator end() const
|
||||
{
|
||||
return iterator{std::end(range1), std::end(range2)};
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T1, typename T2>
|
||||
zip_range<T1, T2> zip(T1 & range1, T2 & range2)
|
||||
{
|
||||
return zip_range<T1, T2>{range1, range2};
|
||||
}
|
||||
} // namespace utils
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* 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 "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;
|
||||
std::vector<std::string> v;
|
||||
|
||||
while (true)
|
||||
{
|
||||
std::string::size_type j = s.find_first_not_of(sep, i);
|
||||
if (j == std::string::npos)
|
||||
{
|
||||
v.push_back(s.substr(i + 1));
|
||||
return v;
|
||||
}
|
||||
|
||||
v.push_back(s.substr(i, j - i));
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 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 <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
|
||||
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* 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 <cassert>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <exception>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
|
||||
namespace utils
|
||||
{
|
||||
class sync_queue_closed : public std::exception
|
||||
{
|
||||
public:
|
||||
const char * what() const noexcept override
|
||||
{
|
||||
return "sync_queue_closed";
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class sync_queue
|
||||
{
|
||||
std::deque<T> queue;
|
||||
std::condition_variable cv;
|
||||
std::mutex mutex;
|
||||
bool closed = false;
|
||||
|
||||
public:
|
||||
void push(T && item)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
|
||||
queue.push_back(std::move(item));
|
||||
cv.notify_one();
|
||||
}
|
||||
|
||||
void push(const T & item)
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
|
||||
queue.push_back(item);
|
||||
cv.notify_one();
|
||||
}
|
||||
|
||||
template <typename Pred>
|
||||
std::optional<T> pop_if(Pred && pred)
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
|
||||
cv.wait(lock, [&]() { return !queue.empty() || closed; });
|
||||
|
||||
if (closed)
|
||||
throw sync_queue_closed{};
|
||||
|
||||
assert(!queue.empty());
|
||||
|
||||
if (pred(queue.front()))
|
||||
{
|
||||
T item = std::move(queue.front());
|
||||
queue.pop_front();
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
T pop()
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
|
||||
cv.wait(lock, [&]() { return !queue.empty() || closed; });
|
||||
|
||||
if (closed)
|
||||
throw sync_queue_closed{};
|
||||
|
||||
assert(!queue.empty());
|
||||
T item = std::move(queue.front());
|
||||
queue.pop_front();
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
template <typename Pred>
|
||||
void drop_until(Pred && pred)
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
|
||||
while (!queue.empty() && !pred(queue.front()))
|
||||
queue.pop_front();
|
||||
}
|
||||
|
||||
T & peek()
|
||||
{
|
||||
std::unique_lock lock(mutex);
|
||||
|
||||
cv.wait(lock, [&]() { return !queue.empty() || closed; });
|
||||
|
||||
if (closed)
|
||||
throw sync_queue_closed{};
|
||||
|
||||
assert(!queue.empty());
|
||||
return queue.front();
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
closed = true;
|
||||
cv.notify_all();
|
||||
}
|
||||
};
|
||||
} // namespace utils
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* 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 <cassert>
|
||||
#include <cxxabi.h>
|
||||
#include <string>
|
||||
|
||||
template <typename T>
|
||||
std::string type_name()
|
||||
{
|
||||
int status;
|
||||
char * demangled = abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, &status);
|
||||
assert(status == 0);
|
||||
|
||||
std::string s = demangled;
|
||||
free(demangled);
|
||||
return s;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* 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
|
||||
|
||||
#cmakedefine GIT_VERSION "@GIT_VERSION@"
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* 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 "buffer.h"
|
||||
#include "utils/check.h"
|
||||
|
||||
vk::buffer::buffer(VkDevice device, const VkBufferCreateInfo & create_info) :
|
||||
device(device)
|
||||
{
|
||||
CHECK_VK(vkCreateBuffer(device, &create_info, nullptr, &id));
|
||||
}
|
||||
|
||||
vk::buffer::~buffer()
|
||||
{
|
||||
if (device)
|
||||
vkDestroyBuffer(device, id, nullptr);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
namespace vk
|
||||
{
|
||||
class buffer : public utils::handle<VkBuffer>
|
||||
{
|
||||
VkDevice device{};
|
||||
|
||||
public:
|
||||
buffer() = default;
|
||||
buffer(VkDevice device, const VkBufferCreateInfo & create_info);
|
||||
buffer(const buffer &) = delete;
|
||||
buffer(buffer &&) = default;
|
||||
buffer & operator=(const buffer &) = delete;
|
||||
buffer & operator=(buffer &&) = default;
|
||||
~buffer();
|
||||
};
|
||||
} // namespace vk
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* 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 "buffer_view.h"
|
||||
#include "utils/check.h"
|
||||
|
||||
vk::buffer_view::buffer_view(VkDevice device, const VkBufferViewCreateInfo & create_info) :
|
||||
device(device)
|
||||
{
|
||||
CHECK_VK(vkCreateBufferView(device, &create_info, nullptr, &id));
|
||||
}
|
||||
|
||||
vk::buffer_view::~buffer_view()
|
||||
{
|
||||
if (device)
|
||||
vkDestroyBufferView(device, id, nullptr);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
namespace vk
|
||||
{
|
||||
class buffer_view : public utils::handle<VkBufferView>
|
||||
{
|
||||
VkDevice device{};
|
||||
|
||||
public:
|
||||
buffer_view() = default;
|
||||
buffer_view(VkDevice device, const VkBufferViewCreateInfo & create_info);
|
||||
buffer_view(const buffer_view &) = delete;
|
||||
buffer_view(buffer_view &&) = default;
|
||||
buffer_view & operator=(const buffer_view &) = delete;
|
||||
buffer_view & operator=(buffer_view &&) = default;
|
||||
~buffer_view();
|
||||
};
|
||||
} // namespace vk
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* 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 "command_pool.h"
|
||||
#include "vk.h"
|
||||
|
||||
vk::command_pool::command_pool(VkDevice device, uint32_t queueFamilyIndex) :
|
||||
device(device), lock(std::make_unique<std::mutex>())
|
||||
{
|
||||
VkCommandPoolCreateInfo cmdpool_create_info{};
|
||||
cmdpool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
||||
cmdpool_create_info.queueFamilyIndex = queueFamilyIndex;
|
||||
cmdpool_create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
|
||||
CHECK_VK(vkCreateCommandPool(device, &cmdpool_create_info, nullptr, &id));
|
||||
}
|
||||
|
||||
vk::command_pool::~command_pool()
|
||||
{
|
||||
if (device)
|
||||
vkDestroyCommandPool(device, id, nullptr);
|
||||
}
|
||||
|
||||
std::vector<VkCommandBuffer> vk::command_pool::allocate_command_buffers(uint32_t count, VkCommandBufferLevel level)
|
||||
{
|
||||
std::unique_lock _{*lock};
|
||||
|
||||
VkCommandBufferAllocateInfo alloc_info{};
|
||||
alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
|
||||
alloc_info.commandPool = id;
|
||||
alloc_info.level = level;
|
||||
alloc_info.commandBufferCount = count;
|
||||
|
||||
std::vector<VkCommandBuffer> command_buffers{count};
|
||||
CHECK_VK(vkAllocateCommandBuffers(device, &alloc_info, command_buffers.data()));
|
||||
|
||||
return command_buffers;
|
||||
}
|
||||
|
||||
VkCommandBuffer vk::command_pool::allocate_command_buffer(VkCommandBufferLevel level)
|
||||
{
|
||||
std::unique_lock _{*lock};
|
||||
|
||||
VkCommandBufferAllocateInfo alloc_info{};
|
||||
alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
|
||||
alloc_info.commandPool = id;
|
||||
alloc_info.level = level;
|
||||
alloc_info.commandBufferCount = 1;
|
||||
|
||||
VkCommandBuffer command_buffer;
|
||||
CHECK_VK(vkAllocateCommandBuffers(device, &alloc_info, &command_buffer));
|
||||
|
||||
return command_buffer;
|
||||
}
|
||||
|
||||
void vk::command_pool::free_command_buffers(const std::vector<VkCommandBuffer> & command_buffers)
|
||||
{
|
||||
std::unique_lock _{*lock};
|
||||
vkFreeCommandBuffers(device, id, command_buffers.size(), command_buffers.data());
|
||||
}
|
||||
|
||||
void vk::command_pool::free_command_buffer(VkCommandBuffer command_buffer)
|
||||
{
|
||||
if (command_buffer)
|
||||
{
|
||||
std::unique_lock _{*lock};
|
||||
vkFreeCommandBuffers(device, id, 1, &command_buffer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
namespace vk
|
||||
{
|
||||
class command_pool : public utils::handle<VkCommandPool>
|
||||
{
|
||||
VkDevice device{};
|
||||
std::unique_ptr<std::mutex> lock;
|
||||
|
||||
public:
|
||||
command_pool() = default;
|
||||
command_pool(VkDevice device, uint32_t queueFamilyIndex);
|
||||
|
||||
command_pool(const command_pool &) = delete;
|
||||
command_pool(command_pool &&) = default;
|
||||
command_pool & operator=(const command_pool &) = delete;
|
||||
command_pool & operator=(command_pool &&) = default;
|
||||
~command_pool();
|
||||
|
||||
std::vector<VkCommandBuffer> allocate_command_buffers(uint32_t count, VkCommandBufferLevel level = VK_COMMAND_BUFFER_LEVEL_PRIMARY);
|
||||
VkCommandBuffer allocate_command_buffer(VkCommandBufferLevel level = VK_COMMAND_BUFFER_LEVEL_PRIMARY);
|
||||
|
||||
void free_command_buffers(const std::vector<VkCommandBuffer> & command_buffers);
|
||||
void free_command_buffer(VkCommandBuffer command_buffer);
|
||||
};
|
||||
} // namespace vk
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 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/typename.h"
|
||||
#include "vk/vk.h"
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
namespace vk::details
|
||||
{
|
||||
|
||||
template <typename T>
|
||||
struct structure_traits_base
|
||||
{
|
||||
static constexpr inline VkStructureType type = static_cast<VkStructureType>(-1);
|
||||
using base = T;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct structure_traits : structure_traits_base<T>
|
||||
{};
|
||||
|
||||
template <typename T>
|
||||
constexpr inline VkStructureType structure_type = structure_traits<T>::type;
|
||||
|
||||
template <typename T, typename F, typename... Args>
|
||||
auto enumerate(F f, Args &&... args) -> auto
|
||||
{
|
||||
std::vector<T> array;
|
||||
uint32_t count;
|
||||
VkResult result;
|
||||
|
||||
result = f(std::forward<Args>(args)..., &count, nullptr);
|
||||
|
||||
if (result >= 0)
|
||||
{
|
||||
if constexpr (structure_type<T> == static_cast<VkStructureType>(-1))
|
||||
{
|
||||
array.resize(count);
|
||||
}
|
||||
else
|
||||
{
|
||||
T default_value{};
|
||||
default_value.type = structure_type<T>;
|
||||
array.resize(count, default_value);
|
||||
}
|
||||
result = f(std::forward<Args>(args)..., &count, reinterpret_cast<typename structure_traits<T>::base *>(array.data()));
|
||||
}
|
||||
|
||||
if (result < 0)
|
||||
{
|
||||
throw std::system_error(result, vk::error_category(), "enumerating " + type_name<T>());
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
} // namespace vk::details
|
||||
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* 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 "device_memory.h"
|
||||
#include "utils/check.h"
|
||||
|
||||
uint32_t vk::device_memory::get_memory_type(VkPhysicalDevice physical_device, VkMemoryRequirements requirements, VkMemoryPropertyFlags property_flags)
|
||||
{
|
||||
uint32_t types = requirements.memoryTypeBits;
|
||||
|
||||
VkPhysicalDeviceMemoryProperties memory_properties{};
|
||||
vkGetPhysicalDeviceMemoryProperties(physical_device, &memory_properties);
|
||||
|
||||
for (uint32_t type = 0; type < memory_properties.memoryTypeCount; ++type)
|
||||
{
|
||||
if (not((1 << type) & types))
|
||||
continue;
|
||||
|
||||
const auto & properties = memory_properties.memoryTypes[type];
|
||||
if ((properties.propertyFlags & property_flags) == property_flags)
|
||||
return type;
|
||||
}
|
||||
|
||||
throw std::runtime_error{"No Vulkan memory with required flags"};
|
||||
}
|
||||
|
||||
vk::device_memory::device_memory(VkDevice device, const VkMemoryAllocateInfo & allocate_info) :
|
||||
device(device)
|
||||
{
|
||||
CHECK_VK(vkAllocateMemory(device, &allocate_info, nullptr, &id));
|
||||
}
|
||||
|
||||
vk::device_memory::device_memory(VkDevice device, VkPhysicalDevice physical_device, VkImage target_image, VkMemoryPropertyFlags properties) :
|
||||
device(device)
|
||||
{
|
||||
VkMemoryRequirements requirements;
|
||||
vkGetImageMemoryRequirements(device, target_image, &requirements);
|
||||
|
||||
uint32_t memory_type = get_memory_type(physical_device, requirements, properties);
|
||||
|
||||
VkMemoryDedicatedAllocateInfoKHR dedicated_allocate_info{};
|
||||
dedicated_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
|
||||
dedicated_allocate_info.image = target_image;
|
||||
|
||||
VkMemoryAllocateInfo memory_allocate_info{};
|
||||
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
memory_allocate_info.allocationSize = requirements.size;
|
||||
memory_allocate_info.memoryTypeIndex = memory_type;
|
||||
memory_allocate_info.pNext = &dedicated_allocate_info;
|
||||
|
||||
CHECK_VK(vkAllocateMemory(device, &memory_allocate_info, nullptr, &id));
|
||||
|
||||
try
|
||||
{
|
||||
CHECK_VK(vkBindImageMemory(device, target_image, id, 0));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
vkFreeMemory(device, id, nullptr);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
vk::device_memory::device_memory(VkDevice device, VkPhysicalDevice physical_device, VkBuffer target_buffer, VkMemoryPropertyFlags properties) :
|
||||
device(device)
|
||||
{
|
||||
VkMemoryRequirements requirements;
|
||||
vkGetBufferMemoryRequirements(device, target_buffer, &requirements);
|
||||
|
||||
uint32_t memory_type = get_memory_type(physical_device, requirements, properties);
|
||||
|
||||
VkMemoryDedicatedAllocateInfoKHR dedicated_allocate_info{};
|
||||
dedicated_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
|
||||
dedicated_allocate_info.buffer = target_buffer;
|
||||
|
||||
VkMemoryAllocateInfo memory_allocate_info{};
|
||||
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
memory_allocate_info.allocationSize = requirements.size;
|
||||
memory_allocate_info.memoryTypeIndex = memory_type;
|
||||
memory_allocate_info.pNext = &dedicated_allocate_info;
|
||||
|
||||
CHECK_VK(vkAllocateMemory(device, &memory_allocate_info, nullptr, &id));
|
||||
|
||||
try
|
||||
{
|
||||
CHECK_VK(vkBindBufferMemory(device, target_buffer, id, 0));
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
vkFreeMemory(device, id, nullptr);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
vk::device_memory::~device_memory()
|
||||
{
|
||||
if (device)
|
||||
{
|
||||
if (id and map)
|
||||
{
|
||||
vkUnmapMemory(device, id);
|
||||
}
|
||||
vkFreeMemory(device, id, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
void vk::device_memory::map_memory()
|
||||
{
|
||||
CHECK_VK(vkMapMemory(device, id, 0, VK_WHOLE_SIZE, 0, (void **)&map));
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
namespace vk
|
||||
{
|
||||
class device_memory : public utils::handle<VkDeviceMemory>
|
||||
{
|
||||
VkDevice device{};
|
||||
void * map = nullptr;
|
||||
|
||||
public:
|
||||
device_memory() = default;
|
||||
device_memory(VkDevice device, const VkMemoryAllocateInfo & allocate_info);
|
||||
device_memory(VkDevice device, VkPhysicalDevice physical_device, VkImage target_image, VkMemoryPropertyFlags properties);
|
||||
|
||||
device_memory(VkDevice device, VkPhysicalDevice physical_device, VkBuffer target_buffer, VkMemoryPropertyFlags properties);
|
||||
|
||||
device_memory(const device_memory &) = delete;
|
||||
device_memory(device_memory &&) = default;
|
||||
device_memory & operator=(const device_memory &) = delete;
|
||||
device_memory & operator=(device_memory &&) = default;
|
||||
~device_memory();
|
||||
|
||||
void * data()
|
||||
{
|
||||
return map;
|
||||
}
|
||||
|
||||
void map_memory();
|
||||
|
||||
static uint32_t get_memory_type(VkPhysicalDevice physical_device, VkMemoryRequirements requirements, VkMemoryPropertyFlags property_flags);
|
||||
};
|
||||
} // namespace vk
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* 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 "utils/check.h"
|
||||
#include "vk.h"
|
||||
#include <system_error>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct : std::error_category
|
||||
{
|
||||
const char * name() const noexcept override
|
||||
{
|
||||
return "vulkan";
|
||||
}
|
||||
|
||||
std::string message(int condition) const override
|
||||
{
|
||||
return string_VkResult(static_cast<VkResult>(condition));
|
||||
}
|
||||
} vulkan_error_category;
|
||||
} // namespace
|
||||
|
||||
const std::error_category & vk::error_category()
|
||||
{
|
||||
return vulkan_error_category;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* 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 "image.h"
|
||||
#include "utils/check.h"
|
||||
|
||||
vk::image::image(VkDevice device, const VkImageCreateInfo & create_info) :
|
||||
device(device)
|
||||
{
|
||||
CHECK_VK(vkCreateImage(device, &create_info, nullptr, &id));
|
||||
}
|
||||
|
||||
vk::image::~image()
|
||||
{
|
||||
if (device)
|
||||
vkDestroyImage(device, id, nullptr);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
namespace vk
|
||||
{
|
||||
class image : public utils::handle<VkImage>
|
||||
{
|
||||
VkDevice device{};
|
||||
|
||||
public:
|
||||
image() = default;
|
||||
image(VkDevice device, const VkImageCreateInfo & create_info);
|
||||
image(const image &) = delete;
|
||||
image(image &&) = default;
|
||||
image & operator=(const image &) = delete;
|
||||
image & operator=(image &&) = default;
|
||||
~image();
|
||||
};
|
||||
} // namespace vk
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* 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 "pipeline.h"
|
||||
|
||||
#include "vk.h"
|
||||
|
||||
vk::pipeline::pipeline(VkDevice device, vk::pipeline::graphics_info & create_info, const VkPipelineLayout layout) :
|
||||
device(device)
|
||||
{
|
||||
for (VkPipelineShaderStageCreateInfo & i: create_info.shader_stages)
|
||||
{
|
||||
i.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
|
||||
}
|
||||
|
||||
create_info.InputAssemblyState.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||||
create_info.RasterizationState.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
|
||||
create_info.MultisampleState.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
|
||||
create_info.DepthStencilState.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
|
||||
create_info.ColorBlendState.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
|
||||
|
||||
VkPipelineVertexInputStateCreateInfo VertexInputState{
|
||||
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
|
||||
.vertexBindingDescriptionCount = (uint32_t)create_info.vertex_input_bindings.size(),
|
||||
.pVertexBindingDescriptions = create_info.vertex_input_bindings.data(),
|
||||
.vertexAttributeDescriptionCount = (uint32_t)create_info.vertex_input_attributes.size(),
|
||||
.pVertexAttributeDescriptions = create_info.vertex_input_attributes.data(),
|
||||
};
|
||||
|
||||
VkPipelineDynamicStateCreateInfo DynamicState{
|
||||
.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
|
||||
.dynamicStateCount = (uint32_t)create_info.dynamic_states.size(),
|
||||
.pDynamicStates = create_info.dynamic_states.data()};
|
||||
|
||||
VkPipelineViewportStateCreateInfo ViewportState{
|
||||
.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
|
||||
.viewportCount = (uint32_t)create_info.viewports.size(),
|
||||
.pViewports = create_info.viewports.data(),
|
||||
.scissorCount = (uint32_t)create_info.scissors.size(),
|
||||
.pScissors = create_info.scissors.data(),
|
||||
};
|
||||
|
||||
VkGraphicsPipelineCreateInfo info{};
|
||||
info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
|
||||
info.stageCount = create_info.shader_stages.size();
|
||||
info.pStages = create_info.shader_stages.data();
|
||||
info.pVertexInputState = &VertexInputState;
|
||||
info.pInputAssemblyState = &create_info.InputAssemblyState;
|
||||
info.pViewportState = &ViewportState;
|
||||
info.pRasterizationState = &create_info.RasterizationState;
|
||||
info.pMultisampleState = &create_info.MultisampleState;
|
||||
info.pColorBlendState = &create_info.ColorBlendState;
|
||||
info.layout = layout;
|
||||
info.renderPass = create_info.renderPass;
|
||||
info.subpass = create_info.subpass;
|
||||
|
||||
if (DynamicState.dynamicStateCount > 0)
|
||||
info.pDynamicState = &DynamicState;
|
||||
|
||||
CHECK_VK(vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &info, nullptr, &id));
|
||||
}
|
||||
|
||||
vk::pipeline::~pipeline()
|
||||
{
|
||||
if (device)
|
||||
vkDestroyPipeline(device, id, nullptr);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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 "pipeline_layout.h"
|
||||
#include "utils/handle.h"
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
namespace vk
|
||||
{
|
||||
class pipeline : public utils::handle<VkPipeline>
|
||||
{
|
||||
VkDevice device{};
|
||||
|
||||
public:
|
||||
struct graphics_info
|
||||
{
|
||||
std::vector<VkPipelineShaderStageCreateInfo> shader_stages;
|
||||
std::vector<VkVertexInputBindingDescription> vertex_input_bindings;
|
||||
std::vector<VkVertexInputAttributeDescription> vertex_input_attributes;
|
||||
VkPipelineInputAssemblyStateCreateInfo InputAssemblyState{};
|
||||
// VkPipelineTessellationStateCreateInfo TessellationState;
|
||||
std::vector<VkViewport> viewports;
|
||||
std::vector<VkRect2D> scissors;
|
||||
VkPipelineRasterizationStateCreateInfo RasterizationState{};
|
||||
VkPipelineMultisampleStateCreateInfo MultisampleState{};
|
||||
VkPipelineDepthStencilStateCreateInfo DepthStencilState{};
|
||||
VkPipelineColorBlendStateCreateInfo ColorBlendState{};
|
||||
std::vector<VkDynamicState> dynamic_states;
|
||||
VkRenderPass renderPass{};
|
||||
uint32_t subpass{};
|
||||
};
|
||||
|
||||
pipeline() = default;
|
||||
pipeline(VkDevice device, graphics_info & create_info, VkPipelineLayout layout);
|
||||
pipeline(const pipeline &) = delete;
|
||||
pipeline(pipeline &&) = default;
|
||||
pipeline & operator=(const pipeline &) = delete;
|
||||
pipeline & operator=(pipeline &&) = default;
|
||||
~pipeline();
|
||||
};
|
||||
} // namespace vk
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* 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 "pipeline_layout.h"
|
||||
#include "utils/check.h"
|
||||
|
||||
vk::pipeline_layout::pipeline_layout(VkDevice device, const info & create_info) :
|
||||
device(device)
|
||||
{
|
||||
VkPipelineLayoutCreateInfo plci{
|
||||
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
|
||||
.setLayoutCount = (uint32_t)create_info.descriptor_set_layouts.size(),
|
||||
.pSetLayouts = create_info.descriptor_set_layouts.data(),
|
||||
.pushConstantRangeCount = (uint32_t)create_info.push_constant_ranges.size(),
|
||||
.pPushConstantRanges = create_info.push_constant_ranges.data()};
|
||||
CHECK_VK(vkCreatePipelineLayout(device, &plci, nullptr, &id));
|
||||
}
|
||||
|
||||
vk::pipeline_layout::~pipeline_layout()
|
||||
{
|
||||
if (device)
|
||||
vkDestroyPipelineLayout(device, id, nullptr);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
namespace vk
|
||||
{
|
||||
class pipeline_layout : public utils::handle<VkPipelineLayout>
|
||||
{
|
||||
VkDevice device{};
|
||||
|
||||
public:
|
||||
struct info
|
||||
{
|
||||
std::vector<VkDescriptorSetLayout> descriptor_set_layouts;
|
||||
std::vector<VkPushConstantRange> push_constant_ranges;
|
||||
};
|
||||
|
||||
~pipeline_layout();
|
||||
pipeline_layout() = default;
|
||||
pipeline_layout(VkDevice device, const info & create_info);
|
||||
pipeline_layout(const pipeline_layout &) = delete;
|
||||
pipeline_layout(pipeline_layout &&) = default;
|
||||
pipeline_layout & operator=(const pipeline_layout &) = delete;
|
||||
pipeline_layout & operator=(pipeline_layout &&) = default;
|
||||
};
|
||||
} // namespace vk
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* 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 "renderpass.h"
|
||||
|
||||
#include "vk/vk.h"
|
||||
|
||||
vk::renderpass::renderpass(VkDevice device, info & create_info) :
|
||||
device(device)
|
||||
{
|
||||
VkRenderPassCreateInfo renderpass_create_info{};
|
||||
renderpass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
|
||||
renderpass_create_info.attachmentCount = create_info.attachments.size();
|
||||
renderpass_create_info.pAttachments = create_info.attachments.data();
|
||||
renderpass_create_info.subpassCount = create_info.subpasses.size();
|
||||
renderpass_create_info.pSubpasses = create_info.subpasses.data();
|
||||
renderpass_create_info.dependencyCount = create_info.dependencies.size();
|
||||
renderpass_create_info.pDependencies = create_info.dependencies.data();
|
||||
|
||||
CHECK_VK(vkCreateRenderPass(device, &renderpass_create_info, nullptr, &id));
|
||||
}
|
||||
|
||||
vk::renderpass::~renderpass()
|
||||
{
|
||||
if (device)
|
||||
vkDestroyRenderPass(device, id, nullptr);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
namespace vk
|
||||
{
|
||||
class renderpass : public utils::handle<VkRenderPass>
|
||||
{
|
||||
VkDevice device{};
|
||||
|
||||
public:
|
||||
struct info
|
||||
{
|
||||
std::vector<VkAttachmentDescription> attachments;
|
||||
std::vector<VkSubpassDescription> subpasses;
|
||||
std::vector<VkSubpassDependency> dependencies;
|
||||
};
|
||||
|
||||
renderpass() = default;
|
||||
renderpass(VkDevice device, info & create_info);
|
||||
renderpass(const renderpass &) = delete;
|
||||
renderpass(renderpass &&) = default;
|
||||
renderpass & operator=(const renderpass &) = delete;
|
||||
renderpass & operator=(renderpass &&) = default;
|
||||
~renderpass();
|
||||
};
|
||||
} // namespace vk
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* 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 "shader.h"
|
||||
|
||||
#include "vk.h"
|
||||
|
||||
vk::shader::shader(VkDevice device, const std::vector<uint32_t> & spirv) :
|
||||
device(device)
|
||||
{
|
||||
VkShaderModuleCreateInfo create_info{};
|
||||
create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
|
||||
create_info.pCode = data(spirv);
|
||||
create_info.codeSize = spirv.size() * sizeof(uint32_t);
|
||||
|
||||
CHECK_VK(vkCreateShaderModule(device, &create_info, nullptr, &id));
|
||||
}
|
||||
|
||||
vk::shader::shader(VkDevice device, const std::string & name) :
|
||||
shader(device, shaders.at(name)) {}
|
||||
|
||||
vk::shader::~shader()
|
||||
{
|
||||
if (device)
|
||||
vkDestroyShaderModule(device, id, nullptr);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
extern const std::map<std::string, std::vector<uint32_t>> shaders;
|
||||
|
||||
namespace vk
|
||||
{
|
||||
class shader : public utils::handle<VkShaderModule>
|
||||
{
|
||||
VkDevice device;
|
||||
|
||||
public:
|
||||
shader(VkDevice device, const std::vector<uint32_t> & spirv);
|
||||
shader(VkDevice device, const std::string & name);
|
||||
shader(shader &&) = default;
|
||||
shader & operator=(shader &&) = default;
|
||||
shader(const shader &) = delete;
|
||||
shader operator=(const shader &) = delete;
|
||||
~shader();
|
||||
};
|
||||
} // namespace vk
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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 "external/magic_enum.hpp"
|
||||
#include "utils/check.h"
|
||||
#include "vk/buffer.h"
|
||||
#include "vk/buffer_view.h"
|
||||
#include "vk/command_pool.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/image.h"
|
||||
#include "vk/pipeline.h"
|
||||
#include "vk/renderpass.h"
|
||||
#include "vk/shader.h"
|
||||
#include <string>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#if __has_include(<vulkan/vk_enum_string_helper.h>)
|
||||
#include <vulkan/vk_enum_string_helper.h>
|
||||
#else
|
||||
#define string_VkFormat(x) std::string(magic_enum::enum_name((VkFormat)(x)))
|
||||
#endif
|
||||
|
||||
template <>
|
||||
struct magic_enum::customize::enum_range<VkFormat>
|
||||
{
|
||||
static constexpr int min = 0;
|
||||
static constexpr int max = 200;
|
||||
};
|
||||
|
||||
template <typename... Args>
|
||||
struct vk_chain
|
||||
{
|
||||
std::tuple<Args...> structs;
|
||||
};
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* 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 "wivrn_client.h"
|
||||
#include "spdlog/common.h"
|
||||
#include "version.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include "wivrn_serialization.h"
|
||||
#include <algorithm>
|
||||
#include <arpa/inet.h>
|
||||
#include <ifaddrs.h>
|
||||
#include <linux/ipv6.h>
|
||||
#include <net/if.h>
|
||||
#include <poll.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <stdexcept>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
static std::vector<std::pair<int, std::string>> get_network_interfaces()
|
||||
{
|
||||
ifaddrs * addresses;
|
||||
if (getifaddrs(&addresses) < 0)
|
||||
{
|
||||
spdlog::warn("Cannot get network interfaces: {}", strerror(errno));
|
||||
return {};
|
||||
}
|
||||
|
||||
int fd = socket(AF_INET6, SOCK_DGRAM, 0);
|
||||
|
||||
const int required_flags = IFF_UP | IFF_MULTICAST;
|
||||
const int forbidden_flags = IFF_LOOPBACK;
|
||||
|
||||
std::vector<std::pair<int, std::string>> interfaces;
|
||||
for (ifaddrs * i = addresses; i; i = i->ifa_next)
|
||||
{
|
||||
if (i->ifa_addr == nullptr)
|
||||
continue;
|
||||
|
||||
if (i->ifa_addr->sa_family != AF_INET6)
|
||||
continue;
|
||||
|
||||
if ((i->ifa_flags & required_flags) != required_flags)
|
||||
continue;
|
||||
|
||||
if ((i->ifa_flags & forbidden_flags) != 0)
|
||||
continue;
|
||||
|
||||
if (std::any_of(interfaces.begin(), interfaces.end(), [&](const auto & j) { return j.second == i->ifa_name; }))
|
||||
continue;
|
||||
|
||||
ifreq interface {};
|
||||
strncpy(interface.ifr_name, i->ifa_name, sizeof(interface.ifr_name) - 1);
|
||||
ioctl(fd, SIOCGIFINDEX, &interface);
|
||||
|
||||
interfaces.emplace_back(interface.ifr_ifindex, i->ifa_name);
|
||||
}
|
||||
|
||||
close(fd);
|
||||
freeifaddrs(addresses);
|
||||
|
||||
return interfaces;
|
||||
}
|
||||
|
||||
wivrn_client::wivrn_client() :
|
||||
listener(control_port)
|
||||
{
|
||||
auto interfaces = get_network_interfaces();
|
||||
|
||||
if (interfaces.empty())
|
||||
{
|
||||
spdlog::critical("No suitable network interface found");
|
||||
throw std::runtime_error("No suitable network interface found"); // TODO class exception
|
||||
}
|
||||
|
||||
for (auto [id, name]: interfaces)
|
||||
{
|
||||
auto & socket = broadcasters.emplace_back();
|
||||
if (setsockopt(socket.get_fd(), IPPROTO_IPV6, IPV6_MULTICAST_IF, &id, sizeof(id)) < 0)
|
||||
{
|
||||
spdlog::error("setsockopt: {}", strerror(errno));
|
||||
}
|
||||
|
||||
spdlog::info("Starting multicaster on {}", name);
|
||||
socket.connect(announce_address, announce_port);
|
||||
}
|
||||
}
|
||||
|
||||
wivrn_session::wivrn_session(xrt::drivers::wivrn::TCP && tcp, in6_addr address) :
|
||||
control(std::move(tcp)), stream()
|
||||
{
|
||||
stream.bind(stream_port);
|
||||
stream.connect(address, stream_port);
|
||||
stream.set_receive_buffer_size(1024 * 1024 * 5);
|
||||
}
|
||||
|
||||
std::unique_ptr<wivrn_session> wivrn_client::poll()
|
||||
{
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
|
||||
auto time_since_last_broadcast = now - last_broadcast;
|
||||
|
||||
if (time_since_last_broadcast >= 1s)
|
||||
{
|
||||
last_broadcast = now;
|
||||
|
||||
details::hash_context h;
|
||||
serialization_traits<from_headset::control_packets>::type_hash(h);
|
||||
serialization_traits<to_headset::control_packets>::type_hash(h);
|
||||
serialization_traits<from_headset::stream_packets>::type_hash(h);
|
||||
serialization_traits<to_headset::stream_packets>::type_hash(h);
|
||||
|
||||
from_headset::client_announce_packet packet{
|
||||
.magic = from_headset::client_announce_packet::magic_value,
|
||||
.client_version = "WiVRn " GIT_VERSION,
|
||||
.protocol_hash = h.hash,
|
||||
};
|
||||
|
||||
for (auto & i: broadcasters)
|
||||
i.send(packet);
|
||||
}
|
||||
|
||||
pollfd fds{};
|
||||
fds.events = POLLIN;
|
||||
fds.fd = listener.get_fd();
|
||||
|
||||
int r = ::poll(&fds, 1, 0);
|
||||
if (r < 0)
|
||||
throw std::system_error(errno, std::system_category());
|
||||
|
||||
if (r > 0 && (fds.revents & POLLIN))
|
||||
{
|
||||
auto [tcp, addr] = listener.accept();
|
||||
char buffer[100];
|
||||
spdlog::info("Connection from {}", inet_ntop(AF_INET6, &addr.sin6_addr, buffer, sizeof(buffer)));
|
||||
return std::make_unique<wivrn_session>(std::move(tcp), addr.sin6_addr);
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void wivrn_session::send_control(const from_headset::control_packets & packet)
|
||||
{
|
||||
control.send(packet);
|
||||
}
|
||||
|
||||
void wivrn_session::send_stream(const from_headset::stream_packets & packet)
|
||||
{
|
||||
stream.send(packet);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* 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 "wivrn_packets.h"
|
||||
#include "wivrn_sockets.h"
|
||||
#include <memory>
|
||||
#include <poll.h>
|
||||
|
||||
using namespace xrt::drivers::wivrn;
|
||||
|
||||
class wivrn_session;
|
||||
|
||||
class wivrn_client
|
||||
{
|
||||
using broadcast_socket = typed_socket<UDP, void, from_headset::client_announce_packet>;
|
||||
|
||||
std::vector<broadcast_socket> broadcasters;
|
||||
TCPListener listener;
|
||||
|
||||
std::chrono::steady_clock::time_point last_broadcast{};
|
||||
|
||||
public:
|
||||
wivrn_client();
|
||||
std::unique_ptr<wivrn_session> poll();
|
||||
};
|
||||
|
||||
class wivrn_session
|
||||
{
|
||||
typed_socket<TCP, to_headset::control_packets, from_headset::control_packets> control;
|
||||
typed_socket<UDP, to_headset::stream_packets, from_headset::stream_packets> stream;
|
||||
|
||||
public:
|
||||
wivrn_session(TCP && tcp, in6_addr address);
|
||||
wivrn_session(const wivrn_session &) = delete;
|
||||
wivrn_session & operator=(const wivrn_session &) = delete;
|
||||
|
||||
void send_control(const from_headset::control_packets & packet);
|
||||
void send_stream(const from_headset::stream_packets & packet);
|
||||
|
||||
template <typename T>
|
||||
int poll(T && visitor, std::chrono::milliseconds timeout)
|
||||
{
|
||||
pollfd fds[2] = {};
|
||||
fds[0].events = POLLIN;
|
||||
fds[0].fd = stream.get_fd();
|
||||
fds[1].events = POLLIN;
|
||||
fds[1].fd = control.get_fd();
|
||||
|
||||
int r = ::poll(fds, std::size(fds), timeout.count());
|
||||
if (r < 0)
|
||||
throw std::system_error(errno, std::system_category());
|
||||
|
||||
if (fds[0].revents & (POLLHUP | POLLERR))
|
||||
throw std::runtime_error("Error on stream socket");
|
||||
|
||||
if (fds[1].revents & (POLLHUP | POLLERR))
|
||||
throw std::runtime_error("Error on control socket");
|
||||
|
||||
if (fds[0].revents & POLLIN)
|
||||
{
|
||||
auto packet = stream.receive();
|
||||
if (packet)
|
||||
std::visit(std::forward<T>(visitor), std::move(*packet));
|
||||
}
|
||||
|
||||
if (fds[1].revents & POLLIN)
|
||||
{
|
||||
auto packet = control.receive();
|
||||
if (packet)
|
||||
std::visit(std::forward<T>(visitor), std::move(*packet));
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,277 @@
|
||||
/*
|
||||
* 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 <array>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <netinet/in.h>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
|
||||
static const int announce_port = 9756;
|
||||
static const int control_port = 9757;
|
||||
static const int stream_port = 9757;
|
||||
static const in6_addr announce_address = []() {
|
||||
in6_addr address{};
|
||||
|
||||
address.s6_addr[0] = 0xff; // multicast
|
||||
address.s6_addr[1] = 0x15; // not assigned by IANA, site-local
|
||||
|
||||
address.s6_addr[11] = 'W';
|
||||
address.s6_addr[12] = 'i';
|
||||
address.s6_addr[13] = 'V';
|
||||
address.s6_addr[14] = 'R';
|
||||
address.s6_addr[15] = 'n';
|
||||
return address;
|
||||
}();
|
||||
|
||||
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_GRIP, // /user/hand/left/input/grip/pose
|
||||
LEFT_AIM, // /user/hand/left/input/aim/pose
|
||||
RIGHT_GRIP, // /user/hand/right/input/grip/pose
|
||||
RIGHT_AIM, // /user/hand/right/input/aim/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_VALUE, // /user/hand/left/input/squeeze/value
|
||||
LEFT_TRIGGER_VALUE, // /user/hand/left/input/trigger/value
|
||||
LEFT_TRIGGER_TOUCH, // /user/hand/left/input/trigger/touch
|
||||
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
|
||||
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_VALUE, // /user/hand/right/input/squeeze/value
|
||||
RIGHT_TRIGGER_VALUE, // /user/hand/right/input/trigger/value
|
||||
RIGHT_TRIGGER_TOUCH, // /user/hand/right/input/trigger/touch
|
||||
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
|
||||
};
|
||||
|
||||
enum video_codec
|
||||
{
|
||||
h264,
|
||||
hevc,
|
||||
h265 = hevc,
|
||||
};
|
||||
|
||||
namespace from_headset
|
||||
{
|
||||
|
||||
struct client_announce_packet
|
||||
{
|
||||
static const constexpr std::array<char, 5> magic_value = {'W', 'i', 'V', 'R', 'n'};
|
||||
// Broadcast on the announce port, not typed
|
||||
std::array<char, 5> magic;
|
||||
|
||||
std::string client_version;
|
||||
uint64_t protocol_hash;
|
||||
};
|
||||
|
||||
struct headset_info_packet
|
||||
{
|
||||
// First packet sent by the HMD on the control socket, not typed
|
||||
uint32_t recommended_eye_width;
|
||||
uint32_t recommended_eye_height;
|
||||
std::vector<float> available_refresh_rates;
|
||||
float preferred_refresh_rate;
|
||||
uint32_t microphone_sample_rate;
|
||||
};
|
||||
|
||||
struct tracking
|
||||
{
|
||||
enum flags : uint8_t
|
||||
{
|
||||
orientation_valid = 1 << 0,
|
||||
position_valid = 1 << 1,
|
||||
linear_velocity_valid = 1 << 2,
|
||||
angular_velocity_valid = 1 << 3,
|
||||
orientation_tracked = 1 << 4,
|
||||
position_tracked = 1 << 5
|
||||
};
|
||||
|
||||
struct pose
|
||||
{
|
||||
device_id device;
|
||||
XrPosef pose;
|
||||
XrVector3f linear_velocity;
|
||||
XrVector3f angular_velocity;
|
||||
uint8_t flags;
|
||||
};
|
||||
|
||||
struct view
|
||||
{
|
||||
// Relative to XR_REFERENCE_SPACE_TYPE_VIEW
|
||||
XrPosef pose;
|
||||
XrFovf fov;
|
||||
};
|
||||
|
||||
uint64_t timestamp;
|
||||
XrViewStateFlags flags;
|
||||
|
||||
std::array<view, 2> views;
|
||||
std::vector<pose> device_poses;
|
||||
};
|
||||
|
||||
struct inputs
|
||||
{
|
||||
struct input_value
|
||||
{
|
||||
device_id id;
|
||||
float value;
|
||||
};
|
||||
std::vector<input_value> values;
|
||||
};
|
||||
|
||||
struct timesync_response
|
||||
{
|
||||
std::chrono::nanoseconds query;
|
||||
uint64_t response;
|
||||
};
|
||||
|
||||
struct feedback
|
||||
{
|
||||
uint64_t frame_index;
|
||||
uint8_t stream_index;
|
||||
|
||||
// Timestamps
|
||||
uint64_t received_first_packet;
|
||||
uint64_t received_last_packet;
|
||||
uint64_t reconstructed;
|
||||
uint64_t sent_to_decoder;
|
||||
uint64_t received_from_decoder;
|
||||
uint64_t blitted;
|
||||
uint64_t displayed;
|
||||
|
||||
std::array<XrPosef, 2> received_pose;
|
||||
std::array<XrPosef, 2> real_pose;
|
||||
|
||||
uint8_t data_packets;
|
||||
uint8_t parity_packets;
|
||||
uint8_t received_data_packets;
|
||||
uint8_t received_parity_packets;
|
||||
};
|
||||
|
||||
using control_packets = std::variant<headset_info_packet, feedback>;
|
||||
using stream_packets = std::variant<tracking, inputs, timesync_response>;
|
||||
} // namespace from_headset
|
||||
|
||||
namespace to_headset
|
||||
{
|
||||
|
||||
struct video_stream_description
|
||||
{
|
||||
struct item
|
||||
{
|
||||
uint16_t width;
|
||||
uint16_t height;
|
||||
uint16_t offset_x;
|
||||
uint16_t offset_y;
|
||||
video_codec codec;
|
||||
};
|
||||
uint16_t width;
|
||||
uint16_t height;
|
||||
float fps;
|
||||
std::vector<item> items;
|
||||
};
|
||||
|
||||
struct video_stream_data_shard
|
||||
{
|
||||
inline static const size_t max_payload_size = 1400;
|
||||
enum flags : uint8_t
|
||||
{
|
||||
start_of_slice = 1,
|
||||
end_of_slice = 1 << 1,
|
||||
end_of_frame = 1 << 2,
|
||||
};
|
||||
// Identifier of stream in video_stream_description
|
||||
uint8_t stream_item_idx;
|
||||
// Counter increased for each frame
|
||||
uint64_t frame_idx;
|
||||
// Identifier of the shard within the frame
|
||||
uint16_t shard_idx;
|
||||
uint8_t flags;
|
||||
|
||||
// Actual video data, may contain multiple NAL units
|
||||
std::vector<uint8_t> payload;
|
||||
|
||||
// Position information, must be present on last video shard
|
||||
struct view_info_t
|
||||
{
|
||||
// ns in headset time referential
|
||||
uint64_t display_time;
|
||||
|
||||
std::array<XrPosef, 2> pose;
|
||||
std::array<XrFovf, 2> fov;
|
||||
};
|
||||
std::optional<view_info_t> view_info;
|
||||
};
|
||||
|
||||
struct video_stream_parity_shard
|
||||
{
|
||||
uint8_t stream_item_idx;
|
||||
uint64_t frame_idx;
|
||||
uint16_t data_shard_count;
|
||||
uint8_t num_parity_elements;
|
||||
uint8_t parity_element;
|
||||
// Parity data
|
||||
std::vector<uint8_t> payload;
|
||||
};
|
||||
|
||||
struct haptics
|
||||
{
|
||||
device_id id;
|
||||
std::chrono::nanoseconds duration;
|
||||
float frequency;
|
||||
float amplitude;
|
||||
};
|
||||
|
||||
struct timesync_query
|
||||
{
|
||||
std::chrono::nanoseconds query;
|
||||
};
|
||||
|
||||
using stream_packets = std::variant<video_stream_data_shard, video_stream_parity_shard, haptics, timesync_query>;
|
||||
using control_packets = std::variant<video_stream_description>;
|
||||
|
||||
} // namespace to_headset
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,519 @@
|
||||
/*
|
||||
* 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 "boost/pfr/core.hpp"
|
||||
#include "boost/pfr/tuple_size.hpp"
|
||||
#include <array>
|
||||
#include <boost/pfr.hpp>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
|
||||
namespace details
|
||||
{
|
||||
struct hash_context
|
||||
{
|
||||
// FNV1a hash
|
||||
static const uint64_t fnv_prime = 0x100000001b3;
|
||||
static const uint64_t fnv_offset_basis = 0xcbf29ce484222325;
|
||||
uint64_t hash = fnv_offset_basis;
|
||||
|
||||
constexpr uint64_t feed(std::string_view s)
|
||||
{
|
||||
for (const char c: s)
|
||||
hash = (hash ^ c) * fnv_prime;
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
constexpr uint64_t feed_unsigned(uint64_t n)
|
||||
{
|
||||
if (n >= 10)
|
||||
feed(n / 10);
|
||||
|
||||
char digit[] = "0";
|
||||
digit[0] += n % 10;
|
||||
feed(digit);
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
constexpr uint64_t feed(int64_t n)
|
||||
{
|
||||
if (n < 0)
|
||||
{
|
||||
feed("-");
|
||||
feed_unsigned(static_cast<uint64_t>(-n));
|
||||
}
|
||||
else
|
||||
{
|
||||
feed_unsigned(static_cast<uint64_t>(n));
|
||||
}
|
||||
|
||||
return hash;
|
||||
}
|
||||
};
|
||||
} // namespace details
|
||||
|
||||
template <typename T, typename Enable = void>
|
||||
struct serialization_traits;
|
||||
|
||||
class deserialization_error : public std::runtime_error
|
||||
{
|
||||
public:
|
||||
deserialization_error() :
|
||||
std::runtime_error("Deserialization error") {}
|
||||
};
|
||||
|
||||
class serialization_packet
|
||||
{
|
||||
std::vector<uint8_t> buffer;
|
||||
|
||||
public:
|
||||
serialization_packet() = default;
|
||||
|
||||
void write(const void * data, size_t size)
|
||||
{
|
||||
size_t index = buffer.size();
|
||||
buffer.resize(index + size);
|
||||
memcpy(&buffer[index], data, size);
|
||||
}
|
||||
|
||||
const uint8_t * data() const
|
||||
{
|
||||
return buffer.data();
|
||||
}
|
||||
size_t size() const
|
||||
{
|
||||
return buffer.size();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void serialize(const T & value)
|
||||
{
|
||||
serialization_traits<T>::serialize(value, *this);
|
||||
}
|
||||
|
||||
operator std::vector<uint8_t> &&() &&
|
||||
{
|
||||
return std::move(buffer);
|
||||
}
|
||||
};
|
||||
|
||||
class deserialization_packet
|
||||
{
|
||||
std::vector<uint8_t> buffer;
|
||||
size_t read_index;
|
||||
|
||||
public:
|
||||
deserialization_packet() :
|
||||
read_index(0) {}
|
||||
explicit deserialization_packet(std::vector<uint8_t> buffer, size_t skip = 0) :
|
||||
buffer(std::move(buffer)), read_index(skip)
|
||||
{}
|
||||
|
||||
void read(void * data, size_t size)
|
||||
{
|
||||
check_remaining_size(size);
|
||||
|
||||
memcpy(data, &buffer[read_index], size);
|
||||
read_index += size;
|
||||
}
|
||||
|
||||
size_t remaining() const
|
||||
{
|
||||
return buffer.size() - read_index;
|
||||
}
|
||||
|
||||
bool empty() const
|
||||
{
|
||||
return buffer.size() <= read_index;
|
||||
}
|
||||
|
||||
void check_remaining_size(size_t min_size) const
|
||||
{
|
||||
if (min_size > remaining())
|
||||
throw deserialization_error();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T deserialize()
|
||||
{
|
||||
return serialization_traits<T>::deserialize(*this);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct serialization_traits<T, std::enable_if_t<std::is_arithmetic_v<T>>>
|
||||
{
|
||||
static constexpr void type_hash(details::hash_context & h)
|
||||
{
|
||||
if constexpr (std::is_floating_point_v<T>)
|
||||
h.feed("float");
|
||||
else if constexpr (std::is_integral_v<T>)
|
||||
{
|
||||
if constexpr (std::is_unsigned_v<T>)
|
||||
h.feed("uint");
|
||||
else
|
||||
h.feed("int");
|
||||
}
|
||||
|
||||
h.feed(sizeof(T) * 8);
|
||||
}
|
||||
|
||||
static void serialize(T value, serialization_packet & packet)
|
||||
{
|
||||
packet.write(&value, sizeof(value));
|
||||
}
|
||||
|
||||
static T deserialize(deserialization_packet & packet)
|
||||
{
|
||||
T value;
|
||||
packet.read((char *)&value, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct serialization_traits<T, std::enable_if_t<std::is_enum_v<T>>>
|
||||
{
|
||||
static constexpr void type_hash(details::hash_context & h)
|
||||
{
|
||||
h.feed("enum");
|
||||
h.feed(sizeof(T) * 8);
|
||||
}
|
||||
|
||||
static void serialize(T value, serialization_packet & packet)
|
||||
{
|
||||
packet.write(&value, sizeof(value));
|
||||
}
|
||||
|
||||
static T deserialize(deserialization_packet & packet)
|
||||
{
|
||||
T value;
|
||||
packet.read((char *)&value, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <class>
|
||||
struct is_stdarray : public std::false_type
|
||||
{};
|
||||
|
||||
template <class T, size_t N>
|
||||
struct is_stdarray<std::array<T, N>> : public std::true_type
|
||||
{};
|
||||
|
||||
template <typename T>
|
||||
inline constexpr bool is_stdarray_v = is_stdarray<T>::value;
|
||||
|
||||
template <typename T>
|
||||
struct serialization_traits<T, std::enable_if_t<std::is_aggregate_v<T> && !is_stdarray_v<T>>>
|
||||
{
|
||||
template <size_t I>
|
||||
static constexpr void aux2(details::hash_context & h)
|
||||
{
|
||||
if constexpr (I > 0)
|
||||
h.feed(",");
|
||||
serialization_traits<boost::pfr::tuple_element_t<I, T>>::type_hash(h);
|
||||
}
|
||||
|
||||
template <size_t... I>
|
||||
static constexpr void aux1(details::hash_context & h, std::index_sequence<I...>)
|
||||
{
|
||||
(aux2<I>(h), ...);
|
||||
}
|
||||
|
||||
static constexpr void type_hash(details::hash_context & h)
|
||||
{
|
||||
h.feed("structure{");
|
||||
aux1(h, std::make_index_sequence<boost::pfr::tuple_size_v<T>>());
|
||||
h.feed("}");
|
||||
}
|
||||
|
||||
static void serialize(const T & value, serialization_packet & packet)
|
||||
{
|
||||
boost::pfr::for_each_field(value, [&](const auto & x) { packet.serialize(x); });
|
||||
}
|
||||
|
||||
static T deserialize(deserialization_packet & packet)
|
||||
{
|
||||
T value;
|
||||
|
||||
boost::pfr::for_each_field(
|
||||
value, [&](auto & x) { x = packet.deserialize<std::remove_reference_t<decltype(x)>>(); });
|
||||
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct serialization_traits<std::string>
|
||||
{
|
||||
static constexpr void type_hash(details::hash_context & h)
|
||||
{
|
||||
h.feed("string");
|
||||
}
|
||||
|
||||
static void serialize(const std::string & value, serialization_packet & packet)
|
||||
{
|
||||
packet.serialize<uint64_t>(value.size());
|
||||
packet.write(value.data(), value.size());
|
||||
}
|
||||
|
||||
static std::string deserialize(deserialization_packet & packet)
|
||||
{
|
||||
std::string value;
|
||||
size_t size = packet.deserialize<uint64_t>();
|
||||
|
||||
packet.check_remaining_size(size);
|
||||
|
||||
value.resize(size);
|
||||
packet.read(value.data(), size);
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct serialization_traits<std::vector<T>>
|
||||
{
|
||||
static constexpr void type_hash(details::hash_context & h)
|
||||
{
|
||||
h.feed("vector<");
|
||||
serialization_traits<T>::type_hash(h);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void serialize(const std::vector<T> & value, serialization_packet & packet)
|
||||
{
|
||||
packet.serialize<uint64_t>(value.size());
|
||||
|
||||
for (const T & i: value)
|
||||
packet.serialize<T>(i);
|
||||
}
|
||||
|
||||
static std::vector<T> deserialize(deserialization_packet & packet)
|
||||
{
|
||||
std::vector<T> value;
|
||||
size_t size = packet.deserialize<uint64_t>();
|
||||
|
||||
packet.check_remaining_size(size);
|
||||
|
||||
value.reserve(size);
|
||||
for (size_t i = 0; i < size; i++)
|
||||
{
|
||||
value.emplace_back(packet.deserialize<T>());
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct serialization_traits<std::optional<T>>
|
||||
{
|
||||
static constexpr void type_hash(details::hash_context & h)
|
||||
{
|
||||
h.feed("optional<");
|
||||
serialization_traits<T>::type_hash(h);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void serialize(const std::optional<T> & value, serialization_packet & packet)
|
||||
{
|
||||
if (value)
|
||||
{
|
||||
packet.serialize<bool>(true);
|
||||
packet.serialize<T>(*value);
|
||||
}
|
||||
else
|
||||
{
|
||||
packet.serialize<bool>(false);
|
||||
}
|
||||
}
|
||||
|
||||
static std::optional<T> deserialize(deserialization_packet & packet)
|
||||
{
|
||||
if (packet.deserialize<bool>())
|
||||
return packet.deserialize<T>();
|
||||
else
|
||||
return std::nullopt;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, size_t N>
|
||||
struct serialization_traits<std::array<T, N>>
|
||||
{
|
||||
static constexpr void type_hash(details::hash_context & h)
|
||||
{
|
||||
h.feed("array<");
|
||||
serialization_traits<T>::type_hash(h);
|
||||
h.feed(",");
|
||||
h.feed(N);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void serialize(const std::array<T, N> & value, serialization_packet & packet)
|
||||
{
|
||||
for (const T & i: value)
|
||||
packet.serialize<T>(i);
|
||||
}
|
||||
|
||||
static std::array<T, N> deserialize(deserialization_packet & packet)
|
||||
{
|
||||
std::array<T, N> value;
|
||||
|
||||
for (size_t i = 0; i < N; i++)
|
||||
{
|
||||
value[i] = packet.deserialize<T>();
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename... T>
|
||||
struct serialization_traits<std::variant<T...>>
|
||||
{
|
||||
template <typename U, typename... V>
|
||||
static constexpr void type_list_hash(details::hash_context & h)
|
||||
{
|
||||
serialization_traits<U>::type_hash(h);
|
||||
|
||||
if constexpr (sizeof...(V) > 0)
|
||||
{
|
||||
h.feed(",");
|
||||
type_list_hash<V...>(h);
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr void type_hash(details::hash_context & h)
|
||||
{
|
||||
h.feed("variant<");
|
||||
type_list_hash<T...>(h);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void serialize(const std::variant<T...> & value, serialization_packet & packet)
|
||||
{
|
||||
packet.serialize<uint32_t>(value.index());
|
||||
std::visit([&](const auto & x) { packet.serialize(x); }, value);
|
||||
}
|
||||
|
||||
template <size_t I>
|
||||
using i_th_type = std::tuple_element_t<I, std::tuple<T...>>;
|
||||
|
||||
template <size_t... I>
|
||||
static std::variant<T...> deserialize_aux(deserialization_packet & packet, size_t type_index, std::index_sequence<I...>)
|
||||
{
|
||||
std::variant<T...> value;
|
||||
((I == type_index ? (void)(value = packet.deserialize<i_th_type<I>>()) : (void)0), ...);
|
||||
return value;
|
||||
}
|
||||
|
||||
static std::variant<T...> deserialize(deserialization_packet & packet)
|
||||
{
|
||||
uint32_t type_index = packet.deserialize<uint32_t>();
|
||||
if (type_index >= sizeof...(T))
|
||||
throw deserialization_error();
|
||||
|
||||
return deserialize_aux(packet, type_index, std::make_index_sequence<sizeof...(T)>());
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Rep, typename Period>
|
||||
struct serialization_traits<std::chrono::duration<Rep, Period>>
|
||||
{
|
||||
static constexpr void type_hash(details::hash_context & h)
|
||||
{
|
||||
h.feed("duration<");
|
||||
serialization_traits<Rep>::type_hash(h);
|
||||
h.feed(",");
|
||||
h.feed(Period::num);
|
||||
h.feed("/");
|
||||
h.feed(Period::den);
|
||||
h.feed(">");
|
||||
}
|
||||
|
||||
static void serialize(const std::chrono::duration<Rep, Period> & value, serialization_packet & packet)
|
||||
{
|
||||
packet.serialize<Rep>(value.count());
|
||||
}
|
||||
|
||||
static std::chrono::duration<Rep, Period> deserialize(deserialization_packet & packet)
|
||||
{
|
||||
Rep nsec = packet.deserialize<Rep>();
|
||||
return std::chrono::duration<Rep, Period>{nsec};
|
||||
}
|
||||
};
|
||||
|
||||
namespace unit_tests
|
||||
{
|
||||
template <typename T>
|
||||
constexpr uint64_t hash(T s)
|
||||
{
|
||||
return details::hash_context{}.feed(s);
|
||||
}
|
||||
|
||||
static_assert(hash("test") == 0xf9e6e6ef197c2b25);
|
||||
static_assert(hash(1234) == 0x1fabbdf10314a21d);
|
||||
static_assert(hash(-1234) == 0x77fa1c9653db5a84);
|
||||
static_assert(hash(0) == 0xaf63ad4c86019caf);
|
||||
|
||||
template <typename T>
|
||||
constexpr uint64_t serialization_type_hash()
|
||||
{
|
||||
details::hash_context h;
|
||||
serialization_traits<T>::type_hash(h);
|
||||
return h.hash;
|
||||
}
|
||||
|
||||
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>"));
|
||||
|
||||
struct test
|
||||
{
|
||||
int x;
|
||||
float y;
|
||||
};
|
||||
static_assert(serialization_type_hash<test>() == hash("structure{int32,float32}"));
|
||||
} // namespace unit_tests
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,299 @@
|
||||
/*
|
||||
* 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 "wivrn_sockets.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
#include <netdb.h>
|
||||
#include <netinet/ip.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <system_error>
|
||||
#include <unistd.h>
|
||||
|
||||
const char * xrt::drivers::wivrn::invalid_packet::what() const noexcept
|
||||
{
|
||||
return "Invalid packet";
|
||||
}
|
||||
|
||||
const char * xrt::drivers::wivrn::socket_shutdown::what() const noexcept
|
||||
{
|
||||
return "Socket shutdown";
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::socket_base::socket_base(xrt::drivers::wivrn::socket_base && other) :
|
||||
fd(other.fd)
|
||||
{
|
||||
other.fd = -1;
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::socket_base::~socket_base()
|
||||
{
|
||||
if (fd >= 0)
|
||||
::close(fd);
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::UDP::UDP()
|
||||
{
|
||||
fd = socket(AF_INET6, SOCK_DGRAM, 0);
|
||||
|
||||
if (fd < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
void xrt::drivers::wivrn::UDP::bind(int port)
|
||||
{
|
||||
sockaddr_in6 bind_addr{};
|
||||
bind_addr.sin6_family = AF_INET6;
|
||||
bind_addr.sin6_addr = IN6ADDR_ANY_INIT;
|
||||
bind_addr.sin6_port = htons(port);
|
||||
|
||||
if (::bind(fd, (sockaddr *)&bind_addr, sizeof(bind_addr)) < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
void xrt::drivers::wivrn::UDP::connect(in6_addr address, int port)
|
||||
{
|
||||
sockaddr_in6 sa;
|
||||
sa.sin6_family = AF_INET6;
|
||||
sa.sin6_addr = address;
|
||||
sa.sin6_port = htons(port);
|
||||
|
||||
if (::connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
void xrt::drivers::wivrn::UDP::subscribe_multicast(in6_addr address)
|
||||
{
|
||||
assert(IN6_IS_ADDR_MULTICAST(&address));
|
||||
|
||||
ipv6_mreq subscribe{};
|
||||
subscribe.ipv6mr_multiaddr = address;
|
||||
|
||||
if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &subscribe, sizeof(subscribe)) < 0)
|
||||
{
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
void xrt::drivers::wivrn::UDP::unsubscribe_multicast(in6_addr address)
|
||||
{
|
||||
assert(IN6_IS_ADDR_MULTICAST(&address));
|
||||
|
||||
ipv6_mreq subscribe{};
|
||||
subscribe.ipv6mr_multiaddr = address;
|
||||
|
||||
if (setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &subscribe, sizeof(subscribe)) < 0)
|
||||
{
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
void xrt::drivers::wivrn::UDP::set_receive_buffer_size(int size)
|
||||
{
|
||||
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::TCP::TCP(int fd)
|
||||
{
|
||||
this->fd = fd;
|
||||
mutex = std::make_unique<std::mutex>();
|
||||
|
||||
int nodelay = 1;
|
||||
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0)
|
||||
{
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::TCP::TCP(in6_addr address, int port)
|
||||
{
|
||||
fd = socket(AF_INET6, SOCK_STREAM, 0);
|
||||
mutex = std::make_unique<std::mutex>();
|
||||
|
||||
if (fd < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
sockaddr_in6 sa;
|
||||
sa.sin6_family = AF_INET6;
|
||||
sa.sin6_addr = address;
|
||||
sa.sin6_port = htons(port);
|
||||
|
||||
if (connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
|
||||
{
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
int nodelay = 1;
|
||||
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0)
|
||||
{
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::TCPListener::TCPListener(int port)
|
||||
{
|
||||
fd = socket(AF_INET6, SOCK_STREAM, 0);
|
||||
|
||||
if (fd < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
int reuse_addr = 1;
|
||||
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)) < 0)
|
||||
{
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
sockaddr_in6 addr{};
|
||||
addr.sin6_family = AF_INET6;
|
||||
addr.sin6_port = htons(port);
|
||||
addr.sin6_addr = in6addr_any;
|
||||
|
||||
if (bind(fd, (sockaddr *)&addr, sizeof(addr)) < 0)
|
||||
{
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
int backlog = 1;
|
||||
if (listen(fd, backlog) < 0)
|
||||
{
|
||||
::close(fd);
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
}
|
||||
|
||||
std::pair<xrt::drivers::wivrn::TCP, sockaddr_in6> xrt::drivers::wivrn::TCPListener::accept()
|
||||
{
|
||||
sockaddr_in6 addr{};
|
||||
socklen_t addrlen = sizeof(addr);
|
||||
|
||||
int fd2 = ::accept(fd, (sockaddr *)&addr, &addrlen);
|
||||
if (fd2 < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
return {TCP{fd2}, addr};
|
||||
}
|
||||
|
||||
std::pair<xrt::drivers::wivrn::deserialization_packet, sockaddr_in6> xrt::drivers::wivrn::UDP::receive_from_raw()
|
||||
{
|
||||
std::vector<uint8_t> buffer(2000);
|
||||
|
||||
sockaddr_in6 addr;
|
||||
socklen_t addrlen = sizeof(addr);
|
||||
|
||||
ssize_t received = recvfrom(fd, buffer.data(), buffer.size(), 0, (sockaddr *)&addr, &addrlen);
|
||||
if (received < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
buffer.resize(received);
|
||||
|
||||
return {deserialization_packet{buffer}, addr};
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::deserialization_packet xrt::drivers::wivrn::UDP::receive_raw()
|
||||
{
|
||||
return receive_from_raw().first;
|
||||
}
|
||||
|
||||
void xrt::drivers::wivrn::UDP::send_raw(const std::vector<uint8_t> & data)
|
||||
{
|
||||
if (::send(fd, data.data(), data.size(), 0) < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
}
|
||||
|
||||
xrt::drivers::wivrn::deserialization_packet xrt::drivers::wivrn::TCP::receive_raw()
|
||||
{
|
||||
size_t expected_size;
|
||||
size_t already_received = buffer.size();
|
||||
|
||||
if (already_received < 4)
|
||||
{
|
||||
expected_size = 4 - buffer.size();
|
||||
}
|
||||
else
|
||||
{
|
||||
uint32_t payload_size = *reinterpret_cast<uint32_t *>(buffer.data());
|
||||
expected_size = payload_size + 4 - buffer.size();
|
||||
}
|
||||
|
||||
buffer.resize(already_received + expected_size);
|
||||
ssize_t received = recv(fd, buffer.data() + already_received, expected_size, MSG_DONTWAIT);
|
||||
|
||||
if (received < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
if (received == 0)
|
||||
throw socket_shutdown{};
|
||||
|
||||
buffer.resize(already_received + received);
|
||||
|
||||
if (buffer.size() < 4)
|
||||
return {};
|
||||
|
||||
uint32_t payload_size = *reinterpret_cast<uint32_t *>(buffer.data());
|
||||
if (buffer.size() < 4 + payload_size)
|
||||
return {};
|
||||
|
||||
assert(buffer.size() == 4 + payload_size);
|
||||
|
||||
std::vector<uint8_t> new_buffer;
|
||||
std::swap(buffer, new_buffer);
|
||||
|
||||
return deserialization_packet{std::move(new_buffer), 4};
|
||||
}
|
||||
|
||||
void xrt::drivers::wivrn::TCP::send_raw(const std::vector<uint8_t> & data)
|
||||
{
|
||||
std::lock_guard lock(*mutex);
|
||||
|
||||
uint32_t size = data.size();
|
||||
ssize_t sent = ::send(fd, &size, sizeof(size), MSG_NOSIGNAL);
|
||||
|
||||
if (sent == 0)
|
||||
throw socket_shutdown{};
|
||||
|
||||
if (sent < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
assert(sent == sizeof(size));
|
||||
|
||||
size_t index = 0;
|
||||
while (index < data.size())
|
||||
{
|
||||
sent = ::send(fd, data.data() + index, data.size() - index, MSG_NOSIGNAL);
|
||||
|
||||
if (sent == 0)
|
||||
throw socket_shutdown{};
|
||||
|
||||
if (sent < 0)
|
||||
throw std::system_error{errno, std::generic_category()};
|
||||
|
||||
index += sent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* 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 "wivrn_serialization.h"
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <netinet/ip.h>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace xrt::drivers::wivrn
|
||||
{
|
||||
class socket_shutdown : public std::exception
|
||||
{
|
||||
public:
|
||||
const char * what() const noexcept override;
|
||||
};
|
||||
|
||||
class invalid_packet : public std::exception
|
||||
{
|
||||
public:
|
||||
const char * what() const noexcept override;
|
||||
};
|
||||
|
||||
template <typename T, typename... Ts>
|
||||
struct index_of_type
|
||||
{};
|
||||
|
||||
template <typename T, typename... Ts>
|
||||
struct index_of_type<T, T, Ts...> : std::integral_constant<size_t, 0>
|
||||
{};
|
||||
|
||||
template <typename T, typename T2, typename... Ts>
|
||||
struct index_of_type<T, T2, Ts...> : std::integral_constant<size_t, 1 + index_of_type<T, Ts...>::value>
|
||||
{};
|
||||
|
||||
static_assert(index_of_type<int, int, float>::value == 0);
|
||||
static_assert(index_of_type<float, int, float>::value == 1);
|
||||
|
||||
class socket_base
|
||||
{
|
||||
protected:
|
||||
int fd = -1;
|
||||
|
||||
socket_base() = default;
|
||||
socket_base(const socket_base &) = delete;
|
||||
socket_base(socket_base &&);
|
||||
~socket_base();
|
||||
|
||||
public:
|
||||
int get_fd() const
|
||||
{
|
||||
return fd;
|
||||
}
|
||||
};
|
||||
|
||||
class UDP : public socket_base
|
||||
{
|
||||
public:
|
||||
UDP();
|
||||
UDP(const UDP &) = delete;
|
||||
UDP(UDP &&) = default;
|
||||
|
||||
deserialization_packet receive_raw();
|
||||
std::pair<deserialization_packet, sockaddr_in6> receive_from_raw();
|
||||
void send_raw(const std::vector<uint8_t> & data);
|
||||
|
||||
void connect(in6_addr address, int port);
|
||||
void bind(int port);
|
||||
void subscribe_multicast(in6_addr address);
|
||||
void unsubscribe_multicast(in6_addr address);
|
||||
void set_receive_buffer_size(int size);
|
||||
};
|
||||
|
||||
class TCP : public socket_base
|
||||
{
|
||||
std::vector<uint8_t> buffer;
|
||||
std::unique_ptr<std::mutex> mutex;
|
||||
|
||||
public:
|
||||
TCP(in6_addr address, int port);
|
||||
explicit TCP(int fd);
|
||||
TCP(const TCP &) = delete;
|
||||
TCP(TCP &&) = default;
|
||||
|
||||
deserialization_packet receive_raw();
|
||||
void send_raw(const std::vector<uint8_t> & data);
|
||||
};
|
||||
|
||||
class TCPListener : public socket_base
|
||||
{
|
||||
public:
|
||||
TCPListener(int port);
|
||||
TCPListener(const TCPListener &) = delete;
|
||||
TCPListener(TCPListener &&) = default;
|
||||
|
||||
std::pair<TCP, sockaddr_in6> accept();
|
||||
};
|
||||
|
||||
template <typename Socket, typename ReceivedType, typename SentType>
|
||||
class typed_socket : public Socket
|
||||
{
|
||||
public:
|
||||
template <typename... Args>
|
||||
typed_socket(Args &&... args) :
|
||||
Socket(std::forward<Args>(args)...)
|
||||
{}
|
||||
|
||||
std::optional<ReceivedType> receive()
|
||||
{
|
||||
deserialization_packet packet = this->receive_raw();
|
||||
if (packet.empty())
|
||||
return {};
|
||||
|
||||
return packet.deserialize<ReceivedType>();
|
||||
}
|
||||
|
||||
std::optional<std::pair<ReceivedType, sockaddr_in6>> receive_from()
|
||||
{
|
||||
auto [buffer, addr] = this->receive_from_raw();
|
||||
if (buffer.empty())
|
||||
return {};
|
||||
|
||||
return {deserialization_packet(std::move(buffer)).deserialize<ReceivedType>(), addr};
|
||||
}
|
||||
|
||||
template <typename T = SentType, typename = std::enable_if_t<std::is_same_v<T, SentType>>>
|
||||
void send(const T & data)
|
||||
{
|
||||
serialization_packet p;
|
||||
p.serialize(data);
|
||||
this->send_raw(std::move(p));
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace xrt::drivers::wivrn
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* 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 "actionset.h"
|
||||
#include "xr.h"
|
||||
#include <cstring>
|
||||
|
||||
xr::actionset::actionset(xr::instance & inst, const std::string & name, const std::string & localized_name, uint32_t priority)
|
||||
{
|
||||
this->inst = &inst;
|
||||
|
||||
XrActionSetCreateInfo create_info{};
|
||||
create_info.type = XR_TYPE_ACTION_SET_CREATE_INFO;
|
||||
strncpy(create_info.actionSetName, name.c_str(), sizeof(create_info.actionSetName) - 1);
|
||||
strncpy(create_info.localizedActionSetName, localized_name.c_str(), sizeof(create_info.localizedActionSetName) - 1);
|
||||
create_info.priority = priority;
|
||||
|
||||
CHECK_XR(xrCreateActionSet(inst, &create_info, &id));
|
||||
}
|
||||
|
||||
XrAction xr::actionset::create_action(XrActionType type, const std::string & name, const std::string & localized_name, const std::vector<std::string> & subactionpaths)
|
||||
{
|
||||
std::vector<XrPath> paths(subactionpaths.size());
|
||||
for (size_t i = 0; i < subactionpaths.size(); i++)
|
||||
{
|
||||
paths[i] = inst->string_to_path(subactionpaths[i]);
|
||||
}
|
||||
|
||||
XrActionCreateInfo create_info{};
|
||||
create_info.type = XR_TYPE_ACTION_CREATE_INFO;
|
||||
create_info.actionType = type,
|
||||
strncpy(create_info.actionName, name.c_str(), sizeof(create_info.actionName) - 1);
|
||||
strncpy(create_info.localizedActionName, localized_name.c_str(), sizeof(create_info.localizedActionName) - 1);
|
||||
create_info.countSubactionPaths = paths.size();
|
||||
create_info.subactionPaths = paths.data();
|
||||
|
||||
XrAction action;
|
||||
CHECK_XR(xrCreateAction(id, &create_info, &action));
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
xr::actionset::~actionset()
|
||||
{
|
||||
if (id != XR_NULL_HANDLE)
|
||||
xrDestroyActionSet(id);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
namespace xr
|
||||
{
|
||||
class instance;
|
||||
|
||||
class actionset : public utils::handle<XrActionSet>
|
||||
{
|
||||
instance * inst;
|
||||
|
||||
public:
|
||||
actionset() = default;
|
||||
actionset(instance & inst, const std::string & name, const std::string & localized_name, uint32_t priority = 0);
|
||||
actionset(actionset &&) = default;
|
||||
actionset & operator=(actionset &&) = default;
|
||||
|
||||
XrAction create_action(XrActionType type, const std::string & name, const std::string & localized_name, const std::vector<std::string> & subactionpaths = {});
|
||||
|
||||
XrAction create_action(XrActionType type, const std::string & name, const std::vector<std::string> & subactionpaths = {})
|
||||
{
|
||||
return create_action(type, name, name, subactionpaths);
|
||||
}
|
||||
|
||||
~actionset();
|
||||
};
|
||||
} // namespace xr
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* 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
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#include <jni.h>
|
||||
#endif
|
||||
|
||||
#include "utils/check.h"
|
||||
#include "utils/typename.h"
|
||||
#include <type_traits>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <openxr/openxr.h>
|
||||
#include <openxr/openxr_platform.h>
|
||||
|
||||
namespace xr::details
|
||||
{
|
||||
|
||||
template <typename T>
|
||||
struct structure_traits_base
|
||||
{
|
||||
static constexpr inline XrStructureType type = XR_TYPE_UNKNOWN;
|
||||
using base = T;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct structure_traits : structure_traits_base<T>
|
||||
{};
|
||||
|
||||
template <>
|
||||
struct structure_traits<XrViewConfigurationView> : structure_traits_base<XrViewConfigurationView>
|
||||
{
|
||||
static constexpr inline XrStructureType type = XR_TYPE_VIEW_CONFIGURATION_VIEW;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct structure_traits<XrView> : structure_traits_base<XrView>
|
||||
{
|
||||
static constexpr inline XrStructureType type = XR_TYPE_VIEW;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct structure_traits<XrApiLayerProperties> : structure_traits_base<XrApiLayerProperties>
|
||||
{
|
||||
static constexpr inline XrStructureType type = XR_TYPE_API_LAYER_PROPERTIES;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct structure_traits<XrExtensionProperties> : structure_traits_base<XrExtensionProperties>
|
||||
{
|
||||
static constexpr inline XrStructureType type = XR_TYPE_EXTENSION_PROPERTIES;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct structure_traits<XrSwapchainImageVulkanKHR> : structure_traits_base<XrSwapchainImageVulkanKHR>
|
||||
{
|
||||
static constexpr inline XrStructureType type = XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR;
|
||||
using base = XrSwapchainImageBaseHeader;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
constexpr inline XrStructureType structure_type = structure_traits<T>::type;
|
||||
|
||||
template <typename T, typename F, typename... Args>
|
||||
auto enumerate(F f, Args &&... args) -> auto
|
||||
{
|
||||
using array_type = std::conditional_t<std::is_same_v<T, char>, std::string, std::vector<T>>;
|
||||
array_type array;
|
||||
uint32_t count;
|
||||
XrResult result;
|
||||
|
||||
result = f(std::forward<Args>(args)..., 0, &count, nullptr);
|
||||
|
||||
if (XR_SUCCEEDED(result))
|
||||
{
|
||||
if constexpr (structure_type<T> == XR_TYPE_UNKNOWN)
|
||||
{
|
||||
array.resize(count);
|
||||
}
|
||||
else
|
||||
{
|
||||
T default_value{};
|
||||
default_value.type = structure_type<T>;
|
||||
array.resize(count, default_value);
|
||||
}
|
||||
result = f(std::forward<Args>(args)..., count, &count, reinterpret_cast<typename structure_traits<T>::base *>(array.data()));
|
||||
}
|
||||
|
||||
if (!XR_SUCCEEDED(result))
|
||||
{
|
||||
throw std::system_error(result, xr::error_category(), "enumerating " + type_name<T>());
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
} // namespace xr::details
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* 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 "utils/check.h"
|
||||
#include "xr.h"
|
||||
#include <system_error>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct : std::error_category
|
||||
{
|
||||
const char * name() const noexcept override
|
||||
{
|
||||
return "openxr";
|
||||
}
|
||||
|
||||
std::string message(int condition) const override
|
||||
{
|
||||
return xr::to_string(static_cast<XrResult>(condition));
|
||||
}
|
||||
} openxr_error_category;
|
||||
} // namespace
|
||||
|
||||
const std::error_category & xr::error_category()
|
||||
{
|
||||
return openxr_error_category;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
/*
|
||||
* 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 "instance.h"
|
||||
|
||||
#include "spdlog/fmt/fmt.h"
|
||||
#include "xr.h"
|
||||
#include "xr/details/enumerate.h"
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <utility>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <openxr/openxr.h>
|
||||
#include <openxr/openxr_platform.h>
|
||||
#include <openxr/openxr_reflection.h>
|
||||
|
||||
static XrBool32 debug_callback(
|
||||
XrDebugUtilsMessageSeverityFlagsEXT messageSeverity,
|
||||
XrDebugUtilsMessageTypeFlagsEXT messageTypes,
|
||||
const XrDebugUtilsMessengerCallbackDataEXT * callbackData,
|
||||
void * userData)
|
||||
{
|
||||
spdlog::info("OpenXR debug message: severity={}, type={}, function={}, {}", messageSeverity, messageTypes, callbackData->functionName, callbackData->message);
|
||||
|
||||
return XR_FALSE;
|
||||
}
|
||||
|
||||
#if defined(XR_USE_PLATFORM_ANDROID)
|
||||
xr::instance::instance(std::string_view application_name, void * applicationVM, void * applicationActivity, std::vector<const char *> extensions)
|
||||
#else
|
||||
xr::instance::instance(std::string_view application_name, std::vector<const char *> extensions)
|
||||
#endif
|
||||
{
|
||||
#if defined(XR_USE_GRAPHICS_API_VULKAN)
|
||||
extensions.push_back(XR_KHR_VULKAN_ENABLE2_EXTENSION_NAME);
|
||||
#else
|
||||
#error Not implemented
|
||||
#endif
|
||||
|
||||
#if defined(XR_USE_PLATFORM_ANDROID)
|
||||
extensions.push_back(XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME);
|
||||
#endif
|
||||
|
||||
std::vector<const char *> layers;
|
||||
// TODO: runtime switch
|
||||
|
||||
spdlog::info("Available OpenXR layers:");
|
||||
for (XrApiLayerProperties & i: xr::details::enumerate<XrApiLayerProperties>(xrEnumerateApiLayerProperties))
|
||||
{
|
||||
spdlog::info(" {}", i.layerName);
|
||||
#ifndef NDEBUG
|
||||
if (!strcmp(i.layerName, "XR_APILAYER_LUNARG_core_validation"))
|
||||
{
|
||||
layers.push_back("XR_APILAYER_LUNARG_core_validation");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
spdlog::info("Available OpenXR extensions:");
|
||||
bool debug_utils_found = false;
|
||||
for (XrExtensionProperties & i:
|
||||
xr::details::enumerate<XrExtensionProperties>(xrEnumerateInstanceExtensionProperties, nullptr))
|
||||
{
|
||||
spdlog::info(" {}", i.extensionName);
|
||||
#ifndef NDEBUG
|
||||
if (!strcmp(i.extensionName, "XR_EXT_debug_utils"))
|
||||
{
|
||||
debug_utils_found = true;
|
||||
extensions.push_back("XR_EXT_debug_utils");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
spdlog::info("Using OpenXR extensions:");
|
||||
for (auto & i: extensions)
|
||||
{
|
||||
loaded_extensions.insert(i);
|
||||
spdlog::info(" {}", i);
|
||||
}
|
||||
|
||||
XrInstanceCreateInfo create_info{
|
||||
.type = XR_TYPE_INSTANCE_CREATE_INFO,
|
||||
.applicationInfo = {.apiVersion = XR_CURRENT_API_VERSION},
|
||||
.enabledApiLayerCount = (uint32_t)layers.size(),
|
||||
.enabledApiLayerNames = layers.data(),
|
||||
.enabledExtensionCount = (uint32_t)extensions.size(),
|
||||
.enabledExtensionNames = extensions.data(),
|
||||
};
|
||||
strncpy(create_info.applicationInfo.applicationName, application_name.data(), sizeof(create_info.applicationInfo.applicationName) - 1);
|
||||
|
||||
#if defined(XR_USE_PLATFORM_ANDROID)
|
||||
XrInstanceCreateInfoAndroidKHR instanceCreateInfoAndroid{
|
||||
.type = XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR,
|
||||
.applicationVM = applicationVM,
|
||||
.applicationActivity = applicationActivity,
|
||||
};
|
||||
create_info.next = &instanceCreateInfoAndroid;
|
||||
#endif
|
||||
|
||||
CHECK_XR(xrCreateInstance(&create_info, &id));
|
||||
assert(id != XR_NULL_HANDLE);
|
||||
|
||||
if (debug_utils_found)
|
||||
{
|
||||
XrDebugUtilsMessengerCreateInfoEXT debug_messenger_info{
|
||||
.type = XR_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
|
||||
.messageSeverities = XR_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
|
||||
.messageTypes = XR_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT,
|
||||
.userCallback = debug_callback};
|
||||
auto xrCreateDebugUtilsMessengerEXT = get_proc<PFN_xrCreateDebugUtilsMessengerEXT>("xrCreateDebugUtilsMessengerEXT");
|
||||
XrDebugUtilsMessengerEXT messenger;
|
||||
CHECK_XR(xrCreateDebugUtilsMessengerEXT(id, &debug_messenger_info, &messenger));
|
||||
}
|
||||
|
||||
XrInstanceProperties prop{XR_TYPE_INSTANCE_PROPERTIES};
|
||||
CHECK_XR(xrGetInstanceProperties(id, &prop));
|
||||
// TODO: exception safety
|
||||
// if (!XR_SUCCEEDED(result))
|
||||
// {
|
||||
// xrDestroyInstance(id);
|
||||
// throw error("Cannot get instance properties", result);
|
||||
// }
|
||||
|
||||
runtime_version = to_string(prop.runtimeVersion);
|
||||
runtime_name = prop.runtimeName;
|
||||
}
|
||||
|
||||
std::string xr::instance::path_to_string(XrPath path)
|
||||
{
|
||||
if (path == XR_NULL_PATH)
|
||||
return "XR_NULL_PATH";
|
||||
|
||||
uint32_t length;
|
||||
std::string s;
|
||||
|
||||
CHECK_XR(xrPathToString(id, path, 0, &length, nullptr));
|
||||
s.resize(length);
|
||||
CHECK_XR(xrPathToString(id, path, length, &length, s.data()));
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
XrPath xr::instance::string_to_path(const std::string & path)
|
||||
{
|
||||
XrPath p;
|
||||
CHECK_XR(xrStringToPath(id, path.c_str(), &p));
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
bool xr::instance::poll_event(xr::event & buffer)
|
||||
{
|
||||
buffer.header.type = XR_TYPE_EVENT_DATA_BUFFER;
|
||||
buffer.header.next = nullptr;
|
||||
XrResult result = CHECK_XR(xrPollEvent(id, &buffer.header));
|
||||
|
||||
return result == XR_SUCCESS;
|
||||
}
|
||||
|
||||
void xr::instance::suggest_bindings(const std::string & interaction_profile,
|
||||
std::vector<XrActionSuggestedBinding> & bindings)
|
||||
{
|
||||
XrInteractionProfileSuggestedBinding suggested_binding{};
|
||||
suggested_binding.type = XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING;
|
||||
suggested_binding.interactionProfile = string_to_path(interaction_profile);
|
||||
suggested_binding.countSuggestedBindings = bindings.size();
|
||||
suggested_binding.suggestedBindings = bindings.data();
|
||||
CHECK_XR(xrSuggestInteractionProfileBindings(id, &suggested_binding));
|
||||
}
|
||||
|
||||
xr::instance::~instance()
|
||||
{
|
||||
if (id != XR_NULL_HANDLE)
|
||||
xrDestroyInstance(id);
|
||||
}
|
||||
|
||||
XrTime xr::instance::now()
|
||||
{
|
||||
static PFN_xrConvertTimespecTimeToTimeKHR xrConvertTimespecTimeToTimeKHR =
|
||||
get_proc<PFN_xrConvertTimespecTimeToTimeKHR>("xrConvertTimespecTimeToTimeKHR");
|
||||
timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
XrTime res;
|
||||
CHECK_XR(xrConvertTimespecTimeToTimeKHR(id, &ts, &res));
|
||||
return res;
|
||||
}
|
||||
|
||||
std::vector<XrExtensionProperties> xr::instance::extensions(const char * layer_name)
|
||||
{
|
||||
return xr::details::enumerate<XrExtensionProperties>(xrEnumerateInstanceExtensionProperties, layer_name);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* 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
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#include <android_native_app_glue.h>
|
||||
#endif
|
||||
|
||||
#include "error.h"
|
||||
#include "utils/check.h"
|
||||
#include "utils/handle.h"
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <openxr/openxr.h>
|
||||
#include <openxr/openxr_platform.h>
|
||||
|
||||
namespace xr
|
||||
{
|
||||
union event
|
||||
{
|
||||
XrEventDataBuffer header;
|
||||
XrEventDataInstanceLossPending loss_pending;
|
||||
XrEventDataInteractionProfileChanged interaction_profile_changed;
|
||||
XrEventDataReferenceSpaceChangePending space_changed_pending;
|
||||
XrEventDataSessionStateChanged state_changed;
|
||||
};
|
||||
class instance : public utils::handle<XrInstance>
|
||||
{
|
||||
std::string runtime_version;
|
||||
std::string runtime_name;
|
||||
std::unordered_set<std::string> loaded_extensions;
|
||||
|
||||
public:
|
||||
#if defined(XR_USE_PLATFORM_ANDROID)
|
||||
explicit instance(std::string_view application_name, void * applicationVM, void * applicationActivity, std::vector<const char *> extensions = {});
|
||||
#else
|
||||
explicit instance(std::string_view application_name, std::vector<const char *> extensions = {});
|
||||
#endif
|
||||
|
||||
instance() = default;
|
||||
instance(instance &&) = default;
|
||||
instance & operator=(instance &&) = default;
|
||||
~instance();
|
||||
|
||||
const std::string & get_runtime_version() const
|
||||
{
|
||||
return runtime_version;
|
||||
}
|
||||
const std::string & get_runtime_name() const
|
||||
{
|
||||
return runtime_name;
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
F get_proc(const char * name)
|
||||
{
|
||||
F f;
|
||||
XrResult result = xrGetInstanceProcAddr(id, name, (PFN_xrVoidFunction *)&f);
|
||||
if (!XR_SUCCEEDED(result))
|
||||
{
|
||||
throw std::system_error(result, vk::error_category(), std::string("xrGetInstanceProcAddr(") + name + ")");
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
bool poll_event(event &);
|
||||
|
||||
XrPath string_to_path(const std::string & path);
|
||||
std::string path_to_string(XrPath path);
|
||||
|
||||
void suggest_bindings(const std::string & interaction_profile,
|
||||
std::vector<XrActionSuggestedBinding> & bindings);
|
||||
|
||||
XrTime now();
|
||||
|
||||
static std::vector<XrExtensionProperties> extensions(const char * layer_name = nullptr);
|
||||
|
||||
bool has_extension(const std::string & extension_name)
|
||||
{
|
||||
return loaded_extensions.find(extension_name) != loaded_extensions.end();
|
||||
}
|
||||
};
|
||||
} // namespace xr
|
||||
@@ -0,0 +1,259 @@
|
||||
/*
|
||||
* 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 "session.h"
|
||||
|
||||
#include "details/enumerate.h"
|
||||
#include "xr.h"
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <openxr/openxr_platform.h>
|
||||
|
||||
xr::session::session(xr::instance & inst, xr::system & sys, VkInstance vk_inst, VkPhysicalDevice pdev, VkDevice dev, int queue_family_index) :
|
||||
inst(&inst)
|
||||
{
|
||||
XrGraphicsBindingVulkan2KHR vulkan_binding{};
|
||||
vulkan_binding.type = XR_TYPE_GRAPHICS_BINDING_VULKAN2_KHR;
|
||||
|
||||
vulkan_binding.instance = vk_inst;
|
||||
vulkan_binding.physicalDevice = pdev;
|
||||
vulkan_binding.device = dev;
|
||||
vulkan_binding.queueFamilyIndex = queue_family_index;
|
||||
vulkan_binding.queueIndex = 0;
|
||||
|
||||
XrSessionCreateInfo session_info{};
|
||||
session_info.type = XR_TYPE_SESSION_CREATE_INFO;
|
||||
session_info.next = &vulkan_binding;
|
||||
session_info.systemId = sys;
|
||||
CHECK_XR(xrCreateSession(inst, &session_info, &id));
|
||||
}
|
||||
|
||||
std::vector<XrReferenceSpaceType> xr::session::get_reference_spaces() const
|
||||
{
|
||||
return details::enumerate<XrReferenceSpaceType>(xrEnumerateReferenceSpaces, id);
|
||||
}
|
||||
|
||||
xr::space xr::session::create_reference_space(XrReferenceSpaceType ref, const XrPosef & pose)
|
||||
{
|
||||
XrReferenceSpaceCreateInfo create_info{};
|
||||
create_info.type = XR_TYPE_REFERENCE_SPACE_CREATE_INFO;
|
||||
create_info.referenceSpaceType = ref;
|
||||
create_info.poseInReferenceSpace = pose;
|
||||
|
||||
XrSpace s;
|
||||
CHECK_XR(xrCreateReferenceSpace(id, &create_info, &s));
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
xr::space xr::session::create_action_space(XrAction action, const XrPosef & pose)
|
||||
{
|
||||
XrActionSpaceCreateInfo create_info{};
|
||||
create_info.type = XR_TYPE_ACTION_SPACE_CREATE_INFO;
|
||||
create_info.action = action;
|
||||
create_info.poseInActionSpace = pose;
|
||||
create_info.subactionPath = XR_NULL_PATH;
|
||||
|
||||
XrSpace s;
|
||||
CHECK_XR(xrCreateActionSpace(id, &create_info, &s));
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
std::vector<VkFormat> xr::session::get_swapchain_formats() const
|
||||
{
|
||||
std::vector<VkFormat> formats;
|
||||
for (auto i: details::enumerate<int64_t>(xrEnumerateSwapchainFormats, id))
|
||||
formats.push_back(static_cast<VkFormat>(i));
|
||||
return formats;
|
||||
}
|
||||
|
||||
XrFrameState xr::session::wait_frame()
|
||||
{
|
||||
XrFrameWaitInfo wait_info{};
|
||||
wait_info.type = XR_TYPE_FRAME_WAIT_INFO;
|
||||
|
||||
XrFrameState state{};
|
||||
state.type = XR_TYPE_FRAME_STATE;
|
||||
|
||||
CHECK_XR(xrWaitFrame(id, &wait_info, &state));
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
void xr::session::begin_frame()
|
||||
{
|
||||
XrFrameBeginInfo begin_info{};
|
||||
begin_info.type = XR_TYPE_FRAME_BEGIN_INFO;
|
||||
|
||||
CHECK_XR(xrBeginFrame(id, &begin_info));
|
||||
}
|
||||
|
||||
void xr::session::end_frame(XrTime display_time, const std::vector<XrCompositionLayerBaseHeader *> & layers, XrEnvironmentBlendMode blend_mode)
|
||||
{
|
||||
XrFrameEndInfo end_info{};
|
||||
end_info.type = XR_TYPE_FRAME_END_INFO;
|
||||
end_info.displayTime = display_time;
|
||||
end_info.environmentBlendMode = blend_mode;
|
||||
end_info.layerCount = layers.size();
|
||||
end_info.layers = layers.data();
|
||||
|
||||
CHECK_XR(xrEndFrame(id, &end_info));
|
||||
}
|
||||
|
||||
void xr::session::begin_session(XrViewConfigurationType view_config)
|
||||
{
|
||||
XrSessionBeginInfo begin_info{};
|
||||
begin_info.type = XR_TYPE_SESSION_BEGIN_INFO;
|
||||
begin_info.primaryViewConfigurationType = view_config;
|
||||
|
||||
CHECK_XR(xrBeginSession(id, &begin_info));
|
||||
}
|
||||
|
||||
void xr::session::end_session()
|
||||
{
|
||||
CHECK_XR(xrEndSession(id));
|
||||
}
|
||||
|
||||
std::pair<XrViewStateFlags, std::vector<XrView>> xr::session::locate_views(XrViewConfigurationType view_config_type,
|
||||
XrTime display_time,
|
||||
XrSpace space)
|
||||
{
|
||||
XrViewLocateInfo view_locate_info{};
|
||||
view_locate_info.type = XR_TYPE_VIEW_LOCATE_INFO;
|
||||
view_locate_info.viewConfigurationType = view_config_type;
|
||||
view_locate_info.displayTime = display_time;
|
||||
view_locate_info.space = space;
|
||||
|
||||
XrViewState view_state{};
|
||||
view_state.type = XR_TYPE_VIEW_STATE;
|
||||
|
||||
auto views = details::enumerate<XrView>(xrLocateViews, id, &view_locate_info, &view_state);
|
||||
|
||||
return {view_state.viewStateFlags, views};
|
||||
}
|
||||
|
||||
std::string xr::session::get_current_interaction_profile(const std::string & path)
|
||||
{
|
||||
XrInteractionProfileState state{};
|
||||
state.type = XR_TYPE_INTERACTION_PROFILE_STATE;
|
||||
CHECK_XR(xrGetCurrentInteractionProfile(id, inst->string_to_path(path), &state));
|
||||
|
||||
return inst->path_to_string(state.interactionProfile);
|
||||
}
|
||||
|
||||
void xr::session::attach_actionsets(const std::vector<XrActionSet> & actionsets)
|
||||
{
|
||||
XrSessionActionSetsAttachInfo attach_info{};
|
||||
attach_info.type = XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO;
|
||||
attach_info.countActionSets = actionsets.size();
|
||||
attach_info.actionSets = actionsets.data();
|
||||
|
||||
CHECK_XR(xrAttachSessionActionSets(id, &attach_info));
|
||||
}
|
||||
|
||||
std::vector<std::string> xr::session::sources_for_action(XrAction action)
|
||||
{
|
||||
XrBoundSourcesForActionEnumerateInfo action_info{
|
||||
.type = XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO,
|
||||
.action = action,
|
||||
};
|
||||
|
||||
auto sources = xr::details::enumerate<XrPath>(xrEnumerateBoundSourcesForAction, id, &action_info);
|
||||
|
||||
std::vector<std::string> sources_name;
|
||||
sources_name.reserve(sources.size());
|
||||
for (XrPath path: sources)
|
||||
{
|
||||
sources_name.push_back(inst->path_to_string(path));
|
||||
}
|
||||
|
||||
return sources_name;
|
||||
}
|
||||
|
||||
std::vector<std::string> xr::session::localized_sources_for_action(XrAction action, XrInputSourceLocalizedNameFlags components)
|
||||
{
|
||||
XrBoundSourcesForActionEnumerateInfo action_info{
|
||||
.type = XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO,
|
||||
.action = action,
|
||||
};
|
||||
|
||||
auto sources = xr::details::enumerate<XrPath>(xrEnumerateBoundSourcesForAction, id, &action_info);
|
||||
|
||||
std::vector<std::string> sources_name;
|
||||
sources_name.reserve(sources.size());
|
||||
for (XrPath path: details::enumerate<XrPath>(xrEnumerateBoundSourcesForAction, id, &action_info))
|
||||
{
|
||||
XrInputSourceLocalizedNameGetInfo name_info{
|
||||
.type = XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO,
|
||||
.sourcePath = path,
|
||||
.whichComponents = components,
|
||||
};
|
||||
|
||||
sources_name.push_back(details::enumerate<char>(xrGetInputSourceLocalizedName, id, &name_info));
|
||||
}
|
||||
|
||||
return sources_name;
|
||||
}
|
||||
|
||||
float xr::session::get_current_refresh_rate()
|
||||
{
|
||||
auto xrGetDisplayRefreshRateFB = inst->get_proc<PFN_xrGetDisplayRefreshRateFB>("xrGetDisplayRefreshRateFB");
|
||||
|
||||
float refresh_rate = 0;
|
||||
if (xrGetDisplayRefreshRateFB)
|
||||
CHECK_XR(xrGetDisplayRefreshRateFB(id, &refresh_rate));
|
||||
|
||||
return refresh_rate;
|
||||
}
|
||||
|
||||
std::vector<float> xr::session::get_refresh_rates()
|
||||
{
|
||||
auto xrEnumerateDisplayRefreshRatesFB = inst->get_proc<PFN_xrEnumerateDisplayRefreshRatesFB>("xrEnumerateDisplayRefreshRatesFB");
|
||||
|
||||
if (xrEnumerateDisplayRefreshRatesFB)
|
||||
return xr::details::enumerate<float>(xrEnumerateDisplayRefreshRatesFB, id);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void xr::session::sync_actions(XrActionSet action_set, XrPath subaction_path)
|
||||
{
|
||||
XrActiveActionSet active_action_set{
|
||||
.actionSet = action_set,
|
||||
.subactionPath = subaction_path};
|
||||
|
||||
XrActionsSyncInfo sync_info{
|
||||
.type = XR_TYPE_ACTIONS_SYNC_INFO,
|
||||
.countActiveActionSets = 1,
|
||||
.activeActionSets = &active_action_set,
|
||||
};
|
||||
|
||||
CHECK_XR(xrSyncActions(id, &sync_info));
|
||||
}
|
||||
|
||||
void xr::session::sync_actions(XrActionSet action_set, const std::string & subaction_path)
|
||||
{
|
||||
sync_actions(action_set, inst->string_to_path(subaction_path));
|
||||
}
|
||||
|
||||
xr::session::~session()
|
||||
{
|
||||
if (id != XR_NULL_HANDLE)
|
||||
xrDestroySession(id);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
#include "space.h"
|
||||
|
||||
namespace xr
|
||||
{
|
||||
class instance;
|
||||
class system;
|
||||
|
||||
class session : public utils::handle<XrSession>
|
||||
{
|
||||
instance * inst = nullptr;
|
||||
|
||||
public:
|
||||
session() = default;
|
||||
session(instance &, system &, VkInstance, VkPhysicalDevice, VkDevice, int queue_family_index);
|
||||
session(session &&) = default;
|
||||
session & operator=(session &&) = default;
|
||||
|
||||
~session();
|
||||
|
||||
std::vector<XrReferenceSpaceType> get_reference_spaces() const;
|
||||
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}});
|
||||
|
||||
std::vector<VkFormat> get_swapchain_formats() const;
|
||||
|
||||
XrFrameState wait_frame();
|
||||
void begin_frame();
|
||||
void end_frame(XrTime display_time, const std::vector<XrCompositionLayerBaseHeader *> & layers, XrEnvironmentBlendMode blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE);
|
||||
|
||||
void begin_session(XrViewConfigurationType view_config);
|
||||
void end_session();
|
||||
|
||||
std::pair<XrViewStateFlags, std::vector<XrView>> locate_views(XrViewConfigurationType view_config_type,
|
||||
XrTime display_time,
|
||||
XrSpace space);
|
||||
|
||||
std::string get_current_interaction_profile(const std::string & path);
|
||||
void attach_actionsets(const std::vector<XrActionSet> & actionsets);
|
||||
std::vector<std::string> sources_for_action(XrAction a);
|
||||
std::vector<std::string> localized_sources_for_action(XrAction action, XrInputSourceLocalizedNameFlags components = XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT | XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT | XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT);
|
||||
|
||||
float get_current_refresh_rate();
|
||||
std::vector<float> get_refresh_rates();
|
||||
|
||||
void sync_actions(XrActionSet action_set, XrPath subaction_path = XR_NULL_PATH);
|
||||
void sync_actions(XrActionSet action_set, const std::string & subaction_path);
|
||||
};
|
||||
} // namespace xr
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* 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/handle.h"
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
namespace xr
|
||||
{
|
||||
class space : public utils::handle<XrSpace>
|
||||
{
|
||||
public:
|
||||
space() = default;
|
||||
space(XrSpace s)
|
||||
{
|
||||
id = s;
|
||||
}
|
||||
space(space &&) = default;
|
||||
space & operator=(space &&) = default;
|
||||
|
||||
~space()
|
||||
{
|
||||
if (id != XR_NULL_HANDLE)
|
||||
xrDestroySpace(id);
|
||||
}
|
||||
};
|
||||
} // namespace xr
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* 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 "swapchain.h"
|
||||
#include "details/enumerate.h"
|
||||
#include "error.h"
|
||||
#include "session.h"
|
||||
#include "vk/vk.h"
|
||||
#include "xr.h"
|
||||
|
||||
xr::swapchain::swapchain(xr::session & s, VkDevice device, VkFormat format, uint32_t width, uint32_t height, int sample_count) :
|
||||
device(device)
|
||||
{
|
||||
assert(sample_count == 1);
|
||||
|
||||
XrSwapchainCreateInfo create_info{};
|
||||
create_info.type = XR_TYPE_SWAPCHAIN_CREATE_INFO;
|
||||
create_info.createFlags = 0;
|
||||
create_info.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT;
|
||||
create_info.format = format;
|
||||
create_info.sampleCount = sample_count;
|
||||
create_info.width = width;
|
||||
create_info.height = height;
|
||||
create_info.faceCount = 1;
|
||||
create_info.arraySize = 1;
|
||||
create_info.mipCount = 1;
|
||||
|
||||
width_ = width;
|
||||
height_ = height;
|
||||
sample_count_ = sample_count;
|
||||
format_ = format;
|
||||
|
||||
CHECK_XR(xrCreateSwapchain(s, &create_info, &id));
|
||||
|
||||
std::vector<XrSwapchainImageVulkanKHR> array =
|
||||
details::enumerate<XrSwapchainImageVulkanKHR>(xrEnumerateSwapchainImages, id);
|
||||
|
||||
images_.resize(array.size());
|
||||
for (uint32_t i = 0; i < array.size(); i++)
|
||||
{
|
||||
images_[i].image = array[i].image;
|
||||
|
||||
VkImageViewCreateInfo iv_create_info{};
|
||||
iv_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
|
||||
iv_create_info.image = array[i].image;
|
||||
iv_create_info.viewType = VkImageViewType::VK_IMAGE_VIEW_TYPE_2D;
|
||||
iv_create_info.format = format;
|
||||
iv_create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
|
||||
iv_create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
|
||||
iv_create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
|
||||
iv_create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
|
||||
iv_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
iv_create_info.subresourceRange.baseMipLevel = 0;
|
||||
iv_create_info.subresourceRange.levelCount = 1;
|
||||
iv_create_info.subresourceRange.baseArrayLayer = 0;
|
||||
iv_create_info.subresourceRange.layerCount = 1;
|
||||
CHECK_VK(vkCreateImageView(device, &iv_create_info, nullptr, &images_[i].view));
|
||||
}
|
||||
}
|
||||
|
||||
xr::swapchain::~swapchain()
|
||||
{
|
||||
for (auto & i: images_)
|
||||
{
|
||||
if (i.view)
|
||||
vkDestroyImageView(device, i.view, nullptr);
|
||||
}
|
||||
|
||||
if (id != XR_NULL_HANDLE)
|
||||
xrDestroySwapchain(id);
|
||||
}
|
||||
|
||||
int xr::swapchain::acquire()
|
||||
{
|
||||
uint32_t index;
|
||||
|
||||
XrSwapchainImageAcquireInfo acquire_info{};
|
||||
acquire_info.type = XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO;
|
||||
|
||||
CHECK_XR(xrAcquireSwapchainImage(id, &acquire_info, &index));
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
bool xr::swapchain::wait(XrDuration timeout)
|
||||
{
|
||||
XrSwapchainImageWaitInfo wait_info{};
|
||||
wait_info.type = XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO;
|
||||
wait_info.timeout = timeout;
|
||||
|
||||
XrResult result = xrWaitSwapchainImage(id, &wait_info);
|
||||
CHECK_XR(result, "xrWaitSwapchainImage");
|
||||
return result == XR_SUCCESS;
|
||||
}
|
||||
|
||||
void xr::swapchain::release()
|
||||
{
|
||||
XrSwapchainImageReleaseInfo release_info{};
|
||||
release_info.type = XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO;
|
||||
|
||||
CHECK_XR(xrReleaseSwapchainImage(id, &release_info));
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* 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
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#include <android_native_app_glue.h>
|
||||
#endif
|
||||
|
||||
#include "utils/handle.h"
|
||||
#include <vector>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <openxr/openxr.h>
|
||||
#include <openxr/openxr_platform.h>
|
||||
|
||||
namespace xr
|
||||
{
|
||||
class session;
|
||||
|
||||
class swapchain : public utils::handle<XrSwapchain>
|
||||
{
|
||||
public:
|
||||
struct image
|
||||
{
|
||||
VkImage image{};
|
||||
VkImageView view{};
|
||||
};
|
||||
|
||||
private:
|
||||
VkDevice device;
|
||||
uint32_t width_;
|
||||
uint32_t height_;
|
||||
int sample_count_;
|
||||
VkFormat format_;
|
||||
|
||||
std::vector<image> images_;
|
||||
|
||||
public:
|
||||
swapchain() = default;
|
||||
swapchain(session &, VkDevice device, VkFormat format, uint32_t width, uint32_t height, int sample_count = 1);
|
||||
swapchain(swapchain &&) = default;
|
||||
swapchain(const swapchain &) = delete;
|
||||
swapchain & operator=(swapchain &&) = default;
|
||||
swapchain & operator=(const swapchain &) = delete;
|
||||
~swapchain();
|
||||
|
||||
uint32_t width() const
|
||||
{
|
||||
return width_;
|
||||
}
|
||||
uint32_t height() const
|
||||
{
|
||||
return height_;
|
||||
}
|
||||
int sample_count() const
|
||||
{
|
||||
return sample_count_;
|
||||
}
|
||||
const std::vector<image> & images() const
|
||||
{
|
||||
return images_;
|
||||
};
|
||||
std::vector<image> & images()
|
||||
{
|
||||
return images_;
|
||||
}
|
||||
VkFormat format() const
|
||||
{
|
||||
return format_;
|
||||
}
|
||||
|
||||
int acquire();
|
||||
bool wait(XrDuration timeout = XR_INFINITE_DURATION);
|
||||
void release();
|
||||
};
|
||||
} // namespace xr
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user