diff --git a/src/xrt/auxiliary/android/android_ahardwarebuffer_allocator.c b/src/xrt/auxiliary/android/android_ahardwarebuffer_allocator.c index e1a773304..1dc86516d 100644 --- a/src/xrt/auxiliary/android/android_ahardwarebuffer_allocator.c +++ b/src/xrt/auxiliary/android/android_ahardwarebuffer_allocator.c @@ -19,61 +19,43 @@ #ifdef XRT_GRAPHICS_BUFFER_HANDLE_IS_AHARDWAREBUFFER #include -DEBUG_GET_ONCE_LOG_OPTION(ahardwarebuffer_log, - "AHARDWAREBUFFER_LOG", - U_LOGGING_WARN) -#define AHB_TRACE(...) \ - U_LOG_IFL_T(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) -#define AHB_DEBUG(...) \ - U_LOG_IFL_D(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) -#define AHB_INFO(...) \ - U_LOG_IFL_I(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) -#define AHB_WARN(...) \ - U_LOG_IFL_W(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) -#define AHB_ERROR(...) \ - U_LOG_IFL_E(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) +DEBUG_GET_ONCE_LOG_OPTION(ahardwarebuffer_log, "AHARDWAREBUFFER_LOG", U_LOGGING_WARN) +#define AHB_TRACE(...) U_LOG_IFL_T(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) +#define AHB_DEBUG(...) U_LOG_IFL_D(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) +#define AHB_INFO(...) U_LOG_IFL_I(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) +#define AHB_WARN(...) U_LOG_IFL_W(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) +#define AHB_ERROR(...) U_LOG_IFL_E(debug_get_log_option_ahardwarebuffer_log(), __VA_ARGS__) static inline enum AHardwareBuffer_Format vk_format_to_ahardwarebuffer(uint64_t format) { switch (format) { - case VK_FORMAT_X8_D24_UNORM_PACK32: - return AHARDWAREBUFFER_FORMAT_D24_UNORM; - case VK_FORMAT_D24_UNORM_S8_UINT: - return AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT; - case VK_FORMAT_R5G6B5_UNORM_PACK16: - return AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM; + case VK_FORMAT_X8_D24_UNORM_PACK32: return AHARDWAREBUFFER_FORMAT_D24_UNORM; + case VK_FORMAT_D24_UNORM_S8_UINT: return AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT; + case VK_FORMAT_R5G6B5_UNORM_PACK16: return AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM; case VK_FORMAT_D16_UNORM: return AHARDWAREBUFFER_FORMAT_D16_UNORM; case VK_FORMAT_R8G8B8_UNORM: return AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM; - case VK_FORMAT_D32_SFLOAT_S8_UINT: - return AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT; - case VK_FORMAT_A2B10G10R10_UNORM_PACK32: - return AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM; + case VK_FORMAT_D32_SFLOAT_S8_UINT: return AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT; + case VK_FORMAT_A2B10G10R10_UNORM_PACK32: return AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM; case VK_FORMAT_S8_UINT: return AHARDWAREBUFFER_FORMAT_S8_UINT; case VK_FORMAT_D32_SFLOAT: return AHARDWAREBUFFER_FORMAT_D32_FLOAT; - case VK_FORMAT_R16G16B16A16_SFLOAT: - return AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT; + case VK_FORMAT_R16G16B16A16_SFLOAT: return AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT; case VK_FORMAT_R8G8B8A8_SRGB: /* apply EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_SRGB_KHR! */ return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM; - case VK_FORMAT_R8G8B8A8_UNORM: - return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM; + case VK_FORMAT_R8G8B8A8_UNORM: return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM; default: return 0; } } xrt_result_t -ahardwarebuffer_image_allocate(const struct xrt_swapchain_create_info *xsci, - xrt_graphics_buffer_handle_t *out_image) +ahardwarebuffer_image_allocate(const struct xrt_swapchain_create_info *xsci, xrt_graphics_buffer_handle_t *out_image) { AHardwareBuffer_Desc desc; U_ZERO(&desc); - enum AHardwareBuffer_Format ahb_format = - vk_format_to_ahardwarebuffer(xsci->format); + enum AHardwareBuffer_Format ahb_format = vk_format_to_ahardwarebuffer(xsci->format); if (ahb_format == 0) { - AHB_ERROR("Could not convert %04" PRIx64 - " to AHardwareBuffer_Format!", - (uint64_t)xsci->format); + AHB_ERROR("Could not convert %04" PRIx64 " to AHardwareBuffer_Format!", (uint64_t)xsci->format); return XRT_ERROR_ALLOCATION; } desc.height = xsci->height; @@ -84,8 +66,7 @@ ahardwarebuffer_image_allocate(const struct xrt_swapchain_create_info *xsci, desc.usage |= AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP; desc.layers *= 6; } - if (0 != (xsci->bits & (XRT_SWAPCHAIN_USAGE_COLOR | - XRT_SWAPCHAIN_USAGE_DEPTH_STENCIL))) { + if (0 != (xsci->bits & (XRT_SWAPCHAIN_USAGE_COLOR | XRT_SWAPCHAIN_USAGE_DEPTH_STENCIL))) { desc.usage |= AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER; } if (0 != (xsci->bits & XRT_SWAPCHAIN_USAGE_SAMPLED)) { @@ -119,12 +100,9 @@ ahardwarebuffer_images_allocate(struct xrt_image_native_allocator *xina, { AHardwareBuffer_Desc desc; U_ZERO(&desc); - enum AHardwareBuffer_Format ahb_format = - vk_format_to_ahardwarebuffer(xsci->format); + enum AHardwareBuffer_Format ahb_format = vk_format_to_ahardwarebuffer(xsci->format); if (ahb_format == 0) { - AHB_ERROR("Could not convert %04" PRIx64 - " to AHardwareBuffer_Format!", - (uint64_t)xsci->format); + AHB_ERROR("Could not convert %04" PRIx64 " to AHardwareBuffer_Format!", (uint64_t)xsci->format); return XRT_ERROR_ALLOCATION; } desc.height = xsci->height; @@ -135,8 +113,7 @@ ahardwarebuffer_images_allocate(struct xrt_image_native_allocator *xina, desc.usage |= AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP; desc.layers *= 6; } - if (0 != (xsci->bits & (XRT_SWAPCHAIN_USAGE_COLOR | - XRT_SWAPCHAIN_USAGE_DEPTH_STENCIL))) { + if (0 != (xsci->bits & (XRT_SWAPCHAIN_USAGE_COLOR | XRT_SWAPCHAIN_USAGE_DEPTH_STENCIL))) { desc.usage |= AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER; } if (0 != (xsci->bits & XRT_SWAPCHAIN_USAGE_SAMPLED)) { @@ -156,8 +133,7 @@ ahardwarebuffer_images_allocate(struct xrt_image_native_allocator *xina, memset(out_images, 0, sizeof(*out_images) * num_images); bool failed = false; for (size_t i = 0; i < num_images; ++i) { - int ret = - AHardwareBuffer_allocate(&desc, &(out_images[i].handle)); + int ret = AHardwareBuffer_allocate(&desc, &(out_images[i].handle)); if (ret != 0) { AHB_ERROR("Failed allocating image %d.", (int)i); failed = true; @@ -174,9 +150,7 @@ ahardwarebuffer_images_allocate(struct xrt_image_native_allocator *xina, } static xrt_result_t -ahardwarebuffer_images_free(struct xrt_image_native_allocator *xina, - size_t num_images, - struct xrt_image_native *images) +ahardwarebuffer_images_free(struct xrt_image_native_allocator *xina, size_t num_images, struct xrt_image_native *images) { for (size_t i = 0; i < num_images; ++i) { u_graphics_buffer_unref(&(images[i].handle)); @@ -194,8 +168,7 @@ ahardwarebuffer_destroy(struct xrt_image_native_allocator *xina) struct xrt_image_native_allocator * android_ahardwarebuffer_allocator_create() { - struct xrt_image_native_allocator *xina = - U_TYPED_CALLOC(struct xrt_image_native_allocator); + struct xrt_image_native_allocator *xina = U_TYPED_CALLOC(struct xrt_image_native_allocator); xina->images_allocate = ahardwarebuffer_images_allocate; xina->images_free = ahardwarebuffer_images_free; xina->destroy = ahardwarebuffer_destroy; diff --git a/src/xrt/auxiliary/android/android_ahardwarebuffer_allocator.h b/src/xrt/auxiliary/android/android_ahardwarebuffer_allocator.h index 1df9db9d2..db061a708 100644 --- a/src/xrt/auxiliary/android/android_ahardwarebuffer_allocator.h +++ b/src/xrt/auxiliary/android/android_ahardwarebuffer_allocator.h @@ -23,8 +23,7 @@ struct xrt_image_native_allocator * android_ahardwarebuffer_allocator_create(); xrt_result_t -ahardwarebuffer_image_allocate(const struct xrt_swapchain_create_info *xsci, - xrt_graphics_buffer_handle_t *out_image); +ahardwarebuffer_image_allocate(const struct xrt_swapchain_create_info *xsci, xrt_graphics_buffer_handle_t *out_image); #endif // XRT_GRAPHICS_BUFFER_HANDLE_IS_AHARDWAREBUFFER diff --git a/src/xrt/auxiliary/android/android_custom_surface.cpp b/src/xrt/auxiliary/android/android_custom_surface.cpp index 2510e0bc4..829f01fd4 100644 --- a/src/xrt/auxiliary/android/android_custom_surface.cpp +++ b/src/xrt/auxiliary/android/android_custom_surface.cpp @@ -47,13 +47,11 @@ android_custom_surface::~android_custom_surface() } } catch (std::exception const &e) { // Must catch and ignore any exceptions in the destructor! - U_LOG_E("Failure while marking MonadoView as discarded: %s", - e.what()); + U_LOG_E("Failure while marking MonadoView as discarded: %s", e.what()); } } -constexpr auto FULLY_QUALIFIED_CLASSNAME = - "org.freedesktop.monado.auxiliary.MonadoView"; +constexpr auto FULLY_QUALIFIED_CLASSNAME = "org.freedesktop.monado.auxiliary.MonadoView"; struct android_custom_surface * android_custom_surface_async_start(struct _JavaVM *vm, void *activity) @@ -62,18 +60,16 @@ android_custom_surface_async_start(struct _JavaVM *vm, void *activity) try { auto info = getAppInfo(XRT_ANDROID_PACKAGE, (jobject)activity); if (info.isNull()) { - U_LOG_E( - "Could not get application info for package '%s'", - "org.freedesktop.monado.openxr_runtime"); + U_LOG_E("Could not get application info for package '%s'", + "org.freedesktop.monado.openxr_runtime"); return nullptr; } - auto clazz = loadClassFromPackage(info, (jobject)activity, - FULLY_QUALIFIED_CLASSNAME); + auto clazz = loadClassFromPackage(info, (jobject)activity, FULLY_QUALIFIED_CLASSNAME); if (clazz.isNull()) { - U_LOG_E("Could not load class '%s' from package '%s'", - FULLY_QUALIFIED_CLASSNAME, XRT_ANDROID_PACKAGE); + U_LOG_E("Could not load class '%s' from package '%s'", FULLY_QUALIFIED_CLASSNAME, + XRT_ANDROID_PACKAGE); return nullptr; } @@ -84,8 +80,7 @@ android_custom_surface_async_start(struct _JavaVM *vm, void *activity) // the 0 is to avoid this being considered "temporary" and to // create a global ref. - ret->monadoViewClass = - jni::Class((jclass)clazz.object().getHandle(), 0); + ret->monadoViewClass = jni::Class((jclass)clazz.object().getHandle(), 0); if (ret->monadoViewClass.isNull()) { U_LOG_E("monadoViewClass was null"); @@ -94,13 +89,11 @@ android_custom_surface_async_start(struct _JavaVM *vm, void *activity) std::string clazz_name = ret->monadoViewClass.getName(); if (clazz_name != FULLY_QUALIFIED_CLASSNAME) { - U_LOG_E("Unexpected class name: %s", - clazz_name.c_str()); + U_LOG_E("Unexpected class name: %s", clazz_name.c_str()); return nullptr; } - ret->monadoView = - MonadoView::attachToActivity(ret->activity, ret.get()); + ret->monadoView = MonadoView::attachToActivity(ret->activity, ret.get()); return ret.release(); } catch (std::exception const &e) { @@ -115,8 +108,7 @@ android_custom_surface_async_start(struct _JavaVM *vm, void *activity) void -android_custom_surface_destroy( - struct android_custom_surface **ptr_custom_surface) +android_custom_surface_destroy(struct android_custom_surface **ptr_custom_surface) { if (ptr_custom_surface == NULL) { return; @@ -130,13 +122,11 @@ android_custom_surface_destroy( } ANativeWindow * -android_custom_surface_wait_get_surface( - struct android_custom_surface *custom_surface, uint64_t timeout_ms) +android_custom_surface_wait_get_surface(struct android_custom_surface *custom_surface, uint64_t timeout_ms) { SurfaceHolder surfaceHolder{}; try { - surfaceHolder = - custom_surface->monadoView.waitGetSurfaceHolder(timeout_ms); + surfaceHolder = custom_surface->monadoView.waitGetSurfaceHolder(timeout_ms); } catch (std::exception const &e) { // do nothing right now. @@ -154,49 +144,43 @@ android_custom_surface_wait_get_surface( if (surf.isNull()) { return nullptr; } - return ANativeWindow_fromSurface(jni::env(), - surf.object().makeLocalReference()); + return ANativeWindow_fromSurface(jni::env(), surf.object().makeLocalReference()); } bool -android_custom_surface_get_display_metrics( - struct _JavaVM *vm, - void *activity, - struct xrt_android_display_metrics *out_metrics) +android_custom_surface_get_display_metrics(struct _JavaVM *vm, + void *activity, + struct xrt_android_display_metrics *out_metrics) { jni::init(vm); try { auto info = getAppInfo(XRT_ANDROID_PACKAGE, (jobject)activity); if (info.isNull()) { - U_LOG_E( - "Could not get application info for package '%s'", - "org.freedesktop.monado.openxr_runtime"); + U_LOG_E("Could not get application info for package '%s'", + "org.freedesktop.monado.openxr_runtime"); return false; } - auto clazz = loadClassFromPackage(info, (jobject)activity, - FULLY_QUALIFIED_CLASSNAME); + auto clazz = loadClassFromPackage(info, (jobject)activity, FULLY_QUALIFIED_CLASSNAME); if (clazz.isNull()) { - U_LOG_E("Could not load class '%s' from package '%s'", - FULLY_QUALIFIED_CLASSNAME, XRT_ANDROID_PACKAGE); + U_LOG_E("Could not load class '%s' from package '%s'", FULLY_QUALIFIED_CLASSNAME, + XRT_ANDROID_PACKAGE); return false; } // Teach the wrapper our class before we start to use it. MonadoView::staticInitClass((jclass)clazz.object().getHandle()); - jni::Object displayMetrics = - MonadoView::getDisplayMetrics(Activity((jobject)activity)); - - *out_metrics = { - .width_pixels = displayMetrics.get("widthPixels"), - .height_pixels = displayMetrics.get("heightPixels"), - .density_dpi = displayMetrics.get("densityDpi"), - .density = displayMetrics.get("xdpi"), - .scaled_density = displayMetrics.get("ydpi"), - .xdpi = displayMetrics.get("density"), - .ydpi = displayMetrics.get("scaledDensity")}; + jni::Object displayMetrics = MonadoView::getDisplayMetrics(Activity((jobject)activity)); + + *out_metrics = {.width_pixels = displayMetrics.get("widthPixels"), + .height_pixels = displayMetrics.get("heightPixels"), + .density_dpi = displayMetrics.get("densityDpi"), + .density = displayMetrics.get("xdpi"), + .scaled_density = displayMetrics.get("ydpi"), + .xdpi = displayMetrics.get("density"), + .ydpi = displayMetrics.get("scaledDensity")}; return true; } catch (std::exception const &e) { diff --git a/src/xrt/auxiliary/android/android_custom_surface.h b/src/xrt/auxiliary/android/android_custom_surface.h index fe65a8275..f42126a49 100644 --- a/src/xrt/auxiliary/android/android_custom_surface.h +++ b/src/xrt/auxiliary/android/android_custom_surface.h @@ -74,8 +74,7 @@ android_custom_surface_async_start(struct _JavaVM *vm, void *activity); * @public @memberof android_custom_surface */ void -android_custom_surface_destroy( - struct android_custom_surface **ptr_custom_surface); +android_custom_surface_destroy(struct android_custom_surface **ptr_custom_surface); /*! * Get the ANativeWindow pointer corresponding to the added Surface, if @@ -86,14 +85,12 @@ android_custom_surface_destroy( * @public @memberof android_custom_surface */ ANativeWindow * -android_custom_surface_wait_get_surface( - struct android_custom_surface *custom_surface, uint64_t timeout_ms); +android_custom_surface_wait_get_surface(struct android_custom_surface *custom_surface, uint64_t timeout_ms); bool -android_custom_surface_get_display_metrics( - struct _JavaVM *vm, - void *activity, - struct xrt_android_display_metrics *out_metrics); +android_custom_surface_get_display_metrics(struct _JavaVM *vm, + void *activity, + struct xrt_android_display_metrics *out_metrics); #ifdef __cplusplus } diff --git a/src/xrt/auxiliary/android/android_load_class.cpp b/src/xrt/auxiliary/android/android_load_class.cpp index b3efff23b..24b2a85f9 100644 --- a/src/xrt/auxiliary/android/android_load_class.cpp +++ b/src/xrt/auxiliary/android/android_load_class.cpp @@ -29,8 +29,7 @@ getAppInfo(std::string const &packageName, jobject application_context) U_LOG_E("getAppInfo: application_context was null"); return {}; } - auto packageManager = - PackageManager{context.getPackageManager()}; + auto packageManager = PackageManager{context.getPackageManager()}; if (packageManager.isNull()) { U_LOG_E( "getAppInfo: " @@ -39,8 +38,7 @@ getAppInfo(std::string const &packageName, jobject application_context) return {}; } auto packageInfo = packageManager.getPackageInfo( - packageName, PackageManager::GET_META_DATA | - PackageManager::GET_SHARED_LIBRARY_FILES); + packageName, PackageManager::GET_META_DATA | PackageManager::GET_SHARED_LIBRARY_FILES); if (packageInfo.isNull()) { U_LOG_E( @@ -57,24 +55,19 @@ getAppInfo(std::string const &packageName, jobject application_context) } wrap::java::lang::Class -loadClassFromPackage(ApplicationInfo applicationInfo, - jobject application_context, - const char *clazz_name) +loadClassFromPackage(ApplicationInfo applicationInfo, jobject application_context, const char *clazz_name) { auto context = Context{application_context}.getApplicationContext(); auto pkgContext = context.createPackageContext( - applicationInfo.getPackageName(), - Context::CONTEXT_IGNORE_SECURITY | Context::CONTEXT_INCLUDE_CODE); + applicationInfo.getPackageName(), Context::CONTEXT_IGNORE_SECURITY | Context::CONTEXT_INCLUDE_CODE); // Not using ClassLoader.loadClass because it expects a /-delimited // class name, while we have a .-delimited class name. // This does work - wrap::java::lang::ClassLoader pkgClassLoader = - pkgContext.getClassLoader(); + wrap::java::lang::ClassLoader pkgClassLoader = pkgContext.getClassLoader(); try { - auto loadedClass = - pkgClassLoader.loadClass(std::string(clazz_name)); + auto loadedClass = pkgClassLoader.loadClass(std::string(clazz_name)); if (loadedClass.isNull()) { U_LOG_E("Could not load class for name %s", clazz_name); return wrap::java::lang::Class(); @@ -82,8 +75,7 @@ loadClassFromPackage(ApplicationInfo applicationInfo, return loadedClass; } catch (std::exception const &e) { - U_LOG_E("Could load class '%s' forName: %s", clazz_name, - e.what()); + U_LOG_E("Could load class '%s' forName: %s", clazz_name, e.what()); return wrap::java::lang::Class(); } } @@ -98,15 +90,12 @@ android_load_class_from_package(struct _JavaVM *vm, Context context((jobject)application_context); auto info = getAppInfo(pkgname, (jobject)application_context); if (info.isNull()) { - U_LOG_E("Could not get application info for package '%s'", - pkgname); + U_LOG_E("Could not get application info for package '%s'", pkgname); return nullptr; } - auto clazz = - loadClassFromPackage(info, (jobject)application_context, classname); + auto clazz = loadClassFromPackage(info, (jobject)application_context, classname); if (clazz.isNull()) { - U_LOG_E("Could not load class '%s' from package '%s'", - classname, pkgname); + U_LOG_E("Could not load class '%s' from package '%s'", classname, pkgname); return nullptr; } return clazz.object().getHandle(); diff --git a/src/xrt/auxiliary/android/android_load_class.hpp b/src/xrt/auxiliary/android/android_load_class.hpp index 2804212be..327158c3e 100644 --- a/src/xrt/auxiliary/android/android_load_class.hpp +++ b/src/xrt/auxiliary/android/android_load_class.hpp @@ -21,8 +21,6 @@ ApplicationInfo getAppInfo(std::string const &packageName, jobject application_context); wrap::java::lang::Class -loadClassFromPackage(ApplicationInfo applicationInfo, - jobject application_context, - const char *clazz_name); +loadClassFromPackage(ApplicationInfo applicationInfo, jobject application_context, const char *clazz_name); #endif // XRT_OS_ANDROID diff --git a/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.cpp b/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.cpp index 2e4832834..63d1f34ce 100644 --- a/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.cpp +++ b/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.cpp @@ -14,17 +14,13 @@ namespace wrap { namespace org::freedesktop::monado::auxiliary { MonadoView::Meta::Meta(jni::jclass clazz) : MetaBase(MonadoView::getTypeName(), clazz), - attachToActivity(classRef().getStaticMethod( - "attachToActivity", - "(Landroid/app/Activity;J)Lorg/freedesktop/" - "monado/auxiliary/MonadoView;")), - waitGetSurfaceHolder(classRef().getMethod( - "waitGetSurfaceHolder", "(I)Landroid/view/SurfaceHolder;")), - markAsDiscardedByNative( - classRef().getMethod("markAsDiscardedByNative", "()V")), - getDisplayMetrics(classRef().getStaticMethod( - "getDisplayMetrics", - "(Landroid/app/Activity;)Landroid/util/DisplayMetrics;")) + attachToActivity(classRef().getStaticMethod("attachToActivity", + "(Landroid/app/Activity;J)Lorg/freedesktop/" + "monado/auxiliary/MonadoView;")), + waitGetSurfaceHolder(classRef().getMethod("waitGetSurfaceHolder", "(I)Landroid/view/SurfaceHolder;")), + markAsDiscardedByNative(classRef().getMethod("markAsDiscardedByNative", "()V")), + getDisplayMetrics(classRef().getStaticMethod("getDisplayMetrics", + "(Landroid/app/Activity;)Landroid/util/DisplayMetrics;")) {} } // namespace org::freedesktop::monado::auxiliary } // namespace wrap diff --git a/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.hpp b/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.hpp index 2c1a25ca1..1cea26e62 100644 --- a/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.hpp +++ b/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.hpp @@ -54,8 +54,7 @@ namespace org::freedesktop::monado::auxiliary { * */ static MonadoView - attachToActivity(android::app::Activity const &activity, - void *nativePointer); + attachToActivity(android::app::Activity const &activity, void *nativePointer); /*! * Wrapper for the waitGetSurfaceHolder method diff --git a/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.impl.hpp b/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.impl.hpp index 431838cae..a334933ea 100644 --- a/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.impl.hpp +++ b/src/xrt/auxiliary/android/org.freedesktop.monado.auxiliary.impl.hpp @@ -16,36 +16,32 @@ namespace wrap { namespace org::freedesktop::monado::auxiliary { inline MonadoView - MonadoView::attachToActivity(android::app::Activity const &activity, - void *nativePointer) + MonadoView::attachToActivity(android::app::Activity const &activity, void *nativePointer) { return MonadoView(Meta::data().clazz().call( Meta::data().attachToActivity, activity.object(), - static_cast( - reinterpret_cast(nativePointer)))); + static_cast(reinterpret_cast(nativePointer)))); } inline android::view::SurfaceHolder MonadoView::waitGetSurfaceHolder(int32_t wait_ms) { assert(!isNull()); - return android::view::SurfaceHolder(object().call( - Meta::data().waitGetSurfaceHolder, wait_ms)); + return android::view::SurfaceHolder( + object().call(Meta::data().waitGetSurfaceHolder, wait_ms)); } inline void MonadoView::markAsDiscardedByNative() { assert(!isNull()); - return object().call( - Meta::data().markAsDiscardedByNative); + return object().call(Meta::data().markAsDiscardedByNative); } inline jni::Object MonadoView::getDisplayMetrics(android::app::Activity const &activity) { - return Meta::data().clazz().call( - Meta::data().getDisplayMetrics, activity.object()); + return Meta::data().clazz().call(Meta::data().getDisplayMetrics, activity.object()); } } // namespace org::freedesktop::monado::auxiliary diff --git a/src/xrt/auxiliary/math/m_api.h b/src/xrt/auxiliary/math/m_api.h index 475097328..10ce1d101 100644 --- a/src/xrt/auxiliary/math/m_api.h +++ b/src/xrt/auxiliary/math/m_api.h @@ -105,8 +105,7 @@ math_vec3_accum(const struct xrt_vec3 *additional, struct xrt_vec3 *inAndOut); * @ingroup aux_math */ void -math_vec3_subtract(const struct xrt_vec3 *subtrahend, - struct xrt_vec3 *inAndOut); +math_vec3_subtract(const struct xrt_vec3 *subtrahend, struct xrt_vec3 *inAndOut); /*! * Multiply a vector in-place. @@ -126,9 +125,7 @@ math_vec3_scalar_mul(float scalar, struct xrt_vec3 *inAndOut); * @ingroup aux_math */ void -math_vec3_cross(const struct xrt_vec3 *l, - const struct xrt_vec3 *r, - struct xrt_vec3 *result); +math_vec3_cross(const struct xrt_vec3 *l, const struct xrt_vec3 *r, struct xrt_vec3 *result); /*! @@ -154,9 +151,7 @@ math_vec3_normalize(struct xrt_vec3 *in); * @ingroup aux_math */ void -math_quat_from_angle_vector(float angle_rads, - const struct xrt_vec3 *vector, - struct xrt_quat *result); +math_quat_from_angle_vector(float angle_rads, const struct xrt_vec3 *vector, struct xrt_quat *result); /*! * Create a rotation from a 3x3 rotation matrix. @@ -166,8 +161,7 @@ math_quat_from_angle_vector(float angle_rads, * @ingroup aux_math */ void -math_quat_from_matrix_3x3(const struct xrt_matrix_3x3 *mat, - struct xrt_quat *result); +math_quat_from_matrix_3x3(const struct xrt_matrix_3x3 *mat, struct xrt_quat *result); /*! * Create a rotation from two vectors plus x and z, by creating a rotation @@ -178,9 +172,7 @@ math_quat_from_matrix_3x3(const struct xrt_matrix_3x3 *mat, * @ingroup aux_math */ void -math_quat_from_plus_x_z(const struct xrt_vec3 *plus_x, - const struct xrt_vec3 *plus_z, - struct xrt_quat *result); +math_quat_from_plus_x_z(const struct xrt_vec3 *plus_x, const struct xrt_vec3 *plus_z, struct xrt_quat *result); /*! * Check if this quat can be used in transformation operations. @@ -229,9 +221,7 @@ math_quat_ensure_normalized(struct xrt_quat *inout); * @ingroup aux_math */ void -math_quat_rotate_vec3(const struct xrt_quat *left, - const struct xrt_vec3 *right, - struct xrt_vec3 *result); +math_quat_rotate_vec3(const struct xrt_quat *left, const struct xrt_vec3 *right, struct xrt_vec3 *result); /*! * Rotate a quaternion (compose rotations). @@ -240,9 +230,7 @@ math_quat_rotate_vec3(const struct xrt_quat *left, * @ingroup aux_math */ void -math_quat_rotate(const struct xrt_quat *left, - const struct xrt_quat *right, - struct xrt_quat *result); +math_quat_rotate(const struct xrt_quat *left, const struct xrt_quat *right, struct xrt_quat *result); /*! @@ -289,9 +277,7 @@ math_quat_finite_difference(const struct xrt_quat *quat0, * @ingroup aux_math */ void -math_quat_rotate_derivative(const struct xrt_quat *rot, - const struct xrt_vec3 *deriv, - struct xrt_vec3 *result); +math_quat_rotate_derivative(const struct xrt_quat *rot, const struct xrt_vec3 *deriv, struct xrt_vec3 *result); /* @@ -343,8 +329,7 @@ math_matrix_4x4_multiply(const struct xrt_matrix_4x4 *left, * @ingroup aux_math */ void -math_matrix_4x4_view_from_pose(const struct xrt_pose *pose, - struct xrt_matrix_4x4 *result); +math_matrix_4x4_view_from_pose(const struct xrt_pose *pose, struct xrt_matrix_4x4 *result); /*! * Compute quad layer model matrix from xrt_pose and xrt_vec2 size. @@ -353,9 +338,7 @@ math_matrix_4x4_view_from_pose(const struct xrt_pose *pose, * @ingroup aux_math */ void -math_matrix_4x4_model(const struct xrt_pose *pose, - const struct xrt_vec3 *size, - struct xrt_matrix_4x4 *result); +math_matrix_4x4_model(const struct xrt_pose *pose, const struct xrt_vec3 *size, struct xrt_matrix_4x4 *result); /*! * Compute inverse view projection matrix, @@ -404,9 +387,7 @@ math_pose_invert(const struct xrt_pose *pose, struct xrt_pose *outPose); * @ingroup aux_math */ void -math_pose_transform(const struct xrt_pose *transform, - const struct xrt_pose *pose, - struct xrt_pose *outPose); +math_pose_transform(const struct xrt_pose *transform, const struct xrt_pose *pose, struct xrt_pose *outPose); /*! * Apply a rigid-body transformation to a point. @@ -418,9 +399,7 @@ math_pose_transform(const struct xrt_pose *transform, * @ingroup aux_math */ void -math_pose_transform_point(const struct xrt_pose *transform, - const struct xrt_vec3 *point, - struct xrt_vec3 *out_point); +math_pose_transform_point(const struct xrt_pose *transform, const struct xrt_vec3 *point, struct xrt_vec3 *out_point); /* diff --git a/src/xrt/auxiliary/math/m_base.cpp b/src/xrt/auxiliary/math/m_base.cpp index 3975a0d98..4bbdf3a1d 100644 --- a/src/xrt/auxiliary/math/m_base.cpp +++ b/src/xrt/auxiliary/math/m_base.cpp @@ -104,9 +104,7 @@ math_vec3_scalar_mul(float scalar, struct xrt_vec3 *inAndOut) } extern "C" void -math_vec3_cross(const struct xrt_vec3 *l, - const struct xrt_vec3 *r, - struct xrt_vec3 *result) +math_vec3_cross(const struct xrt_vec3 *l, const struct xrt_vec3 *r, struct xrt_vec3 *result) { map_vec3(*result) = map_vec3(*l).cross(map_vec3(*r)); } @@ -124,29 +122,23 @@ math_vec3_normalize(struct xrt_vec3 *in) */ extern "C" void -math_quat_from_angle_vector(float angle_rads, - const struct xrt_vec3 *vector, - struct xrt_quat *result) +math_quat_from_angle_vector(float angle_rads, const struct xrt_vec3 *vector, struct xrt_quat *result) { map_quat(*result) = Eigen::AngleAxisf(angle_rads, copy(vector)); } extern "C" void -math_quat_from_matrix_3x3(const struct xrt_matrix_3x3 *mat, - struct xrt_quat *result) +math_quat_from_matrix_3x3(const struct xrt_matrix_3x3 *mat, struct xrt_quat *result) { Eigen::Matrix3f m; - m << mat->v[0], mat->v[1], mat->v[2], mat->v[3], mat->v[4], mat->v[5], - mat->v[6], mat->v[7], mat->v[8]; + m << mat->v[0], mat->v[1], mat->v[2], mat->v[3], mat->v[4], mat->v[5], mat->v[6], mat->v[7], mat->v[8]; Eigen::Quaternionf q(m); map_quat(*result) = q; } extern "C" void -math_quat_from_plus_x_z(const struct xrt_vec3 *plus_x, - const struct xrt_vec3 *plus_z, - struct xrt_quat *result) +math_quat_from_plus_x_z(const struct xrt_vec3 *plus_x, const struct xrt_vec3 *plus_z, struct xrt_quat *result) { xrt_vec3 plus_y; math_vec3_cross(plus_z, plus_x, &plus_y); @@ -234,9 +226,7 @@ math_quat_ensure_normalized(struct xrt_quat *inout) extern "C" void -math_quat_rotate(const struct xrt_quat *left, - const struct xrt_quat *right, - struct xrt_quat *result) +math_quat_rotate(const struct xrt_quat *left, const struct xrt_quat *right, struct xrt_quat *result) { assert(left != NULL); assert(right != NULL); @@ -251,9 +241,7 @@ math_quat_rotate(const struct xrt_quat *left, } extern "C" void -math_quat_rotate_vec3(const struct xrt_quat *left, - const struct xrt_vec3 *right, - struct xrt_vec3 *result) +math_quat_rotate_vec3(const struct xrt_quat *left, const struct xrt_vec3 *right, struct xrt_vec3 *result) { assert(left != NULL); assert(right != NULL); @@ -268,9 +256,7 @@ math_quat_rotate_vec3(const struct xrt_quat *left, } extern "C" void -math_quat_rotate_derivative(const struct xrt_quat *quat, - const struct xrt_vec3 *deriv, - struct xrt_vec3 *result) +math_quat_rotate_derivative(const struct xrt_quat *quat, const struct xrt_vec3 *deriv, struct xrt_vec3 *result) { assert(quat != NULL); assert(deriv != NULL); @@ -305,9 +291,7 @@ math_matrix_2x2_multiply(const struct xrt_matrix_2x2 *left, } extern "C" void -math_matrix_3x3_transform_vec3(const struct xrt_matrix_3x3 *left, - const struct xrt_vec3 *right, - struct xrt_vec3 *result) +math_matrix_3x3_transform_vec3(const struct xrt_matrix_3x3 *left, const struct xrt_vec3 *right, struct xrt_vec3 *result) { Eigen::Matrix3f m; m << left->v[0], left->v[1], left->v[2], // 1 @@ -333,8 +317,7 @@ math_matrix_4x4_multiply(const struct xrt_matrix_4x4 *left, } void -math_matrix_4x4_view_from_pose(const struct xrt_pose *pose, - struct xrt_matrix_4x4 *result) +math_matrix_4x4_view_from_pose(const struct xrt_pose *pose, struct xrt_matrix_4x4 *result) { Eigen::Vector3f position = copy(&pose->position); Eigen::Quaternionf orientation = copy(&pose->orientation); @@ -346,9 +329,7 @@ math_matrix_4x4_view_from_pose(const struct xrt_pose *pose, } void -math_matrix_4x4_model(const struct xrt_pose *pose, - const struct xrt_vec3 *size, - struct xrt_matrix_4x4 *result) +math_matrix_4x4_model(const struct xrt_pose *pose, const struct xrt_vec3 *size, struct xrt_matrix_4x4 *result) { Eigen::Vector3f position = copy(&pose->position); Eigen::Quaternionf orientation = copy(&pose->orientation); @@ -384,8 +365,7 @@ math_pose_validate(const struct xrt_pose *pose) { assert(pose != NULL); - return math_vec3_validate(&pose->position) && - math_quat_validate(&pose->orientation); + return math_vec3_validate(&pose->position) && math_quat_validate(&pose->orientation); } extern "C" void @@ -430,9 +410,7 @@ transform_pose(const xrt_pose &transform, const xrt_pose &pose) } extern "C" void -math_pose_transform(const struct xrt_pose *transform, - const struct xrt_pose *pose, - struct xrt_pose *outPose) +math_pose_transform(const struct xrt_pose *transform, const struct xrt_pose *pose, struct xrt_pose *outPose) { assert(pose != NULL); assert(transform != NULL); @@ -443,9 +421,7 @@ math_pose_transform(const struct xrt_pose *transform, } extern "C" void -math_pose_transform_point(const struct xrt_pose *transform, - const struct xrt_vec3 *point, - struct xrt_vec3 *out_point) +math_pose_transform_point(const struct xrt_pose *transform, const struct xrt_vec3 *point, struct xrt_vec3 *out_point) { assert(transform != NULL); assert(point != NULL); diff --git a/src/xrt/auxiliary/math/m_filter_fifo.c b/src/xrt/auxiliary/math/m_filter_fifo.c index 63cbf4a97..f5c459aed 100644 --- a/src/xrt/auxiliary/math/m_filter_fifo.c +++ b/src/xrt/auxiliary/math/m_filter_fifo.c @@ -95,9 +95,7 @@ m_ff_vec3_f32_get_num(struct m_ff_vec3_f32 *ff) } void -m_ff_vec3_f32_push(struct m_ff_vec3_f32 *ff, - const struct xrt_vec3 *sample, - uint64_t timestamp_ns) +m_ff_vec3_f32_push(struct m_ff_vec3_f32 *ff, const struct xrt_vec3 *sample, uint64_t timestamp_ns) { assert(ff->timestamps_ns[ff->latest] <= timestamp_ns); @@ -110,10 +108,7 @@ m_ff_vec3_f32_push(struct m_ff_vec3_f32 *ff, } bool -m_ff_vec3_f32_get(struct m_ff_vec3_f32 *ff, - size_t num, - struct xrt_vec3 *out_sample, - uint64_t *out_timestamp_ns) +m_ff_vec3_f32_get(struct m_ff_vec3_f32 *ff, size_t num, struct xrt_vec3 *out_sample, uint64_t *out_timestamp_ns) { if (num >= ff->num) { return false; @@ -127,10 +122,7 @@ m_ff_vec3_f32_get(struct m_ff_vec3_f32 *ff, } size_t -m_ff_vec3_f32_filter(struct m_ff_vec3_f32 *ff, - uint64_t start_ns, - uint64_t stop_ns, - struct xrt_vec3 *out_average) +m_ff_vec3_f32_filter(struct m_ff_vec3_f32 *ff, uint64_t start_ns, uint64_t stop_ns, struct xrt_vec3 *out_average) { size_t num_sampled = 0; size_t count = 0; @@ -274,10 +266,7 @@ m_ff_f64_push(struct m_ff_f64 *ff, const double *sample, uint64_t timestamp_ns) } bool -m_ff_f64_get(struct m_ff_f64 *ff, - size_t num, - double *out_sample, - uint64_t *out_timestamp_ns) +m_ff_f64_get(struct m_ff_f64 *ff, size_t num, double *out_sample, uint64_t *out_timestamp_ns) { if (num >= ff->num) { return false; @@ -291,10 +280,7 @@ m_ff_f64_get(struct m_ff_f64 *ff, } size_t -m_ff_f64_filter(struct m_ff_f64 *ff, - uint64_t start_ns, - uint64_t stop_ns, - double *out_average) +m_ff_f64_filter(struct m_ff_f64 *ff, uint64_t start_ns, uint64_t stop_ns, double *out_average) { size_t num_sampled = 0; size_t count = 0; diff --git a/src/xrt/auxiliary/math/m_filter_fifo.h b/src/xrt/auxiliary/math/m_filter_fifo.h index ffbfb774a..fb20596d6 100644 --- a/src/xrt/auxiliary/math/m_filter_fifo.h +++ b/src/xrt/auxiliary/math/m_filter_fifo.h @@ -43,19 +43,14 @@ m_ff_vec3_f32_get_num(struct m_ff_vec3_f32 *ff); * unspecified behaviour, so samples must be pushed in time order. */ void -m_ff_vec3_f32_push(struct m_ff_vec3_f32 *ff, - const struct xrt_vec3 *sample, - uint64_t timestamp_ns); +m_ff_vec3_f32_push(struct m_ff_vec3_f32 *ff, const struct xrt_vec3 *sample, uint64_t timestamp_ns); /*! * Return the sample at the index, zero means the last sample push, one second * last and so on. */ bool -m_ff_vec3_f32_get(struct m_ff_vec3_f32 *ff, - size_t num, - struct xrt_vec3 *out_sample, - uint64_t *out_timestamp_ns); +m_ff_vec3_f32_get(struct m_ff_vec3_f32 *ff, size_t num, struct xrt_vec3 *out_sample, uint64_t *out_timestamp_ns); /*! * Averages all samples in the fifo between the two timepoints, returns number @@ -70,10 +65,7 @@ m_ff_vec3_f32_get(struct m_ff_vec3_f32 *ff, * @param out_average Average of all samples in the given timeframe. */ size_t -m_ff_vec3_f32_filter(struct m_ff_vec3_f32 *ff, - uint64_t start_ns, - uint64_t stop_ns, - struct xrt_vec3 *out_average); +m_ff_vec3_f32_filter(struct m_ff_vec3_f32 *ff, uint64_t start_ns, uint64_t stop_ns, struct xrt_vec3 *out_average); /*! * Allocates a filter fifo tracking @p num samples and fills it with @p num @@ -106,10 +98,7 @@ m_ff_f64_push(struct m_ff_f64 *ff, const double *sample, uint64_t timestamp_ns); * last and so on. */ bool -m_ff_f64_get(struct m_ff_f64 *ff, - size_t num, - double *out_sample, - uint64_t *out_timestamp_ns); +m_ff_f64_get(struct m_ff_f64 *ff, size_t num, double *out_sample, uint64_t *out_timestamp_ns); /*! * Averages all samples in the fifo between the two timepoints, returns number @@ -124,10 +113,7 @@ m_ff_f64_get(struct m_ff_f64 *ff, * @param out_average Average of all samples in the given timeframe. */ size_t -m_ff_f64_filter(struct m_ff_f64 *ff, - uint64_t start_ns, - uint64_t stop_ns, - double *out_average); +m_ff_f64_filter(struct m_ff_f64 *ff, uint64_t start_ns, uint64_t stop_ns, double *out_average); #ifdef __cplusplus @@ -168,9 +154,7 @@ public: } inline size_t - filter(uint64_t start_ns, - uint64_t stop_ns, - struct xrt_vec3 *out_average) + filter(uint64_t start_ns, uint64_t stop_ns, struct xrt_vec3 *out_average) { return m_ff_vec3_f32_filter(ff, start_ns, stop_ns, out_average); } diff --git a/src/xrt/auxiliary/math/m_imu_3dof.c b/src/xrt/auxiliary/math/m_imu_3dof.c index 2ec3890db..9ceceb61c 100644 --- a/src/xrt/auxiliary/math/m_imu_3dof.c +++ b/src/xrt/auxiliary/math/m_imu_3dof.c @@ -157,16 +157,14 @@ gravity_correction(struct m_imu_3dof *f, correction_radians = fmaxf(min_radians, correction_radians); correction_radians = fminf(max_radians, correction_radians); // Do not exceed the remaining error to correct for - correction_radians = - -fminf(correction_radians, f->grav.error_angle); + correction_radians = -fminf(correction_radians, f->grav.error_angle); // Update how much is left. f->grav.error_angle += correction_radians; // Perform the correction. struct xrt_quat corr_quat, old_orient; - math_quat_from_angle_vector(correction_radians, - &f->grav.error_axis, &corr_quat); + math_quat_from_angle_vector(correction_radians, &f->grav.error_axis, &corr_quat); old_orient = f->rot; math_quat_rotate(&corr_quat, &old_orient, &f->rot); } @@ -215,8 +213,7 @@ m_imu_3dof_update(struct m_imu_3dof *f, float rot_angle = gyro_length * dt; struct xrt_quat delta_orient; - math_quat_from_angle_vector(rot_angle, &rot_axis, - &delta_orient); + math_quat_from_angle_vector(rot_angle, &rot_axis, &delta_orient); math_quat_rotate(&f->rot, &delta_orient, &f->rot); #endif diff --git a/src/xrt/auxiliary/math/m_imu_pre.c b/src/xrt/auxiliary/math/m_imu_pre.c index b53d9ed86..1eb08ce87 100644 --- a/src/xrt/auxiliary/math/m_imu_pre.c +++ b/src/xrt/auxiliary/math/m_imu_pre.c @@ -12,9 +12,7 @@ void -m_imu_pre_filter_init(struct m_imu_pre_filter *imu, - float ticks_to_float_accel, - float ticks_to_float_gyro) +m_imu_pre_filter_init(struct m_imu_pre_filter *imu, float ticks_to_float_accel, float ticks_to_float_gyro) { imu->accel.gain.x = 1.0; imu->accel.gain.y = 1.0; diff --git a/src/xrt/auxiliary/math/m_imu_pre.h b/src/xrt/auxiliary/math/m_imu_pre.h index 4efe7b9f9..70b003bbb 100644 --- a/src/xrt/auxiliary/math/m_imu_pre.h +++ b/src/xrt/auxiliary/math/m_imu_pre.h @@ -60,9 +60,7 @@ struct m_imu_pre_filter * other values are set to identity. */ void -m_imu_pre_filter_init(struct m_imu_pre_filter *imu, - float ticks_to_float_accel, - float ticks_to_float_gyro); +m_imu_pre_filter_init(struct m_imu_pre_filter *imu, float ticks_to_float_accel, float ticks_to_float_gyro); /*! * Sets the transformation to flip X and Y axis. This changes the handedness diff --git a/src/xrt/auxiliary/math/m_optics.c b/src/xrt/auxiliary/math/m_optics.c index f3052675d..74ef5af07 100644 --- a/src/xrt/auxiliary/math/m_optics.c +++ b/src/xrt/auxiliary/math/m_optics.c @@ -53,12 +53,8 @@ DEBUG_GET_ONCE_BOOL_OPTION(views, "MATH_DEBUG_VIEWS", false) * @return true if successful. */ static bool -math_solve_triangle(double w_total, - double w_1, - double theta_total, - double *out_theta_1, - double *out_theta_2, - double *out_d) +math_solve_triangle( + double w_total, double w_1, double theta_total, double *out_theta_1, double *out_theta_2, double *out_d) { /* should have at least one out-variable */ assert(out_theta_1 || out_theta_2 || out_d); @@ -98,10 +94,8 @@ math_solve_triangle(double w_total, if (debug_get_bool_option_views()) { const double rad_to_deg = M_1_PI * 180.0; // comments are to force wrapping - U_LOG_D("w=" METERS_FORMAT " theta=" DEG_FORMAT - " w1=" METERS_FORMAT " theta1=" DEG_FORMAT - " w2=" METERS_FORMAT " theta2=" DEG_FORMAT - " d=" METERS_FORMAT, + U_LOG_D("w=" METERS_FORMAT " theta=" DEG_FORMAT " w1=" METERS_FORMAT " theta1=" DEG_FORMAT + " w2=" METERS_FORMAT " theta2=" DEG_FORMAT " d=" METERS_FORMAT, w_total, theta_total * rad_to_deg, // w_1, (theta_total - theta_2) * rad_to_deg, // w_2, theta_2 * rad_to_deg, // @@ -132,8 +126,7 @@ math_compute_fovs(double w_total, double d = 0; double theta_1 = 0; double theta_2 = 0; - if (!math_solve_triangle(w_total, w_1, horizfov_total, &theta_1, - &theta_2, &d)) { + if (!math_solve_triangle(w_total, w_1, horizfov_total, &theta_1, &theta_2, &d)) { /* failure is contagious */ return false; } @@ -153,8 +146,7 @@ math_compute_fovs(double w_total, phi_2 = atan(h_2 / d); } else { /* Run the same algorithm again for vertical. */ - if (!math_solve_triangle(h_total, h_1, vertfov_total, &phi_1, - &phi_2, NULL)) { + if (!math_solve_triangle(h_total, h_1, vertfov_total, &phi_1, &phi_2, NULL)) { /* failure is contagious */ return false; } diff --git a/src/xrt/auxiliary/math/m_permutation.c b/src/xrt/auxiliary/math/m_permutation.c index 5c34fcbd6..3ef88f176 100644 --- a/src/xrt/auxiliary/math/m_permutation.c +++ b/src/xrt/auxiliary/math/m_permutation.c @@ -77,9 +77,7 @@ step(struct m_permutator *mp) */ bool -m_permutator_step(struct m_permutator *mp, - uint32_t *out_elements, - uint32_t num_elements) +m_permutator_step(struct m_permutator *mp, uint32_t *out_elements, uint32_t num_elements) { if (mp->indices == NULL || mp->n != num_elements) { setup(mp, num_elements); diff --git a/src/xrt/auxiliary/math/m_permutation.h b/src/xrt/auxiliary/math/m_permutation.h index 9cd6de1e9..3aa450b38 100644 --- a/src/xrt/auxiliary/math/m_permutation.h +++ b/src/xrt/auxiliary/math/m_permutation.h @@ -33,9 +33,7 @@ struct m_permutator * been zero initialised. */ bool -m_permutator_step(struct m_permutator *mp, - uint32_t *out_elements, - uint32_t num_elements); +m_permutator_step(struct m_permutator *mp, uint32_t *out_elements, uint32_t num_elements); void m_permutator_reset(struct m_permutator *mp); diff --git a/src/xrt/auxiliary/math/m_predict.c b/src/xrt/auxiliary/math/m_predict.c index aa3748b1a..a85928e9e 100644 --- a/src/xrt/auxiliary/math/m_predict.c +++ b/src/xrt/auxiliary/math/m_predict.c @@ -25,10 +25,8 @@ do_orientation(const struct xrt_space_relation *rel, } struct xrt_vec3 accum = {0}; - bool valid_orientation = - (flags & XRT_SPACE_RELATION_ORIENTATION_VALID_BIT) != 0; - bool valid_angular_velocity = - (flags & XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT) != 0; + bool valid_orientation = (flags & XRT_SPACE_RELATION_ORIENTATION_VALID_BIT) != 0; + bool valid_angular_velocity = (flags & XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT) != 0; if (valid_angular_velocity) { // angular velocity needs to be in body space for prediction @@ -37,9 +35,7 @@ do_orientation(const struct xrt_space_relation *rel, struct xrt_quat orientation_inv; math_quat_invert(&rel->pose.orientation, &orientation_inv); - math_quat_rotate_derivative(&orientation_inv, - &rel->angular_velocity, - &ang_vel_body_space); + math_quat_rotate_derivative(&orientation_inv, &rel->angular_velocity, &ang_vel_body_space); accum.x += ang_vel_body_space.x; accum.y += ang_vel_body_space.y; @@ -56,11 +52,10 @@ do_orientation(const struct xrt_space_relation *rel, #endif if (valid_orientation) { - math_quat_integrate_velocity( - &rel->pose.orientation, // Old orientation - &accum, // Angular velocity - delta_s, // Delta in seconds - &out_rel->pose.orientation); // Result + math_quat_integrate_velocity(&rel->pose.orientation, // Old orientation + &accum, // Angular velocity + delta_s, // Delta in seconds + &out_rel->pose.orientation); // Result } // We use everything we integrated in as the new angular_velocity. @@ -68,8 +63,7 @@ do_orientation(const struct xrt_space_relation *rel, // angular velocity is returned in base space. // use the predicted orientation for this calculation. struct xrt_vec3 predicted_ang_vel_base_space; - math_quat_rotate_derivative(&out_rel->pose.orientation, &accum, - &predicted_ang_vel_base_space); + math_quat_rotate_derivative(&out_rel->pose.orientation, &accum, &predicted_ang_vel_base_space); out_rel->angular_velocity = predicted_ang_vel_base_space; } @@ -88,10 +82,8 @@ do_position(const struct xrt_space_relation *rel, } struct xrt_vec3 accum = {0}; - bool valid_position = - (flags & XRT_SPACE_RELATION_POSITION_VALID_BIT) != 0; - bool valid_linear_velocity = - (flags & XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT) != 0; + bool valid_position = (flags & XRT_SPACE_RELATION_POSITION_VALID_BIT) != 0; + bool valid_linear_velocity = (flags & XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT) != 0; if (valid_linear_velocity) { accum.x += rel->linear_velocity.x; @@ -100,8 +92,7 @@ do_position(const struct xrt_space_relation *rel, } if (valid_position) { - out_rel->pose.position = m_vec3_add( - rel->pose.position, m_vec3_mul_scalar(accum, delta_s)); + out_rel->pose.position = m_vec3_add(rel->pose.position, m_vec3_mul_scalar(accum, delta_s)); } // We use the new linear velocity with the acceleration integrated. @@ -111,9 +102,7 @@ do_position(const struct xrt_space_relation *rel, } void -m_predict_relation(const struct xrt_space_relation *rel, - double delta_s, - struct xrt_space_relation *out_rel) +m_predict_relation(const struct xrt_space_relation *rel, double delta_s, struct xrt_space_relation *out_rel) { enum xrt_space_relation_flags flags = rel->relation_flags; diff --git a/src/xrt/auxiliary/math/m_predict.h b/src/xrt/auxiliary/math/m_predict.h index 2f8e0bfa6..04891e256 100644 --- a/src/xrt/auxiliary/math/m_predict.h +++ b/src/xrt/auxiliary/math/m_predict.h @@ -22,6 +22,4 @@ * @aux_math */ void -m_predict_relation(const struct xrt_space_relation *rel, - double delta_s, - struct xrt_space_relation *out_rel); +m_predict_relation(const struct xrt_space_relation *rel, double delta_s, struct xrt_space_relation *out_rel); diff --git a/src/xrt/auxiliary/math/m_quatexpmap.cpp b/src/xrt/auxiliary/math/m_quatexpmap.cpp index d52850d50..f5d0dd99e 100644 --- a/src/xrt/auxiliary/math/m_quatexpmap.cpp +++ b/src/xrt/auxiliary/math/m_quatexpmap.cpp @@ -100,8 +100,7 @@ cscTaylorExpansion(Scalar theta) // 7 theta^4 / 360 (Scalar(7) * theta * theta * theta * theta) / Scalar(360) + // 31 theta^6/15120 - (Scalar(31) * theta * theta * theta * theta * theta * theta) / - Scalar(15120); + (Scalar(31) * theta * theta * theta * theta * theta * theta) / Scalar(15120); } /// fully-templated free function for quaternion log map. @@ -125,8 +124,7 @@ quat_ln(Eigen::Quaternion const &quat) // When the angle approaches zero, we compute the coefficient // differently, since it gets a bit like sinc in that we want it // continuous but 0 is undefined. - Scalar phiOverSin = vecnorm < 1e-4 ? cscTaylorExpansion(phi) - : (phi / std::sin(phi)); + Scalar phiOverSin = vecnorm < 1e-4 ? cscTaylorExpansion(phi) : (phi / std::sin(phi)); return quat.vec() * phiOverSin; } @@ -145,8 +143,7 @@ math_quat_integrate_velocity(const struct xrt_quat *quat, Eigen::Quaternionf q = map_quat(*quat); - Eigen::Quaternionf incremental_rotation = - quat_exp(map_vec3(*ang_vel) * dt * 0.5f).normalized(); + Eigen::Quaternionf incremental_rotation = quat_exp(map_vec3(*ang_vel) * dt * 0.5f).normalized(); map_quat(*result) = q * incremental_rotation; } @@ -162,7 +159,6 @@ math_quat_finite_difference(const struct xrt_quat *quat0, assert(dt != 0); - Eigen::Quaternionf inc_quat = - map_quat(*quat1) * map_quat(*quat0).conjugate(); + Eigen::Quaternionf inc_quat = map_quat(*quat1) * map_quat(*quat0).conjugate(); map_vec3(*out_ang_vel) = 2.f * quat_ln(inc_quat); } diff --git a/src/xrt/auxiliary/math/m_space.cpp b/src/xrt/auxiliary/math/m_space.cpp index 2503c51f9..73ab3bab1 100644 --- a/src/xrt/auxiliary/math/m_space.cpp +++ b/src/xrt/auxiliary/math/m_space.cpp @@ -18,18 +18,15 @@ #include extern "C" void -m_space_relation_invert(struct xrt_space_relation *relation, - struct xrt_space_relation *out_relation) +m_space_relation_invert(struct xrt_space_relation *relation, struct xrt_space_relation *out_relation) { assert(relation != NULL); assert(out_relation != NULL); out_relation->relation_flags = relation->relation_flags; math_pose_invert(&relation->pose, &out_relation->pose); - out_relation->linear_velocity = - m_vec3_mul_scalar(relation->linear_velocity, -1); - out_relation->angular_velocity = - m_vec3_mul_scalar(relation->angular_velocity, -1); + out_relation->linear_velocity = m_vec3_mul_scalar(relation->linear_velocity, -1); + out_relation->angular_velocity = m_vec3_mul_scalar(relation->angular_velocity, -1); } /* @@ -44,24 +41,20 @@ dump_relation(const struct xrt_space_relation *r) fprintf(stderr, "%04x", r->relation_flags); if (r->relation_flags & XRT_SPACE_RELATION_POSITION_VALID_BIT) { - fprintf(stderr, " P{%f %f %f}", r->pose.position.x, - r->pose.position.y, r->pose.position.z); + fprintf(stderr, " P{%f %f %f}", r->pose.position.x, r->pose.position.y, r->pose.position.z); } if (r->relation_flags & XRT_SPACE_RELATION_ORIENTATION_VALID_BIT) { - fprintf(stderr, " O{%f %f %f %f}", r->pose.orientation.x, - r->pose.orientation.y, r->pose.orientation.z, + fprintf(stderr, " O{%f %f %f %f}", r->pose.orientation.x, r->pose.orientation.y, r->pose.orientation.z, r->pose.orientation.w); } if (r->relation_flags & XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT) { - fprintf(stderr, " LV{%f %f %f}", r->linear_velocity.x, - r->linear_velocity.y, r->linear_velocity.z); + fprintf(stderr, " LV{%f %f %f}", r->linear_velocity.x, r->linear_velocity.y, r->linear_velocity.z); } if (r->relation_flags & XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT) { - fprintf(stderr, " AV{%f %f %f}", r->angular_velocity.x, - r->angular_velocity.y, r->angular_velocity.z); + fprintf(stderr, " AV{%f %f %f}", r->angular_velocity.x, r->angular_velocity.y, r->angular_velocity.z); } fprintf(stderr, "\n"); @@ -88,10 +81,8 @@ dump_graph(const struct xrt_space_graph *xsg) static bool has_step_with_no_pose(const struct xrt_space_graph *xsg) { - const enum xrt_space_relation_flags pose_flags = - (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT); + const enum xrt_space_relation_flags pose_flags = (enum xrt_space_relation_flags)( + XRT_SPACE_RELATION_POSITION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_VALID_BIT); for (uint32_t i = 0; i < xsg->num_steps; i++) { const struct xrt_space_relation *r = &xsg->steps[i]; @@ -130,9 +121,7 @@ get_flags(const struct xrt_space_relation *r) } static void -make_valid_pose(flags flags, - const struct xrt_pose *in_pose, - struct xrt_pose *out_pose) +make_valid_pose(flags flags, const struct xrt_pose *in_pose, struct xrt_pose *out_pose) { if (flags.has_orientation) { out_pose->orientation = in_pose->orientation; @@ -193,10 +182,9 @@ apply_relation(const struct xrt_space_relation *a, nf.has_angular_velocity = true; struct xrt_vec3 tmp = {}; - math_quat_rotate_derivative( - &b->pose.orientation, // Base rotation - &a->angular_velocity, // In base space - &tmp); // Output + math_quat_rotate_derivative(&b->pose.orientation, // Base rotation + &a->angular_velocity, // In base space + &tmp); // Output angular_velocity += tmp; } @@ -293,8 +281,7 @@ apply_relation(const struct xrt_space_relation *a, */ void -m_space_graph_resolve(const struct xrt_space_graph *xsg, - struct xrt_space_relation *out_relation) +m_space_graph_resolve(const struct xrt_space_graph *xsg, struct xrt_space_relation *out_relation) { if (xsg->num_steps == 0 || has_step_with_no_pose(xsg)) { U_ZERO(out_relation); diff --git a/src/xrt/auxiliary/math/m_space.h b/src/xrt/auxiliary/math/m_space.h index b484aa654..f88f0f2ed 100644 --- a/src/xrt/auxiliary/math/m_space.h +++ b/src/xrt/auxiliary/math/m_space.h @@ -58,12 +58,10 @@ m_pose_is_identity(struct xrt_pose *pose) */ static inline void -m_space_relation_from_pose(const struct xrt_pose *pose, - struct xrt_space_relation *out_relation) +m_space_relation_from_pose(const struct xrt_pose *pose, struct xrt_space_relation *out_relation) { - enum xrt_space_relation_flags flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_VALID_BIT); + enum xrt_space_relation_flags flags = (enum xrt_space_relation_flags)(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_POSITION_VALID_BIT); struct xrt_space_relation relation = { flags, *pose, @@ -86,8 +84,7 @@ m_space_relation_ident(struct xrt_space_relation *out_relation) } void -m_space_relation_invert(struct xrt_space_relation *relation, - struct xrt_space_relation *out_relation); +m_space_relation_invert(struct xrt_space_relation *relation, struct xrt_space_relation *out_relation); /* * @@ -112,8 +109,7 @@ m_space_graph_reserve(struct xrt_space_graph *xsg) * Flattens a space graph into a single relation. */ static inline void -m_space_graph_add_relation(struct xrt_space_graph *xsg, - const struct xrt_space_relation *relation) +m_space_graph_add_relation(struct xrt_space_graph *xsg, const struct xrt_space_relation *relation) { if (xsg->num_steps >= XRT_SPACE_GRAPHS_MAX) { return; @@ -123,8 +119,7 @@ m_space_graph_add_relation(struct xrt_space_graph *xsg, } static inline void -m_space_graph_add_inverted_relation(struct xrt_space_graph *xsg, - const struct xrt_space_relation *relation) +m_space_graph_add_inverted_relation(struct xrt_space_graph *xsg, const struct xrt_space_relation *relation) { struct xrt_space_relation r = *relation; @@ -142,8 +137,7 @@ m_space_graph_add_pose(struct xrt_space_graph *xsg, const struct xrt_pose *pose) } static inline void -m_space_graph_add_pose_if_not_identity(struct xrt_space_graph *xsg, - const struct xrt_pose *pose) +m_space_graph_add_pose_if_not_identity(struct xrt_space_graph *xsg, const struct xrt_pose *pose) { struct xrt_pose p = *pose; @@ -155,8 +149,7 @@ m_space_graph_add_pose_if_not_identity(struct xrt_space_graph *xsg, } static inline void -m_space_graph_add_inverted_pose_if_not_identity(struct xrt_space_graph *xsg, - const struct xrt_pose *pose) +m_space_graph_add_inverted_pose_if_not_identity(struct xrt_space_graph *xsg, const struct xrt_pose *pose) { struct xrt_pose p = *pose; @@ -173,8 +166,7 @@ m_space_graph_add_inverted_pose_if_not_identity(struct xrt_space_graph *xsg, * Flattens a space graph into a single relation. */ void -m_space_graph_resolve(const struct xrt_space_graph *xsg, - struct xrt_space_relation *out_relation); +m_space_graph_resolve(const struct xrt_space_graph *xsg, struct xrt_space_relation *out_relation); /*! * @} diff --git a/src/xrt/auxiliary/math/m_vec2.h b/src/xrt/auxiliary/math/m_vec2.h index ddecaf4ce..1d90922f1 100644 --- a/src/xrt/auxiliary/math/m_vec2.h +++ b/src/xrt/auxiliary/math/m_vec2.h @@ -99,8 +99,7 @@ operator-(const struct xrt_vec2 &a, const struct xrt_vec2 &b) return m_vec2_sub(a, b); } -static inline struct xrt_vec2 operator*(const struct xrt_vec2 &a, - const struct xrt_vec2 &b) +static inline struct xrt_vec2 operator*(const struct xrt_vec2 &a, const struct xrt_vec2 &b) { return m_vec2_mul(a, b); } diff --git a/src/xrt/auxiliary/math/m_vec3.h b/src/xrt/auxiliary/math/m_vec3.h index bf83b2d19..e3d5f8cd6 100644 --- a/src/xrt/auxiliary/math/m_vec3.h +++ b/src/xrt/auxiliary/math/m_vec3.h @@ -129,8 +129,7 @@ operator-(const struct xrt_vec3 &a, const struct xrt_vec3 &b) return m_vec3_sub(a, b); } -static inline struct xrt_vec3 operator*(const struct xrt_vec3 &a, - const struct xrt_vec3 &b) +static inline struct xrt_vec3 operator*(const struct xrt_vec3 &a, const struct xrt_vec3 &b) { return m_vec3_mul(a, b); } diff --git a/src/xrt/auxiliary/ogl/ogl_helpers.c b/src/xrt/auxiliary/ogl/ogl_helpers.c index 682ed98cf..7529a63e6 100644 --- a/src/xrt/auxiliary/ogl/ogl_helpers.c +++ b/src/xrt/auxiliary/ogl/ogl_helpers.c @@ -11,10 +11,9 @@ #include "ogl_api.h" void -ogl_texture_target_for_swapchain_info( - const struct xrt_swapchain_create_info *info, - uint32_t *out_tex_target, - uint32_t *out_tex_param_name) +ogl_texture_target_for_swapchain_info(const struct xrt_swapchain_create_info *info, + uint32_t *out_tex_target, + uint32_t *out_tex_param_name) { // see reference: // https://android.googlesource.com/platform/cts/+/master/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp#1261 diff --git a/src/xrt/auxiliary/ogl/ogl_helpers.h b/src/xrt/auxiliary/ogl/ogl_helpers.h index 50d1d3603..771c92b6a 100644 --- a/src/xrt/auxiliary/ogl/ogl_helpers.h +++ b/src/xrt/auxiliary/ogl/ogl_helpers.h @@ -20,10 +20,9 @@ extern "C" { * save/restore for creation/use of an OpenGL texture from the given info. */ void -ogl_texture_target_for_swapchain_info( - const struct xrt_swapchain_create_info *info, - uint32_t *out_tex_target, - uint32_t *out_tex_param_name); +ogl_texture_target_for_swapchain_info(const struct xrt_swapchain_create_info *info, + uint32_t *out_tex_target, + uint32_t *out_tex_param_name); #ifdef __cplusplus } diff --git a/src/xrt/auxiliary/os/os_ble.h b/src/xrt/auxiliary/os/os_ble.h index 5ce08e1c8..20b8c160f 100644 --- a/src/xrt/auxiliary/os/os_ble.h +++ b/src/xrt/auxiliary/os/os_ble.h @@ -27,10 +27,7 @@ extern "C" { */ struct os_ble_device { - int (*read)(struct os_ble_device *ble_dev, - uint8_t *data, - size_t size, - int milliseconds); + int (*read)(struct os_ble_device *ble_dev, uint8_t *data, size_t size, int milliseconds); void (*destroy)(struct os_ble_device *ble_dev); }; @@ -44,10 +41,7 @@ struct os_ble_device * @ingroup aux_os */ XRT_MAYBE_UNUSED static inline int -os_ble_read(struct os_ble_device *ble_dev, - uint8_t *data, - size_t size, - int milliseconds) +os_ble_read(struct os_ble_device *ble_dev, uint8_t *data, size_t size, int milliseconds) { return ble_dev->read(ble_dev, data, size, milliseconds); } @@ -79,9 +73,7 @@ os_ble_destroy(struct os_ble_device **ble_dev_ptr) * @ingroup aux_os */ int -os_ble_notify_open(const char *dev_uuid, - const char *char_uuid, - struct os_ble_device **out_ble); +os_ble_notify_open(const char *dev_uuid, const char *char_uuid, struct os_ble_device **out_ble); /*! * Returns write startpoints from the given device uuid and char uuid. @@ -92,9 +84,7 @@ os_ble_notify_open(const char *dev_uuid, * @ingroup aux_os */ int -os_ble_broadcast_write_value(const char *dev_uuid, - const char *char_uuid, - uint8_t value); +os_ble_broadcast_write_value(const char *dev_uuid, const char *char_uuid, uint8_t value); #endif diff --git a/src/xrt/auxiliary/os/os_ble_dbus.c b/src/xrt/auxiliary/os/os_ble_dbus.c index 76d9df417..6ff07ca91 100644 --- a/src/xrt/auxiliary/os/os_ble_dbus.c +++ b/src/xrt/auxiliary/os/os_ble_dbus.c @@ -76,8 +76,7 @@ add_single_byte_array(DBusMessage *msg, uint8_t value) // attach it to our dbus message dbus_message_iter_init_append(msg, &iter); - dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, - container_signature, &array); + dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, container_signature, &array); dbus_message_iter_append_basic(&array, DBUS_TYPE_BYTE, &value); dbus_message_iter_close_container(&iter, &array); } @@ -91,8 +90,7 @@ add_empty_dict_sv(DBusMessage *msg) // attach it to our dbus message dbus_message_iter_init_append(msg, &iter); - dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, - container_signature, &options); + dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, container_signature, &options); dbus_message_iter_close_container(&iter, &options); } @@ -169,8 +167,7 @@ dump_one_element(DBusMessageIter *element, int level) case DBUS_TYPE_BOOLEAN: { int val; dbus_message_iter_get_basic(element, &val); - U_LOG_D("%*sBOOLEAN: %s", level, "", - val == 0 ? "false" : "true"); + U_LOG_D("%*sBOOLEAN: %s", level, "", val == 0 ? "false" : "true"); return 0; } case DBUS_TYPE_BYTE: { @@ -289,9 +286,7 @@ starts_with_and_has_slash(const char *str, const char *beginning) } static int -dict_get_string_and_varient_child(DBusMessageIter *dict, - const char **out_str, - DBusMessageIter *out_child) +dict_get_string_and_varient_child(DBusMessageIter *dict, const char **out_str, DBusMessageIter *out_child) { DBusMessageIter child; int type = dbus_message_iter_get_arg_type(dict); @@ -325,9 +320,7 @@ dict_get_string_and_varient_child(DBusMessageIter *dict, } static int -dict_get_string_and_array_elm(const DBusMessageIter *in_dict, - const char **out_str, - DBusMessageIter *out_array_elm) +dict_get_string_and_array_elm(const DBusMessageIter *in_dict, const char **out_str, DBusMessageIter *out_array_elm) { DBusMessageIter dict = *in_dict; DBusMessageIter child; @@ -361,9 +354,8 @@ dict_get_string_and_array_elm(const DBusMessageIter *in_dict, return 0; } -#define for_each(i, first) \ - for (DBusMessageIter i = first; \ - dbus_message_iter_get_arg_type(&i) != DBUS_TYPE_INVALID; \ +#define for_each(i, first) \ + for (DBusMessageIter i = first; dbus_message_iter_get_arg_type(&i) != DBUS_TYPE_INVALID; \ dbus_message_iter_next(&i)) /*! @@ -371,9 +363,7 @@ dict_get_string_and_array_elm(const DBusMessageIter *in_dict, * outputs the first element of the array on success. */ static int -array_get_first_elem_of_type(const DBusMessageIter *in_parent, - int of_type, - DBusMessageIter *out_elm) +array_get_first_elem_of_type(const DBusMessageIter *in_parent, int of_type, DBusMessageIter *out_elm) { DBusMessageIter parent = *in_parent; int type = dbus_message_iter_get_arg_type(&parent); @@ -387,8 +377,7 @@ array_get_first_elem_of_type(const DBusMessageIter *in_parent, type = dbus_message_iter_get_arg_type(&elm); if (type != of_type) { - U_LOG_E("Expected elem type of '%c' got '%c'!\n", of_type, - type); + U_LOG_E("Expected elem type of '%c' got '%c'!\n", of_type, type); return -1; } @@ -404,9 +393,7 @@ array_get_first_elem_of_type(const DBusMessageIter *in_parent, * the value of the dict pair. */ static int -array_find_variant_value(const DBusMessageIter *first_elm, - const char *key, - DBusMessageIter *out_value) +array_find_variant_value(const DBusMessageIter *first_elm, const char *key, DBusMessageIter *out_value) { const char *str; @@ -472,11 +459,10 @@ dbus_has_name(DBusConnection *conn, const char *name) DBusMessage *msg; DBusError err; - msg = dbus_message_new_method_call( - "org.freedesktop.DBus", // target for the method call - "/org/freedesktop/DBus", // object to call on - "org.freedesktop.DBus", // interface to call on - "ListNames"); // method name + msg = dbus_message_new_method_call("org.freedesktop.DBus", // target for the method call + "/org/freedesktop/DBus", // object to call on + "org.freedesktop.DBus", // interface to call on + "ListNames"); // method name if (send_message(conn, &err, &msg) != 0) { return -1; } @@ -498,8 +484,7 @@ dbus_has_name(DBusConnection *conn, const char *name) } DBusMessageIter first_elm; - int ret = - array_get_first_elem_of_type(&args, DBUS_TYPE_STRING, &first_elm); + int ret = array_get_first_elem_of_type(&args, DBUS_TYPE_STRING, &first_elm); if (ret < 0) { // free reply dbus_message_unref(msg); @@ -534,9 +519,7 @@ dbus_has_name(DBusConnection *conn, const char *name) * and one of it's `UUIDs` matches the given @p uuid. */ static int -device_has_uuid(const DBusMessageIter *dict, - const char *uuid, - const char **out_path_str) +device_has_uuid(const DBusMessageIter *dict, const char *uuid, const char **out_path_str) { DBusMessageIter iface_elm, first_elm; const char *iface_str; @@ -631,9 +614,7 @@ gatt_iface_get_uuid(const DBusMessageIter *iface_elm, const char **out_str) * uuid and has the notify flag set. */ static int -gatt_char_has_uuid_and_notify(const DBusMessageIter *dict, - const char *uuid, - const char **out_path_str) +gatt_char_has_uuid_and_notify(const DBusMessageIter *dict, const char *uuid, const char **out_path_str) { DBusMessageIter first_elm, iface_elm; const char *iface_str; @@ -729,11 +710,10 @@ ble_get_managed_objects(struct ble_conn_helper *bch, DBusMessage **out_msg) DBusMessage *msg; int type; - msg = dbus_message_new_method_call( - "org.bluez", // target for the method call - "/", // object to call on - "org.freedesktop.DBus.ObjectManager", // interface to call on - "GetManagedObjects"); // method name + msg = dbus_message_new_method_call("org.bluez", // target for the method call + "/", // object to call on + "org.freedesktop.DBus.ObjectManager", // interface to call on + "GetManagedObjects"); // method name if (msg == NULL) { E(bch, "Could not create new message!"); return -1; @@ -777,11 +757,10 @@ ble_connect(struct ble_conn_helper *bch, const char *dbus_address) I(bch, "Connecting '%s'", dbus_address); - msg = dbus_message_new_method_call( - "org.bluez", // target for the method call - dbus_address, // object to call on - "org.bluez.Device1", // interface to call on - "Connect"); // method name + msg = dbus_message_new_method_call("org.bluez", // target for the method call + dbus_address, // object to call on + "org.bluez.Device1", // interface to call on + "Connect"); // method name if (msg == NULL) { E(bch, "Message NULL after construction\n"); return -1; @@ -813,8 +792,7 @@ ble_connect(struct ble_conn_helper *bch, const char *dbus_address) } static int -ble_connect_all_devices_with_service_uuid(struct ble_conn_helper *bch, - const char *service_uuid) +ble_connect_all_devices_with_service_uuid(struct ble_conn_helper *bch, const char *service_uuid) { DBusMessageIter args, first_elm; DBusMessage *msg = NULL; @@ -825,8 +803,7 @@ ble_connect_all_devices_with_service_uuid(struct ble_conn_helper *bch, } dbus_message_iter_init(msg, &args); - ret = array_get_first_elem_of_type(&args, DBUS_TYPE_DICT_ENTRY, - &first_elm); + ret = array_get_first_elem_of_type(&args, DBUS_TYPE_DICT_ENTRY, &first_elm); if (ret < 0) { // free reply dbus_message_unref(msg); @@ -851,20 +828,17 @@ ble_connect_all_devices_with_service_uuid(struct ble_conn_helper *bch, } static int -ble_write_value(struct ble_conn_helper *bch, - const char *dbus_address, - uint8_t value) +ble_write_value(struct ble_conn_helper *bch, const char *dbus_address, uint8_t value) { DBusMessage *msg = NULL; DBusMessageIter args; char *response = NULL; int ret, type; - msg = dbus_message_new_method_call( - "org.bluez", // target for the method call - dbus_address, // object to call on - "org.bluez.GattCharacteristic1", // interface to call on - "WriteValue"); // method name + msg = dbus_message_new_method_call("org.bluez", // target for the method call + dbus_address, // object to call on + "org.bluez.GattCharacteristic1", // interface to call on + "WriteValue"); // method name if (msg == NULL) { E(bch, "Message NULL after construction\n"); return -1; @@ -900,11 +874,8 @@ ble_write_value(struct ble_conn_helper *bch, } static ssize_t -get_path_to_notify_char(struct ble_conn_helper *bch, - const char *dev_uuid, - const char *char_uuid, - char *output, - size_t output_len) +get_path_to_notify_char( + struct ble_conn_helper *bch, const char *dev_uuid, const char *char_uuid, char *output, size_t output_len) { DBusMessageIter args, first_elm; DBusMessage *msg; @@ -915,8 +886,7 @@ get_path_to_notify_char(struct ble_conn_helper *bch, } dbus_message_iter_init(msg, &args); - ret = array_get_first_elem_of_type(&args, DBUS_TYPE_DICT_ENTRY, - &first_elm); + ret = array_get_first_elem_of_type(&args, DBUS_TYPE_DICT_ENTRY, &first_elm); if (ret < 0) { // free reply dbus_message_unref(msg); @@ -934,18 +904,15 @@ get_path_to_notify_char(struct ble_conn_helper *bch, for_each(c, first_elm) { - ret = gatt_char_has_uuid_and_notify(&c, char_uuid, - &char_path_str); + ret = gatt_char_has_uuid_and_notify(&c, char_uuid, &char_path_str); if (ret <= 0) { continue; } - if (!starts_with_and_has_slash(char_path_str, - dev_path_str)) { + if (!starts_with_and_has_slash(char_path_str, dev_path_str)) { continue; } - ssize_t written = - snprintf(output, output_len, "%s", char_path_str); + ssize_t written = snprintf(output, output_len, "%s", char_path_str); // free reply dbus_message_unref(msg); @@ -961,9 +928,7 @@ get_path_to_notify_char(struct ble_conn_helper *bch, } static int -init_ble_notify(const char *dev_uuid, - const char *char_uuid, - struct ble_notify *bledev) +init_ble_notify(const char *dev_uuid, const char *char_uuid, struct ble_notify *bledev) { DBusMessage *msg; int ret; @@ -975,8 +940,7 @@ init_ble_notify(const char *dev_uuid, char dbus_address[256]; // should be long enough XRT_MAYBE_UNUSED ssize_t written = - get_path_to_notify_char(&bledev->bch, dev_uuid, char_uuid, - dbus_address, sizeof(dbus_address)); + get_path_to_notify_char(&bledev->bch, dev_uuid, char_uuid, dbus_address, sizeof(dbus_address)); if (written == 0) { return -1; } @@ -984,11 +948,10 @@ init_ble_notify(const char *dev_uuid, return -1; } - msg = dbus_message_new_method_call( - "org.bluez", // target for the method call - dbus_address, // object to call on - "org.bluez.GattCharacteristic1", // interface to call on - "AcquireNotify"); // method name + msg = dbus_message_new_method_call("org.bluez", // target for the method call + dbus_address, // object to call on + "org.bluez.GattCharacteristic1", // interface to call on + "AcquireNotify"); // method name if (msg == NULL) { E(&bledev->bch, "Message Null after construction\n"); return -1; @@ -1012,8 +975,7 @@ init_ble_notify(const char *dev_uuid, } if (type == DBUS_TYPE_STRING) { dbus_message_iter_get_basic(&args, &response); - E(&bledev->bch, "DBus call returned message: %s\n", - response); + E(&bledev->bch, "DBus call returned message: %s\n", response); } else if (type == DBUS_TYPE_UNIX_FD) { dbus_message_iter_get_basic(&args, &bledev->fd); } @@ -1039,10 +1001,7 @@ init_ble_notify(const char *dev_uuid, */ static int -os_ble_notify_read(struct os_ble_device *bdev, - uint8_t *data, - size_t length, - int milliseconds) +os_ble_notify_read(struct os_ble_device *bdev, uint8_t *data, size_t length, int milliseconds) { struct ble_notify *dev = (struct ble_notify *)bdev; struct pollfd fds; @@ -1097,9 +1056,7 @@ os_ble_notify_destroy(struct os_ble_device *bdev) */ int -os_ble_notify_open(const char *dev_uuid, - const char *char_uuid, - struct os_ble_device **out_ble) +os_ble_notify_open(const char *dev_uuid, const char *char_uuid, struct os_ble_device **out_ble) { struct ble_notify *bledev = U_TYPED_CALLOC(struct ble_notify); bledev->base.read = os_ble_notify_read; @@ -1118,9 +1075,7 @@ os_ble_notify_open(const char *dev_uuid, } int -os_ble_broadcast_write_value(const char *service_uuid, - const char *char_uuid, - uint8_t value) +os_ble_broadcast_write_value(const char *service_uuid, const char *char_uuid, uint8_t value) { struct ble_conn_helper bch = {0}; DBusMessageIter args, first_elm; @@ -1160,8 +1115,7 @@ os_ble_broadcast_write_value(const char *service_uuid, } dbus_message_iter_init(msg, &args); - ret = array_get_first_elem_of_type(&args, DBUS_TYPE_DICT_ENTRY, - &first_elm); + ret = array_get_first_elem_of_type(&args, DBUS_TYPE_DICT_ENTRY, &first_elm); if (ret < 0) { // free reply dbus_message_unref(msg); @@ -1180,13 +1134,11 @@ os_ble_broadcast_write_value(const char *service_uuid, for_each(c, first_elm) { - ret = gatt_char_has_uuid_and_notify(&c, char_uuid, - &char_path_str); + ret = gatt_char_has_uuid_and_notify(&c, char_uuid, &char_path_str); if (ret <= 0) { continue; } - if (!starts_with_and_has_slash(char_path_str, - dev_path_str)) { + if (!starts_with_and_has_slash(char_path_str, dev_path_str)) { continue; } diff --git a/src/xrt/auxiliary/os/os_hid.h b/src/xrt/auxiliary/os/os_hid.h index bd5fbc9c8..89fde6216 100644 --- a/src/xrt/auxiliary/os/os_hid.h +++ b/src/xrt/auxiliary/os/os_hid.h @@ -27,28 +27,15 @@ extern "C" { */ struct os_hid_device { - int (*read)(struct os_hid_device *hid_dev, - uint8_t *data, - size_t size, - int milliseconds); + int (*read)(struct os_hid_device *hid_dev, uint8_t *data, size_t size, int milliseconds); - int (*write)(struct os_hid_device *hid_dev, - const uint8_t *data, - size_t size); + int (*write)(struct os_hid_device *hid_dev, const uint8_t *data, size_t size); - int (*get_feature)(struct os_hid_device *hid_dev, - uint8_t report_num, - uint8_t *data, - size_t size); + int (*get_feature)(struct os_hid_device *hid_dev, uint8_t report_num, uint8_t *data, size_t size); - int (*get_feature_timeout)(struct os_hid_device *hid_dev, - void *data, - size_t size, - uint32_t timeout); + int (*get_feature_timeout)(struct os_hid_device *hid_dev, void *data, size_t size, uint32_t timeout); - int (*set_feature)(struct os_hid_device *hid_dev, - const uint8_t *data, - size_t size); + int (*set_feature)(struct os_hid_device *hid_dev, const uint8_t *data, size_t size); void (*destroy)(struct os_hid_device *hid_dev); }; @@ -62,10 +49,7 @@ struct os_hid_device * @public @memberof os_hid_device */ static inline int -os_hid_read(struct os_hid_device *hid_dev, - uint8_t *data, - size_t size, - int milliseconds) +os_hid_read(struct os_hid_device *hid_dev, uint8_t *data, size_t size, int milliseconds) { return hid_dev->read(hid_dev, data, size, milliseconds); } @@ -90,10 +74,7 @@ os_hid_write(struct os_hid_device *hid_dev, const uint8_t *data, size_t size) * @public @memberof os_hid_device */ static inline int -os_hid_get_feature(struct os_hid_device *hid_dev, - uint8_t report_num, - uint8_t *data, - size_t size) +os_hid_get_feature(struct os_hid_device *hid_dev, uint8_t report_num, uint8_t *data, size_t size) { return hid_dev->get_feature(hid_dev, report_num, data, size); } @@ -104,10 +85,7 @@ os_hid_get_feature(struct os_hid_device *hid_dev, * @public @memberof os_hid_device */ static inline int -os_hid_get_feature_timeout(struct os_hid_device *hid_dev, - void *data, - size_t size, - uint32_t timeout) +os_hid_get_feature_timeout(struct os_hid_device *hid_dev, void *data, size_t size, uint32_t timeout) { return hid_dev->get_feature_timeout(hid_dev, data, size, timeout); } @@ -121,9 +99,7 @@ os_hid_get_feature_timeout(struct os_hid_device *hid_dev, * @public @memberof os_hid_device */ static inline int -os_hid_set_feature(struct os_hid_device *hid_dev, - const uint8_t *data, - size_t size) +os_hid_set_feature(struct os_hid_device *hid_dev, const uint8_t *data, size_t size) { return hid_dev->set_feature(hid_dev, data, size); } diff --git a/src/xrt/auxiliary/os/os_hid_hidraw.c b/src/xrt/auxiliary/os/os_hid_hidraw.c index 5b5b03847..ca95b3d2a 100644 --- a/src/xrt/auxiliary/os/os_hid_hidraw.c +++ b/src/xrt/auxiliary/os/os_hid_hidraw.c @@ -39,10 +39,7 @@ struct hid_hidraw }; static int -os_hidraw_read(struct os_hid_device *ohdev, - uint8_t *data, - size_t length, - int milliseconds) +os_hidraw_read(struct os_hid_device *ohdev, uint8_t *data, size_t length, int milliseconds) { struct hid_hidraw *hrdev = (struct hid_hidraw *)ohdev; struct pollfd fds; @@ -83,10 +80,7 @@ os_hidraw_write(struct os_hid_device *ohdev, const uint8_t *data, size_t length) } static int -os_hidraw_get_feature(struct os_hid_device *ohdev, - uint8_t report_num, - uint8_t *data, - size_t length) +os_hidraw_get_feature(struct os_hid_device *ohdev, uint8_t report_num, uint8_t *data, size_t length) { struct hid_hidraw *hrdev = (struct hid_hidraw *)ohdev; // The ioctl expects the report number in the first byte of the buffer, @@ -96,10 +90,7 @@ os_hidraw_get_feature(struct os_hid_device *ohdev, } static int -os_hidraw_get_feature_timeout(struct os_hid_device *ohdev, - void *data, - size_t length, - uint32_t timeout) +os_hidraw_get_feature_timeout(struct os_hid_device *ohdev, void *data, size_t length, uint32_t timeout) { struct hid_hidraw *hrdev = (struct hid_hidraw *)ohdev; @@ -121,9 +112,7 @@ os_hidraw_get_feature_timeout(struct os_hid_device *ohdev, } static int -os_hidraw_set_feature(struct os_hid_device *ohdev, - const uint8_t *data, - size_t length) +os_hidraw_set_feature(struct os_hid_device *ohdev, const uint8_t *data, size_t length) { struct hid_hidraw *hrdev = (struct hid_hidraw *)ohdev; diff --git a/src/xrt/auxiliary/os/os_threading.h b/src/xrt/auxiliary/os/os_threading.h index 057f8009f..177bbab8d 100644 --- a/src/xrt/auxiliary/os/os_threading.h +++ b/src/xrt/auxiliary/os/os_threading.h @@ -258,9 +258,7 @@ os_thread_helper_init(struct os_thread_helper *oth) * Start the internal thread. */ static inline int -os_thread_helper_start(struct os_thread_helper *oth, - os_run_func func, - void *ptr) +os_thread_helper_start(struct os_thread_helper *oth, os_run_func func, void *ptr) { pthread_mutex_lock(&oth->mutex); diff --git a/src/xrt/auxiliary/tracking/t_calibration.cpp b/src/xrt/auxiliary/tracking/t_calibration.cpp index 996a42858..8bf79116d 100644 --- a/src/xrt/auxiliary/tracking/t_calibration.cpp +++ b/src/xrt/auxiliary/tracking/t_calibration.cpp @@ -180,8 +180,7 @@ refresh_gui_frame(class Calibration &c, int rows, int cols) // Also dereferences the old frame. u_frame_create_one_off(XRT_FORMAT_R8G8B8, cols, rows, &c.gui.frame); - c.gui.rgb = cv::Mat(rows, cols, CV_8UC3, c.gui.frame->data, - c.gui.frame->stride); + c.gui.rgb = cv::Mat(rows, cols, CV_8UC3, c.gui.frame->data, c.gui.frame->stride); } static void @@ -216,13 +215,11 @@ print_txt(cv::Mat &rgb, const char *text, double fontScale) { int fontFace = 0; int thickness = 2; - cv::Size textSize = - cv::getTextSize(text, fontFace, fontScale, thickness, NULL); + cv::Size textSize = cv::getTextSize(text, fontFace, fontScale, thickness, NULL); cv::Point textOrg((rgb.cols - textSize.width) / 2, textSize.height * 2); - cv::putText(rgb, text, textOrg, fontFace, fontScale, - cv::Scalar(192, 192, 192), thickness); + cv::putText(rgb, text, textOrg, fontFace, fontScale, cv::Scalar(192, 192, 192), thickness); } static void @@ -234,8 +231,7 @@ make_gui_str(class Calibration &c) int rows = 100; ensure_buffers_are_allocated(c, rows, cols); - cv::rectangle(rgb, cv::Point2f(0, 0), cv::Point2f(cols, rows), - cv::Scalar(0, 0, 0), -1, 0); + cv::rectangle(rgb, cv::Point2f(0, 0), cv::Point2f(cols, rows), cv::Scalar(0, 0, 0), -1, 0); print_txt(rgb, c.text, 1.0); @@ -252,11 +248,7 @@ draw_rect(cv::Mat &rgb, const cv::Rect &rect, const cv::Scalar &colour) } static void -do_view_coverage(class Calibration &c, - struct ViewState &view, - cv::Mat &gray, - cv::Mat &rgb, - bool found) +do_view_coverage(class Calibration &c, struct ViewState &view, cv::Mat &gray, cv::Mat &rgb, bool found) { // Get the current bounding rect. view.current_bounds = cv::boundingRect(view.current_f32); @@ -291,10 +283,7 @@ do_view_coverage(class Calibration &c, } static bool -do_view_chess(class Calibration &c, - struct ViewState &view, - cv::Mat &gray, - cv::Mat &rgb) +do_view_chess(class Calibration &c, struct ViewState &view, cv::Mat &gray, cv::Mat &rgb) { /* * Fisheye requires measurement and model to be double, other functions @@ -322,8 +311,7 @@ do_view_chess(class Calibration &c, cv::Size size(c.subpixel_size, c.subpixel_size); cv::Size zero(-1, -1); - cv::cornerSubPix(gray, view.current_f32, size, zero, - term_criteria); + cv::cornerSubPix(gray, view.current_f32, size, zero, term_criteria); } // Do the conversion here. @@ -338,10 +326,7 @@ do_view_chess(class Calibration &c, } static bool -do_view_circles(class Calibration &c, - struct ViewState &view, - cv::Mat &gray, - cv::Mat &rgb) +do_view_circles(class Calibration &c, struct ViewState &view, cv::Mat &gray, cv::Mat &rgb) { /* * Fisheye requires measurement and model to be double, other functions @@ -371,10 +356,7 @@ do_view_circles(class Calibration &c, } static bool -do_view(class Calibration &c, - struct ViewState &view, - cv::Mat &gray, - cv::Mat &rgb) +do_view(class Calibration &c, struct ViewState &view, cv::Mat &gray, cv::Mat &rgb) { bool found = false; @@ -553,37 +535,35 @@ process_stereo_samples(class Calibration &c, int cols, int rows) flags |= cv::fisheye::CALIB_RECOMPUTE_EXTRINSIC; // fisheye version - rp_error = cv::fisheye::stereoCalibrate( - c.state.board_models_f64, // objectPoints - c.state.view[0].measured_f64, // inagePoints1 - c.state.view[1].measured_f64, // imagePoints2 - wrapped.view[0].intrinsics_mat, // cameraMatrix1 - wrapped.view[0].distortion_fisheye_mat, // distCoeffs1 - wrapped.view[1].intrinsics_mat, // cameraMatrix2 - wrapped.view[1].distortion_fisheye_mat, // distCoeffs2 - image_size, // imageSize - wrapped.camera_rotation_mat, // R - wrapped.camera_translation_mat, // T - flags); + rp_error = cv::fisheye::stereoCalibrate(c.state.board_models_f64, // objectPoints + c.state.view[0].measured_f64, // inagePoints1 + c.state.view[1].measured_f64, // imagePoints2 + wrapped.view[0].intrinsics_mat, // cameraMatrix1 + wrapped.view[0].distortion_fisheye_mat, // distCoeffs1 + wrapped.view[1].intrinsics_mat, // cameraMatrix2 + wrapped.view[1].distortion_fisheye_mat, // distCoeffs2 + image_size, // imageSize + wrapped.camera_rotation_mat, // R + wrapped.camera_translation_mat, // T + flags); } else { // non-fisheye version int flags = 0; // Insists on 32-bit floats for object points and image points - rp_error = cv::stereoCalibrate( - c.state.board_models_f32, // objectPoints - c.state.view[0].measured_f32, // inagePoints1 - c.state.view[1].measured_f32, // imagePoints2, - wrapped.view[0].intrinsics_mat, // cameraMatrix1 - wrapped.view[0].distortion_mat, // distCoeffs1 - wrapped.view[1].intrinsics_mat, // cameraMatrix2 - wrapped.view[1].distortion_mat, // distCoeffs2 - image_size, // imageSize - wrapped.camera_rotation_mat, // R - wrapped.camera_translation_mat, // T - wrapped.camera_essential_mat, // E - wrapped.camera_fundamental_mat, // F - flags); // flags + rp_error = cv::stereoCalibrate(c.state.board_models_f32, // objectPoints + c.state.view[0].measured_f32, // inagePoints1 + c.state.view[1].measured_f32, // imagePoints2, + wrapped.view[0].intrinsics_mat, // cameraMatrix1 + wrapped.view[0].distortion_mat, // distCoeffs1 + wrapped.view[1].intrinsics_mat, // cameraMatrix2 + wrapped.view[1].distortion_mat, // distCoeffs2 + image_size, // imageSize + wrapped.camera_rotation_mat, // R + wrapped.camera_translation_mat, // T + wrapped.camera_essential_mat, // E + wrapped.camera_fundamental_mat, // F + flags); // flags } // Tell the user what has happened. @@ -633,16 +613,12 @@ process_stereo_samples(class Calibration &c, int cols, int rows) assert(wrapped.isDataStorageValid()); if (c.status != NULL) { - t_stereo_camera_calibration_reference(&c.status->stereo_data, - wrapped.base); + t_stereo_camera_calibration_reference(&c.status->stereo_data, wrapped.base); } } static void -process_view_samples(class Calibration &c, - struct ViewState &view, - int cols, - int rows) +process_view_samples(class Calibration &c, struct ViewState &view, int cols, int rows) { const cv::Size image_size = {cols, rows}; @@ -678,26 +654,24 @@ process_view_samples(class Calibration &c, flags |= cv::fisheye::CALIB_FIX_PRINCIPAL_POINT; #endif - rp_error = cv::fisheye::calibrate( - c.state.board_models_f64, // objectPoints - view.measured_f64, // imagePoints - image_size, // image_size - intrinsics_mat, // K (cameraMatrix 3x3) - distortion_fisheye_mat, // D (distCoeffs 4x1) - cv::noArray(), // rvecs - cv::noArray(), // tvecs - flags, // flags - term_criteria); // criteria + rp_error = cv::fisheye::calibrate(c.state.board_models_f64, // objectPoints + view.measured_f64, // imagePoints + image_size, // image_size + intrinsics_mat, // K (cameraMatrix 3x3) + distortion_fisheye_mat, // D (distCoeffs 4x1) + cv::noArray(), // rvecs + cv::noArray(), // tvecs + flags, // flags + term_criteria); // criteria double balance = 0.1f; - cv::fisheye::estimateNewCameraMatrixForUndistortRectify( - intrinsics_mat, // K - distortion_fisheye_mat, // D - image_size, // image_size - cv::Matx33d::eye(), // R - new_intrinsics_mat, // P - balance); // balance + cv::fisheye::estimateNewCameraMatrixForUndistortRectify(intrinsics_mat, // K + distortion_fisheye_mat, // D + image_size, // image_size + cv::Matx33d::eye(), // R + new_intrinsics_mat, // P + balance); // balance // Probably a busted work-around for busted function. new_intrinsics_mat.at(0, 2) = (cols - 1) / 2.0; @@ -724,14 +698,13 @@ process_view_samples(class Calibration &c, float alpha = 1.0; // Create the new camera matrix. - new_intrinsics_mat = cv::getOptimalNewCameraMatrix( - intrinsics_mat, // cameraMatrix - distortion_mat, // distCoeffs - image_size, // imageSize - alpha, // alpha - cv::Size(), // newImgSize - NULL, // validPixROI - false); // centerPrincipalPoint + new_intrinsics_mat = cv::getOptimalNewCameraMatrix(intrinsics_mat, // cameraMatrix + distortion_mat, // distCoeffs + image_size, // imageSize + alpha, // alpha + cv::Size(), // newImgSize + NULL, // validPixROI + false); // centerPrincipalPoint } P("CALIBRATION DONE RP ERROR %f", rp_error); @@ -749,15 +722,14 @@ process_view_samples(class Calibration &c, // clang-format on if (c.use_fisheye) { - cv::fisheye::initUndistortRectifyMap( - intrinsics_mat, // K - distortion_fisheye_mat, // D - cv::Matx33d::eye(), // R - new_intrinsics_mat, // P - image_size, // size - CV_32FC1, // m1type - view.map1, // map1 - view.map2); // map2 + cv::fisheye::initUndistortRectifyMap(intrinsics_mat, // K + distortion_fisheye_mat, // D + cv::Matx33d::eye(), // R + new_intrinsics_mat, // P + image_size, // size + CV_32FC1, // m1type + view.map1, // map1 + view.map2); // map2 // Set the maps as valid. view.maps_valid = true; @@ -795,11 +767,7 @@ update_public_status(class Calibration &c, bool found) * Logic for capturing a frame. */ static void -do_capture_logic_mono(class Calibration &c, - struct ViewState &view, - bool found, - cv::Mat &gray, - cv::Mat &rgb) +do_capture_logic_mono(class Calibration &c, struct ViewState &view, bool found, cv::Mat &gray, cv::Mat &rgb) { int num = (int)c.state.board_models_f32.size(); int of = c.num_collect_total; @@ -837,12 +805,10 @@ do_capture_logic_mono(class Calibration &c, if (c.save_images) { char buf[512]; - snprintf(buf, 512, "gray_%ix%i_%03i.png", gray.cols, gray.rows, - (int)view.measured_f32.size()); + snprintf(buf, 512, "gray_%ix%i_%03i.png", gray.cols, gray.rows, (int)view.measured_f32.size()); cv::imwrite(buf, gray); - snprintf(buf, 512, "debug_rgb_%03i.jpg", - (int)view.measured_f32.size()); + snprintf(buf, 512, "debug_rgb_%03i.jpg", (int)view.measured_f32.size()); cv::imwrite(buf, rgb); } @@ -921,12 +887,10 @@ do_capture_logic_stereo(class Calibration &c, if (c.save_images) { char buf[512]; - snprintf(buf, 512, "gray_%ix%i_%03i.png", gray.cols, gray.rows, - (int)c.state.board_models_f32.size()); + snprintf(buf, 512, "gray_%ix%i_%03i.png", gray.cols, gray.rows, (int)c.state.board_models_f32.size()); cv::imwrite(buf, gray); - snprintf(buf, 512, "debug_rgb_%03i.jpg", - (int)c.state.board_models_f32.size()); + snprintf(buf, 512, "debug_rgb_%03i.jpg", (int)c.state.board_models_f32.size()); cv::imwrite(buf, rgb); } @@ -985,16 +949,13 @@ make_calibration_frame_sbs(class Calibration &c) // Split left and right eyes, don't make any copies. cv::Mat l_gray(rows, cols, CV_8UC1, gray.data, gray.cols); cv::Mat r_gray(rows, cols, CV_8UC1, gray.data + cols, gray.cols); - cv::Mat l_rgb(rows, cols, CV_8UC3, c.gui.frame->data, - c.gui.frame->stride); - cv::Mat r_rgb(rows, cols, CV_8UC3, c.gui.frame->data + 3 * cols, - c.gui.frame->stride); + cv::Mat l_rgb(rows, cols, CV_8UC3, c.gui.frame->data, c.gui.frame->stride); + cv::Mat r_rgb(rows, cols, CV_8UC3, c.gui.frame->data + 3 * cols, c.gui.frame->stride); bool found_left = do_view(c, c.state.view[0], l_gray, l_rgb); bool found_right = do_view(c, c.state.view[1], r_gray, r_rgb); - do_capture_logic_stereo(c, gray, rgb, found_left, c.state.view[0], - l_gray, l_rgb, found_right, c.state.view[1], + do_capture_logic_stereo(c, gray, rgb, found_left, c.state.view[0], l_gray, l_rgb, found_right, c.state.view[1], r_gray, r_rgb); if (c.state.board_models_f32.size() >= c.num_collect_total) { @@ -1035,8 +996,7 @@ make_remap_view(class Calibration &c, struct xrt_frame *xf) int rows = rgb.rows; cv::Mat l_rgb(rows, cols, CV_8UC3, frame.data, frame.stride); - cv::Mat r_rgb(rows, cols, CV_8UC3, frame.data + 3 * cols, - frame.stride); + cv::Mat r_rgb(rows, cols, CV_8UC3, frame.data + 3 * cols, frame.stride); remap_view(c, c.state.view[0], l_rgb); remap_view(c, c.state.view[1], r_rgb); @@ -1144,8 +1104,7 @@ process_load_image(class Calibration &c, struct xrt_frame *xf) break; } - snprintf(buf, 512, "gray_%ux%u_%03i.png", xf->width, xf->height, - i); + snprintf(buf, 512, "gray_%ux%u_%03i.png", xf->width, xf->height, i); c.gray = cv::imread(buf, cv::IMREAD_GRAYSCALE); if (c.gray.rows == 0 || c.gray.cols == 0) { @@ -1153,8 +1112,7 @@ process_load_image(class Calibration &c, struct xrt_frame *xf) continue; } - if (c.gray.rows != (int)xf->height || - c.gray.cols != (int)xf->width) { + if (c.gray.rows != (int)xf->height || c.gray.cols != (int)xf->width) { U_LOG_E( "Image size does not match frame size! Image: " "(%ix%i) Frame: (%ux%u)", @@ -1222,8 +1180,7 @@ t_calibration_frame(struct xrt_frame_sink *xsink, struct xrt_frame *xf) // Clear our gui frame. if (c.clear_frame) { - cv::rectangle(c.gui.rgb, cv::Point2f(0, 0), - cv::Point2f(c.gui.rgb.cols, c.gui.rgb.rows), + cv::rectangle(c.gui.rgb, cv::Point2f(0, 0), cv::Point2f(c.gui.rgb.cols, c.gui.rgb.rows), cv::Scalar(0, 0, 0), -1, 0); } @@ -1277,8 +1234,7 @@ t_calibration_stereo_create(struct xrt_frame_context *xfctx, params->asymmetric_circles.cols, params->asymmetric_circles.rows, }; - c.board.spacing_meters = - params->asymmetric_circles.diagonal_distance_meters; + c.board.spacing_meters = params->asymmetric_circles.diagonal_distance_meters; break; default: assert(false); } @@ -1340,8 +1296,7 @@ t_calibration_stereo_create(struct xrt_frame_context *xfctx, //! Helper for NormalizedCoordsCache constructors static inline std::vector -generateInputCoordsAndReserveOutputCoords(cv::Size size, - std::vector &outputCoords) +generateInputCoordsAndReserveOutputCoords(cv::Size size, std::vector &outputCoords) { std::vector inputCoords; @@ -1372,70 +1327,59 @@ populateCacheMats(cv::Size size, const auto n = size.width * size.height; // Populate the cache matrices for (int i = 0; i < n; ++i) { - auto input = - cv::Point{int(inputCoords[i][0]), int(inputCoords[i][1])}; + auto input = cv::Point{int(inputCoords[i][0]), int(inputCoords[i][1])}; cacheX(input) = outputCoords[i][0]; cacheY(input) = outputCoords[i][1]; } } -NormalizedCoordsCache::NormalizedCoordsCache( - cv::Size size, // NOLINT // small, pass by value - const cv::Matx33d &intrinsics, - const cv::Matx &distortion) +NormalizedCoordsCache::NormalizedCoordsCache(cv::Size size, // NOLINT // small, pass by value + const cv::Matx33d &intrinsics, + const cv::Matx &distortion) { std::vector outputCoords; - std::vector inputCoords = - generateInputCoordsAndReserveOutputCoords(size, outputCoords); + std::vector inputCoords = generateInputCoordsAndReserveOutputCoords(size, outputCoords); // Undistort/reproject those coordinates in one call, to make use of // cached internal/intermediate computations. cv::undistortPoints(inputCoords, outputCoords, intrinsics, distortion); populateCacheMats(size, inputCoords, outputCoords, cacheX_, cacheY_); } -NormalizedCoordsCache::NormalizedCoordsCache( - cv::Size size, // NOLINT // small, pass by value - const cv::Matx33d &intrinsics, - const cv::Matx &distortion, - const cv::Matx33d &rectification, - const cv::Matx33d &new_camera_matrix) +NormalizedCoordsCache::NormalizedCoordsCache(cv::Size size, // NOLINT // small, pass by value + const cv::Matx33d &intrinsics, + const cv::Matx &distortion, + const cv::Matx33d &rectification, + const cv::Matx33d &new_camera_matrix) { std::vector outputCoords; - std::vector inputCoords = - generateInputCoordsAndReserveOutputCoords(size, outputCoords); + std::vector inputCoords = generateInputCoordsAndReserveOutputCoords(size, outputCoords); // Undistort/reproject those coordinates in one call, to make use of // cached internal/intermediate computations. - cv::undistortPoints(inputCoords, outputCoords, intrinsics, distortion, - rectification, new_camera_matrix); + cv::undistortPoints(inputCoords, outputCoords, intrinsics, distortion, rectification, new_camera_matrix); populateCacheMats(size, inputCoords, outputCoords, cacheX_, cacheY_); } -NormalizedCoordsCache::NormalizedCoordsCache( - cv::Size size, // NOLINT // small, pass by value - const cv::Matx33d &intrinsics, - const cv::Matx &distortion, - const cv::Matx33d &rectification, - const cv::Matx &new_projection_matrix) +NormalizedCoordsCache::NormalizedCoordsCache(cv::Size size, // NOLINT // small, pass by value + const cv::Matx33d &intrinsics, + const cv::Matx &distortion, + const cv::Matx33d &rectification, + const cv::Matx &new_projection_matrix) { std::vector outputCoords; - std::vector inputCoords = - generateInputCoordsAndReserveOutputCoords(size, outputCoords); + std::vector inputCoords = generateInputCoordsAndReserveOutputCoords(size, outputCoords); // Undistort/reproject those coordinates in one call, to make use of // cached internal/intermediate computations. - cv::undistortPoints(inputCoords, outputCoords, intrinsics, distortion, - rectification, new_projection_matrix); + cv::undistortPoints(inputCoords, outputCoords, intrinsics, distortion, rectification, new_projection_matrix); populateCacheMats(size, inputCoords, outputCoords, cacheX_, cacheY_); } -NormalizedCoordsCache::NormalizedCoordsCache( - cv::Size size, // NOLINT // small, pass by value - const cv::Mat &intrinsics, - const cv::Mat &distortion) +NormalizedCoordsCache::NormalizedCoordsCache(cv::Size size, // NOLINT // small, pass by value + const cv::Mat &intrinsics, + const cv::Mat &distortion) { std::vector outputCoords; - std::vector inputCoords = - generateInputCoordsAndReserveOutputCoords(size, outputCoords); + std::vector inputCoords = generateInputCoordsAndReserveOutputCoords(size, outputCoords); // Undistort/reproject those coordinates in one call, to make use of // cached internal/intermediate computations. cv::undistortPoints(inputCoords, outputCoords, intrinsics, distortion); diff --git a/src/xrt/auxiliary/tracking/t_calibration_opencv.hpp b/src/xrt/auxiliary/tracking/t_calibration_opencv.hpp index 42808e8c4..20bf20009 100644 --- a/src/xrt/auxiliary/tracking/t_calibration_opencv.hpp +++ b/src/xrt/auxiliary/tracking/t_calibration_opencv.hpp @@ -39,12 +39,10 @@ struct CameraCalibrationWrapper CameraCalibrationWrapper(t_camera_calibration &calib) : base(calib), image_size_pixels(calib.image_size_pixels), - image_size_pixels_cv(calib.image_size_pixels.w, - calib.image_size_pixels.h), + image_size_pixels_cv(calib.image_size_pixels.w, calib.image_size_pixels.h), intrinsics_mat(3, 3, &calib.intrinsics[0][0]), distortion_mat(XRT_DISTORTION_MAX_DIM, 1, &calib.distortion[0]), - distortion_fisheye_mat(4, 1, &calib.distortion_fisheye[0]), - use_fisheye(calib.use_fisheye) + distortion_fisheye_mat(4, 1, &calib.distortion_fisheye[0]), use_fisheye(calib.use_fisheye) { assert(isDataStorageValid()); } @@ -54,16 +52,13 @@ struct CameraCalibrationWrapper isDataStorageValid() const noexcept { return intrinsics_mat.size() == cv::Size(3, 3) && - (double *)intrinsics_mat.data == - &(base.intrinsics[0][0]) && + (double *)intrinsics_mat.data == &(base.intrinsics[0][0]) && - distortion_mat.size() == - cv::Size(1, XRT_DISTORTION_MAX_DIM) && + distortion_mat.size() == cv::Size(1, XRT_DISTORTION_MAX_DIM) && (double *)distortion_mat.data == &(base.distortion[0]) && distortion_fisheye_mat.size() == cv::Size(1, 4) && - (double *)distortion_fisheye_mat.data == - &(base.distortion_fisheye[0]); + (double *)distortion_fisheye_mat.data == &(base.distortion_fisheye[0]); } }; @@ -93,8 +88,7 @@ struct StereoCameraCalibrationWrapper } StereoCameraCalibrationWrapper(t_stereo_camera_calibration *stereo) - : base(stereo), view{CameraCalibrationWrapper{stereo->view[0]}, - CameraCalibrationWrapper{stereo->view[1]}}, + : base(stereo), view{CameraCalibrationWrapper{stereo->view[0]}, CameraCalibrationWrapper{stereo->view[1]}}, camera_translation_mat(3, 1, &stereo->camera_translation[0]), camera_rotation_mat(3, 3, &stereo->camera_rotation[0][0]), camera_essential_mat(3, 3, &stereo->camera_essential[0][0]), @@ -107,8 +101,7 @@ struct StereoCameraCalibrationWrapper assert(isDataStorageValid()); } - StereoCameraCalibrationWrapper() - : StereoCameraCalibrationWrapper(allocData()) + StereoCameraCalibrationWrapper() : StereoCameraCalibrationWrapper(allocData()) { // The function allocData returns with a ref count of one, @@ -127,23 +120,18 @@ struct StereoCameraCalibrationWrapper isDataStorageValid() const noexcept { return camera_translation_mat.size() == cv::Size(1, 3) && - (double *)camera_translation_mat.data == - &base->camera_translation[0] && + (double *)camera_translation_mat.data == &base->camera_translation[0] && camera_rotation_mat.size() == cv::Size(3, 3) && - (double *)camera_rotation_mat.data == - &base->camera_rotation[0][0] && + (double *)camera_rotation_mat.data == &base->camera_rotation[0][0] && camera_essential_mat.size() == cv::Size(3, 3) && - (double *)camera_essential_mat.data == - &base->camera_essential[0][0] && + (double *)camera_essential_mat.data == &base->camera_essential[0][0] && camera_fundamental_mat.size() == cv::Size(3, 3) && - (double *)camera_fundamental_mat.data == - &base->camera_fundamental[0][0] && + (double *)camera_fundamental_mat.data == &base->camera_fundamental[0][0] && - view[0].isDataStorageValid() && - view[1].isDataStorageValid(); + view[0].isDataStorageValid() && view[1].isDataStorageValid(); } }; @@ -170,10 +158,9 @@ struct RemapPair * here uses the input camera matrix as your output camera matrix. */ RemapPair -calibration_get_undistort_map( - t_camera_calibration &calib, - cv::InputArray rectify_transform_optional = cv::noArray(), - cv::Mat new_camera_matrix_optional = cv::Mat()); +calibration_get_undistort_map(t_camera_calibration &calib, + cv::InputArray rectify_transform_optional = cv::noArray(), + cv::Mat new_camera_matrix_optional = cv::Mat()); /*! * @brief Rectification, rotation, projection data for a single view in a stereo @@ -230,9 +217,7 @@ public: * This overload applies no rectification (`R`) and uses a * normalized/identity new camera matrix (`P`). */ - NormalizedCoordsCache(cv::Size size, - const cv::Matx33d &intrinsics, - const cv::Matx &distortion); + NormalizedCoordsCache(cv::Size size, const cv::Matx33d &intrinsics, const cv::Matx &distortion); /*! * @brief Set up the precomputed cache for a given camera (overload for * rectification and new camera matrix) @@ -263,12 +248,11 @@ public: * @param new_projection_matrix A 3x4 new projection matrix - * corresponds to parameter `P` to cv::undistortPoints(). */ - NormalizedCoordsCache( - cv::Size size, - const cv::Matx33d &intrinsics, - const cv::Matx &distortion, - const cv::Matx33d &rectification, - const cv::Matx &new_projection_matrix); + NormalizedCoordsCache(cv::Size size, + const cv::Matx33d &intrinsics, + const cv::Matx &distortion, + const cv::Matx33d &rectification, + const cv::Matx &new_projection_matrix); /*! * @brief Set up the precomputed cache for a given camera. @@ -280,9 +264,7 @@ public: * This overload applies no rectification (`R`) and uses a * normalized/identity new camera matrix (`P`). */ - NormalizedCoordsCache(cv::Size size, - const cv::Mat &intrinsics, - const cv::Mat &distortion); + NormalizedCoordsCache(cv::Size size, const cv::Mat &intrinsics, const cv::Mat &distortion); /*! * @brief Get normalized, undistorted coordinates from a point in the diff --git a/src/xrt/auxiliary/tracking/t_convert.cpp b/src/xrt/auxiliary/tracking/t_convert.cpp index 81c8132bf..827cbef7f 100644 --- a/src/xrt/auxiliary/tracking/t_convert.cpp +++ b/src/xrt/auxiliary/tracking/t_convert.cpp @@ -63,20 +63,14 @@ t_convert_make_h8s8v8_to_r8g8b8(struct t_convert_table *t) } extern "C" void -t_convert_in_place_y8u8v8_to_r8g8b8(uint32_t width, - uint32_t height, - size_t stride, - void *data_ptr) +t_convert_in_place_y8u8v8_to_r8g8b8(uint32_t width, uint32_t height, size_t stride, void *data_ptr) { cv::Mat data(height, width, CV_8UC3, data_ptr, stride); cv::cvtColor(data, data, cv::COLOR_YUV2RGB); } extern "C" void -t_convert_in_place_y8u8v8_to_h8s8v8(uint32_t width, - uint32_t height, - size_t stride, - void *data_ptr) +t_convert_in_place_y8u8v8_to_h8s8v8(uint32_t width, uint32_t height, size_t stride, void *data_ptr) { cv::Mat data(height, width, CV_8UC3, data_ptr, stride); cv::Mat temp(height, width, CV_32FC3); @@ -85,10 +79,7 @@ t_convert_in_place_y8u8v8_to_h8s8v8(uint32_t width, } extern "C" void -t_convert_in_place_h8s8v8_to_r8g8b8(uint32_t width, - uint32_t height, - size_t stride, - void *data_ptr) +t_convert_in_place_h8s8v8_to_r8g8b8(uint32_t width, uint32_t height, size_t stride, void *data_ptr) { cv::Mat data(height, width, CV_8UC3, data_ptr, stride); cv::cvtColor(data, data, cv::COLOR_YUV2RGB); diff --git a/src/xrt/auxiliary/tracking/t_data_utils.c b/src/xrt/auxiliary/tracking/t_data_utils.c index b93832611..25b2775cf 100644 --- a/src/xrt/auxiliary/tracking/t_data_utils.c +++ b/src/xrt/auxiliary/tracking/t_data_utils.c @@ -16,8 +16,7 @@ void t_stereo_camera_calibration_alloc(struct t_stereo_camera_calibration **out_c) { - struct t_stereo_camera_calibration *c = - U_TYPED_CALLOC(struct t_stereo_camera_calibration); + struct t_stereo_camera_calibration *c = U_TYPED_CALLOC(struct t_stereo_camera_calibration); t_stereo_camera_calibration_reference(out_c, c); } diff --git a/src/xrt/auxiliary/tracking/t_debug_hsv_picker.cpp b/src/xrt/auxiliary/tracking/t_debug_hsv_picker.cpp index 324fb7e3c..7b20c24a7 100644 --- a/src/xrt/auxiliary/tracking/t_debug_hsv_picker.cpp +++ b/src/xrt/auxiliary/tracking/t_debug_hsv_picker.cpp @@ -96,8 +96,8 @@ process_frame_yuv(class DebugHSVPicker &d, struct xrt_frame *xf) } } - cv::inRange(d.debug.hsv, cv::Scalar(low_H, low_S, low_V), - cv::Scalar(high_H, high_S, high_V), d.debug.threshold); + cv::inRange(d.debug.hsv, cv::Scalar(low_H, low_S, low_V), cv::Scalar(high_H, high_S, high_V), + d.debug.threshold); cv::imshow(PICK_WIN, d.debug.threshold); } @@ -128,8 +128,8 @@ process_frame_yuyv(class DebugHSVPicker &d, struct xrt_frame *xf) } } - cv::inRange(d.debug.hsv, cv::Scalar(low_H, low_S, low_V), - cv::Scalar(high_H, high_S, high_V), d.debug.threshold); + cv::inRange(d.debug.hsv, cv::Scalar(low_H, low_S, low_V), cv::Scalar(high_H, high_S, high_V), + d.debug.threshold); cv::imshow(PICK_WIN, d.debug.threshold); } @@ -230,18 +230,12 @@ t_debug_hsv_picker_create(struct xrt_frame_context *xfctx, d.passthrough = passthrough; // Trackbars to set thresholds for HSV values - cv::createTrackbar("Low H", PICK_WIN, &low_H, max_value_H, - on_low_H_thresh_trackbar); - cv::createTrackbar("High H", PICK_WIN, &high_H, max_value_H, - on_high_H_thresh_trackbar); - cv::createTrackbar("Low S", PICK_WIN, &low_S, max_value, - on_low_S_thresh_trackbar); - cv::createTrackbar("High S", PICK_WIN, &high_S, max_value, - on_high_S_thresh_trackbar); - cv::createTrackbar("Low V", PICK_WIN, &low_V, max_value, - on_low_V_thresh_trackbar); - cv::createTrackbar("High V", PICK_WIN, &high_V, max_value, - on_high_V_thresh_trackbar); + cv::createTrackbar("Low H", PICK_WIN, &low_H, max_value_H, on_low_H_thresh_trackbar); + cv::createTrackbar("High H", PICK_WIN, &high_H, max_value_H, on_high_H_thresh_trackbar); + cv::createTrackbar("Low S", PICK_WIN, &low_S, max_value, on_low_S_thresh_trackbar); + cv::createTrackbar("High S", PICK_WIN, &high_S, max_value, on_high_S_thresh_trackbar); + cv::createTrackbar("Low V", PICK_WIN, &low_V, max_value, on_low_V_thresh_trackbar); + cv::createTrackbar("High V", PICK_WIN, &high_V, max_value, on_high_V_thresh_trackbar); cv::startWindowThread(); diff --git a/src/xrt/auxiliary/tracking/t_debug_hsv_viewer.cpp b/src/xrt/auxiliary/tracking/t_debug_hsv_viewer.cpp index 450d89f53..619284575 100644 --- a/src/xrt/auxiliary/tracking/t_debug_hsv_viewer.cpp +++ b/src/xrt/auxiliary/tracking/t_debug_hsv_viewer.cpp @@ -54,12 +54,7 @@ public: */ static void -process_pixel(bool f1, - bool f1_diff, - uint8_t *hsv_cap, - uint8_t *hsv_opt, - uint8_t *hsv_diff, - const uint8_t *rgb) +process_pixel(bool f1, bool f1_diff, uint8_t *hsv_cap, uint8_t *hsv_opt, uint8_t *hsv_diff, const uint8_t *rgb) { if (f1) { hsv_cap[0] = rgb[2]; @@ -113,10 +108,8 @@ process_frame(DebugHSVViewer &d, struct xrt_frame *xf) for (uint32_t yp = 0; yp < SIZE; yp++) { for (int chan = 0; chan < NUM_CHAN; chan++) { auto hsv_cap = bgr.ptr(yp + SIZE * chan); - auto hsv_opt = - bgr.ptr(yp + SIZE * chan) + 256 * 3; - auto hsv_diff = - bgr.ptr(yp + SIZE * chan) + 512 * 3; + auto hsv_opt = bgr.ptr(yp + SIZE * chan) + 256 * 3; + auto hsv_diff = bgr.ptr(yp + SIZE * chan) + 512 * 3; int mask = 1 << chan; for (uint32_t xp = 0; xp < SIZE; xp++) { @@ -126,14 +119,12 @@ process_frame(DebugHSVViewer &d, struct xrt_frame *xf) uint8_t *rgb = d.yuv_to_rgb_table.v[y][u][v]; uint8_t large = d.hsv_large.v[y][u][v]; - uint8_t opt = - t_hsv_filter_sample(&d.hsv_opt, y, u, v); + uint8_t opt = t_hsv_filter_sample(&d.hsv_opt, y, u, v); large = (large & mask) != 0; opt = (opt & mask) != 0; - process_pixel(large, opt, hsv_cap, hsv_opt, - hsv_diff, rgb); + process_pixel(large, opt, hsv_cap, hsv_opt, hsv_diff, rgb); hsv_cap += 3; hsv_opt += 3; diff --git a/src/xrt/auxiliary/tracking/t_file.cpp b/src/xrt/auxiliary/tracking/t_file.cpp index c32ae21b8..9cb9113ef 100644 --- a/src/xrt/auxiliary/tracking/t_file.cpp +++ b/src/xrt/auxiliary/tracking/t_file.cpp @@ -45,47 +45,40 @@ calibration_get_undistort_map(t_camera_calibration &calib, //! @todo Scale Our intrinsics if the frame size we request // calibration for does not match what was saved - cv::Size image_size(calib.image_size_pixels.w, - calib.image_size_pixels.h); + cv::Size image_size(calib.image_size_pixels.w, calib.image_size_pixels.h); if (calib.use_fisheye) { - cv::fisheye::initUndistortRectifyMap( - wrap.intrinsics_mat, // cameraMatrix - wrap.distortion_fisheye_mat, // distCoeffs - rectify_transform_optional, // R - new_camera_matrix_optional, // newCameraMatrix - image_size, // size - CV_32FC1, // m1type - ret.remap_x, // map1 - ret.remap_y); // map2 + cv::fisheye::initUndistortRectifyMap(wrap.intrinsics_mat, // cameraMatrix + wrap.distortion_fisheye_mat, // distCoeffs + rectify_transform_optional, // R + new_camera_matrix_optional, // newCameraMatrix + image_size, // size + CV_32FC1, // m1type + ret.remap_x, // map1 + ret.remap_y); // map2 } else { - cv::initUndistortRectifyMap( - wrap.intrinsics_mat, // cameraMatrix - wrap.distortion_mat, // distCoeffs - rectify_transform_optional, // R - new_camera_matrix_optional, // newCameraMatrix - image_size, // size - CV_32FC1, // m1type - ret.remap_x, // map1 - ret.remap_y); // map2 + cv::initUndistortRectifyMap(wrap.intrinsics_mat, // cameraMatrix + wrap.distortion_mat, // distCoeffs + rectify_transform_optional, // R + new_camera_matrix_optional, // newCameraMatrix + image_size, // size + CV_32FC1, // m1type + ret.remap_x, // map1 + ret.remap_y); // map2 } return ret; } -StereoRectificationMaps::StereoRectificationMaps( - t_stereo_camera_calibration *data) +StereoRectificationMaps::StereoRectificationMaps(t_stereo_camera_calibration *data) { assert(data != NULL); - assert(data->view[0].image_size_pixels.w == - data->view[1].image_size_pixels.w); - assert(data->view[0].image_size_pixels.h == - data->view[1].image_size_pixels.h); + assert(data->view[0].image_size_pixels.w == data->view[1].image_size_pixels.w); + assert(data->view[0].image_size_pixels.h == data->view[1].image_size_pixels.h); assert(data->view[0].use_fisheye == data->view[1].use_fisheye); - cv::Size image_size(data->view[0].image_size_pixels.w, - data->view[0].image_size_pixels.h); + cv::Size image_size(data->view[0].image_size_pixels.w, data->view[0].image_size_pixels.h); StereoCameraCalibrationWrapper wrapped(data); /* @@ -124,24 +117,23 @@ StereoRectificationMaps::StereoRectificationMaps( // The function performs the default scaling. float alpha = -1.0f; - cv::stereoRectify( - wrapped.view[0].intrinsics_mat, // cameraMatrix1 - cv::noArray(), // distCoeffs1 - wrapped.view[1].intrinsics_mat, // cameraMatrix2 - cv::noArray(), // distCoeffs2 - image_size, // imageSize - wrapped.camera_rotation_mat, // R - wrapped.camera_translation_mat, // T - view[0].rotation_mat, // R1 - view[1].rotation_mat, // R2 - view[0].projection_mat, // P1 - view[1].projection_mat, // P2 - disparity_to_depth_mat, // Q - flags, // flags - alpha, // alpha - cv::Size(), // newImageSize - NULL, // validPixROI1 - NULL); // validPixROI2 + cv::stereoRectify(wrapped.view[0].intrinsics_mat, // cameraMatrix1 + cv::noArray(), // distCoeffs1 + wrapped.view[1].intrinsics_mat, // cameraMatrix2 + cv::noArray(), // distCoeffs2 + image_size, // imageSize + wrapped.camera_rotation_mat, // R + wrapped.camera_translation_mat, // T + view[0].rotation_mat, // R1 + view[1].rotation_mat, // R2 + view[0].projection_mat, // P1 + view[1].projection_mat, // P2 + disparity_to_depth_mat, // Q + flags, // flags + alpha, // alpha + cv::Size(), // newImageSize + NULL, // validPixROI1 + NULL); // validPixROI2 #endif } else { // Have the same principal point on both. @@ -149,32 +141,29 @@ StereoRectificationMaps::StereoRectificationMaps( // Get all of the pixels from the camera. float alpha = 1.0f; - cv::stereoRectify( - wrapped.view[0].intrinsics_mat, // cameraMatrix1 - /* cv::noArray(), */ // distCoeffs1 - wrapped.view[0].distortion_mat, // distCoeffs1 - wrapped.view[1].intrinsics_mat, // cameraMatrix2 - /* cv::noArray(), */ // distCoeffs2 - wrapped.view[1].distortion_mat, // distCoeffs2 - image_size, // imageSize - wrapped.camera_rotation_mat, // R - wrapped.camera_translation_mat, // T - view[0].rotation_mat, // R1 - view[1].rotation_mat, // R2 - view[0].projection_mat, // P1 - view[1].projection_mat, // P2 - disparity_to_depth_mat, // Q - flags, // flags - alpha, // alpha - cv::Size(), // newImageSize - NULL, // validPixROI1 - NULL); // validPixROI2 + cv::stereoRectify(wrapped.view[0].intrinsics_mat, // cameraMatrix1 + /* cv::noArray(), */ // distCoeffs1 + wrapped.view[0].distortion_mat, // distCoeffs1 + wrapped.view[1].intrinsics_mat, // cameraMatrix2 + /* cv::noArray(), */ // distCoeffs2 + wrapped.view[1].distortion_mat, // distCoeffs2 + image_size, // imageSize + wrapped.camera_rotation_mat, // R + wrapped.camera_translation_mat, // T + view[0].rotation_mat, // R1 + view[1].rotation_mat, // R2 + view[0].projection_mat, // P1 + view[1].projection_mat, // P2 + disparity_to_depth_mat, // Q + flags, // flags + alpha, // alpha + cv::Size(), // newImageSize + NULL, // validPixROI1 + NULL); // validPixROI2 } - view[0].rectify = calibration_get_undistort_map( - data->view[0], view[0].rotation_mat, view[0].projection_mat); - view[1].rectify = calibration_get_undistort_map( - data->view[1], view[1].rotation_mat, view[1].projection_mat); + view[0].rectify = calibration_get_undistort_map(data->view[0], view[0].rotation_mat, view[0].projection_mat); + view[1].rectify = calibration_get_undistort_map(data->view[1], view[1].rotation_mat, view[1].projection_mat); } /* @@ -184,8 +173,7 @@ StereoRectificationMaps::StereoRectificationMaps( */ extern "C" bool -t_stereo_camera_calibration_load_v1( - FILE *calib_file, struct t_stereo_camera_calibration **out_data) +t_stereo_camera_calibration_load_v1(FILE *calib_file, struct t_stereo_camera_calibration **out_data) { t_stereo_camera_calibration *data_ptr = NULL; t_stereo_camera_calibration_alloc(&data_ptr); @@ -265,8 +253,7 @@ t_stereo_camera_calibration_load_v1( */ extern "C" bool -t_stereo_camera_calibration_save_v1(FILE *calib_file, - struct t_stereo_camera_calibration *data) +t_stereo_camera_calibration_save_v1(FILE *calib_file, struct t_stereo_camera_calibration *data) { StereoCameraCalibrationWrapper wrapped(data); // Dummy matrix @@ -324,8 +311,7 @@ write_cv_mat(FILE *f, cv::Mat *m) header[1] = static_cast(m->rows); header[2] = static_cast(m->cols); fwrite(static_cast(header), sizeof(uint32_t), 3, f); - fwrite(static_cast(m->data), header[0], header[1] * header[2], - f); + fwrite(static_cast(m->data), header[0], header[1] * header[2], f); return true; } @@ -338,8 +324,7 @@ read_cv_mat(FILE *f, cv::Mat *m, const char *name) cv::Mat temp; read = fread(static_cast(header), sizeof(uint32_t), 3, f); if (read != 3) { - U_LOG_E("Failed to read mat header: '%i' '%s'", (int)read, - name); + U_LOG_E("Failed to read mat header: '%i' '%s'", (int)read, name); return false; } @@ -349,14 +334,11 @@ read_cv_mat(FILE *f, cv::Mat *m, const char *name) //! @todo We may have written things other than CV_32F and CV_64F. if (header[0] == 4) { - temp.create(static_cast(header[1]), - static_cast(header[2]), CV_32F); + temp.create(static_cast(header[1]), static_cast(header[2]), CV_32F); } else { - temp.create(static_cast(header[1]), - static_cast(header[2]), CV_64F); + temp.create(static_cast(header[1]), static_cast(header[2]), CV_64F); } - read = fread(static_cast(temp.data), header[0], - header[1] * header[2], f); + read = fread(static_cast(temp.data), header[0], header[1] * header[2], f); if (read != (header[1] * header[2])) { U_LOG_E("Failed to read mat body: '%i' '%s'", (int)read, name); return false; @@ -365,13 +347,11 @@ read_cv_mat(FILE *f, cv::Mat *m, const char *name) m->create(header[1], header[2], temp.type()); } if (temp.type() != m->type()) { - U_LOG_E("Mat body type does not match: %i vs %i for '%s'", - (int)temp.type(), (int)m->type(), name); + U_LOG_E("Mat body type does not match: %i vs %i for '%s'", (int)temp.type(), (int)m->type(), name); return false; } if (temp.total() != m->total()) { - U_LOG_E("Mat total size does not match: %i vs %i for '%s'", - (int)temp.total(), (int)m->total(), name); + U_LOG_E("Mat total size does not match: %i vs %i for '%s'", (int)temp.total(), (int)m->total(), name); return false; } if (temp.size() == m->size()) { @@ -379,8 +359,7 @@ read_cv_mat(FILE *f, cv::Mat *m, const char *name) temp.copyTo(*m); return true; } - if (temp.size().width == m->size().height && - temp.size().height == m->size().width) { + if (temp.size().width == m->size().height && temp.size().height == m->size().width) { U_LOG_W("Mat transposing on load: '%s'", name); // needs transpose cv::transpose(temp, *m); diff --git a/src/xrt/auxiliary/tracking/t_fusion.hpp b/src/xrt/auxiliary/tracking/t_fusion.hpp index 478423973..7c644e3d6 100644 --- a/src/xrt/auxiliary/tracking/t_fusion.hpp +++ b/src/xrt/auxiliary/tracking/t_fusion.hpp @@ -29,8 +29,7 @@ using flexkalman::types::Vector; //! For things like accelerometers, which on some level measure the local vector //! of a world direction. template -class WorldDirectionMeasurement - : public flexkalman::MeasurementBase> +class WorldDirectionMeasurement : public flexkalman::MeasurementBase> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW @@ -40,9 +39,7 @@ public: WorldDirectionMeasurement(types::Vector<3> const &direction, types::Vector<3> const &reference, types::Vector<3> const &variance) - : direction_(direction.normalized()), - reference_(reference.normalized()), - covariance_(variance.asDiagonal()) + : direction_(direction.normalized()), reference_(reference.normalized()), covariance_(variance.asDiagonal()) {} MeasurementSquareMatrix const & @@ -58,8 +55,7 @@ public: } MeasurementVector - getResidual(MeasurementVector const &predictedMeasurement, - State const &s) const + getResidual(MeasurementVector const &predictedMeasurement, State const &s) const { return predictedMeasurement - reference_; } @@ -133,16 +129,14 @@ private: }; #endif -class BiasedGyroMeasurement - : public flexkalman::MeasurementBase +class BiasedGyroMeasurement : public flexkalman::MeasurementBase { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW static constexpr size_t Dimension = 3; using MeasurementVector = types::Vector; using MeasurementSquareMatrix = types::SquareMatrix; - BiasedGyroMeasurement(types::Vector<3> const &angVel, - types::Vector<3> const &variance) + BiasedGyroMeasurement(types::Vector<3> const &angVel, types::Vector<3> const &variance) : angVel_(angVel), covariance_(variance.asDiagonal()) {} @@ -162,8 +156,7 @@ public: template MeasurementVector - getResidual(MeasurementVector const &predictedMeasurement, - State const &s) const + getResidual(MeasurementVector const &predictedMeasurement, State const &s) const { return predictedMeasurement - s.a().angularVelocity(); } @@ -183,8 +176,7 @@ private: * For PS Move-like things, where there's a directly-computed absolute position * that is not at the tracked body's origin. */ -class AbsolutePositionLeverArmMeasurement - : public flexkalman::MeasurementBase +class AbsolutePositionLeverArmMeasurement : public flexkalman::MeasurementBase { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW @@ -199,12 +191,10 @@ public: * approximation would be translation along the vector to the center of * projection.... */ - AbsolutePositionLeverArmMeasurement( - MeasurementVector const &measurement, - MeasurementVector const &knownLocationInBodySpace, - MeasurementVector const &variance) - : measurement_(measurement), - knownLocationInBodySpace_(knownLocationInBodySpace), + AbsolutePositionLeverArmMeasurement(MeasurementVector const &measurement, + MeasurementVector const &knownLocationInBodySpace, + MeasurementVector const &variance) + : measurement_(measurement), knownLocationInBodySpace_(knownLocationInBodySpace), covariance_(variance.asDiagonal()) {} @@ -221,8 +211,7 @@ public: } MeasurementVector - getResidual(MeasurementVector const &predictedMeasurement, - State const & /*s*/) const + getResidual(MeasurementVector const &predictedMeasurement, State const & /*s*/) const { return measurement_ - predictedMeasurement; } diff --git a/src/xrt/auxiliary/tracking/t_helper_debug_sink.hpp b/src/xrt/auxiliary/tracking/t_helper_debug_sink.hpp index 7c9de7b3c..59274351d 100644 --- a/src/xrt/auxiliary/tracking/t_helper_debug_sink.hpp +++ b/src/xrt/auxiliary/tracking/t_helper_debug_sink.hpp @@ -82,8 +82,7 @@ public: } // Create a new frame and also dereferences the old frame. - u_frame_create_one_off(XRT_FORMAT_R8G8B8, width, height, - &frame); + u_frame_create_one_off(XRT_FORMAT_R8G8B8, width, height, &frame); // Copy needed info. frame->source_sequence = xf->source_sequence; diff --git a/src/xrt/auxiliary/tracking/t_hsv_filter.c b/src/xrt/auxiliary/tracking/t_hsv_filter.c index 79fc8a6cd..66b44efd9 100644 --- a/src/xrt/auxiliary/tracking/t_hsv_filter.c +++ b/src/xrt/auxiliary/tracking/t_hsv_filter.c @@ -32,11 +32,9 @@ check_range(struct t_hsv_filter_color color, uint32_t h, uint32_t s, uint32_t v) } void -t_hsv_build_convert_table(struct t_hsv_filter_params *params, - struct t_convert_table *t) +t_hsv_build_convert_table(struct t_hsv_filter_params *params, struct t_convert_table *t) { - struct t_hsv_filter_large_table *temp = - U_TYPED_CALLOC(struct t_hsv_filter_large_table); + struct t_hsv_filter_large_table *temp = U_TYPED_CALLOC(struct t_hsv_filter_large_table); t_hsv_build_large_table(params, temp); uint8_t *dst = &t->v[0][0][0][0]; @@ -59,8 +57,7 @@ t_hsv_build_convert_table(struct t_hsv_filter_params *params, } void -t_hsv_build_large_table(struct t_hsv_filter_params *params, - struct t_hsv_filter_large_table *t) +t_hsv_build_large_table(struct t_hsv_filter_params *params, struct t_hsv_filter_large_table *t) { struct t_convert_table *temp = U_TYPED_CALLOC(struct t_convert_table); t_convert_make_y8u8v8_to_h8s8v8(temp); @@ -73,17 +70,12 @@ t_hsv_build_large_table(struct t_hsv_filter_params *params, uint8_t s = temp->v[y][u][v][1]; uint8_t v2 = temp->v[y][u][v][2]; - bool f0 = - check_range(params->color[0], h, s, v2); - bool f1 = - check_range(params->color[1], h, s, v2); - bool f2 = - check_range(params->color[2], h, s, v2); - bool f3 = s <= params->white.s_max && - v2 >= params->white.v_min; - - *dst = (f0 << 0) | (f1 << 1) | (f2 << 2) | - (f3 << 3); + bool f0 = check_range(params->color[0], h, s, v2); + bool f1 = check_range(params->color[1], h, s, v2); + bool f2 = check_range(params->color[2], h, s, v2); + bool f3 = s <= params->white.s_max && v2 >= params->white.v_min; + + *dst = (f0 << 0) | (f1 << 1) | (f2 << 2) | (f3 << 3); dst += 1; } } @@ -93,11 +85,9 @@ t_hsv_build_large_table(struct t_hsv_filter_params *params, } void -t_hsv_build_optimized_table(struct t_hsv_filter_params *params, - struct t_hsv_filter_optimized_table *t) +t_hsv_build_optimized_table(struct t_hsv_filter_params *params, struct t_hsv_filter_optimized_table *t) { - struct t_hsv_filter_large_table *temp = - U_TYPED_CALLOC(struct t_hsv_filter_large_table); + struct t_hsv_filter_large_table *temp = U_TYPED_CALLOC(struct t_hsv_filter_large_table); t_hsv_build_large_table(params, temp); // Half of step, minues one @@ -230,10 +220,8 @@ process_frame_yuyv(struct t_hsv_filter *f, struct xrt_frame *xf) uint8_t cr = src[3]; src += 4; - uint8_t bits0 = - t_hsv_filter_sample(&f->table, y1, cb, cr); - uint8_t bits1 = - t_hsv_filter_sample(&f->table, y2, cb, cr); + uint8_t bits0 = t_hsv_filter_sample(&f->table, y1, cb, cr); + uint8_t bits1 = t_hsv_filter_sample(&f->table, y2, cb, cr); uint8_t v0 = (bits0 & (1 << 0)) ? 0xff : 0x00; uint8_t v1 = (bits0 & (1 << 1)) ? 0xff : 0x00; @@ -270,10 +258,7 @@ ensure_buf_allocated(struct t_hsv_filter *f, struct xrt_frame *xf) } static void -push_buf(struct t_hsv_filter *f, - struct xrt_frame *xf, - struct xrt_frame_sink *xsink, - struct xrt_frame **frame) +push_buf(struct t_hsv_filter *f, struct xrt_frame *xf, struct xrt_frame_sink *xsink, struct xrt_frame **frame) { if (xsink == NULL) { xrt_frame_reference(frame, NULL); diff --git a/src/xrt/auxiliary/tracking/t_imu.cpp b/src/xrt/auxiliary/tracking/t_imu.cpp index 81a5c120b..9df57331f 100644 --- a/src/xrt/auxiliary/tracking/t_imu.cpp +++ b/src/xrt/auxiliary/tracking/t_imu.cpp @@ -64,8 +64,7 @@ imu_fusion_incorporate_gyros(struct imu_fusion *fusion, assert(ang_vel_variance); assert(timestamp_ns != 0); - fusion->simple_fusion.handleGyro( - map_vec3(*ang_vel).cast(), timestamp_ns); + fusion->simple_fusion.handleGyro(map_vec3(*ang_vel).cast(), timestamp_ns); return 0; } catch (...) { assert(false && "Caught exception on incorporate gyros"); @@ -88,15 +87,12 @@ imu_fusion_incorporate_accelerometer(struct imu_fusion *fusion, Eigen::Vector3d accelVec = map_vec3(*accel).cast(); fusion->simple_fusion.handleAccel(accelVec, timestamp_ns); if (out_world_accel != NULL) { - Eigen::Vector3d worldAccel = - fusion->simple_fusion.getCorrectedWorldAccel( - accelVec); + Eigen::Vector3d worldAccel = fusion->simple_fusion.getCorrectedWorldAccel(accelVec); map_vec3(*out_world_accel) = worldAccel.cast(); } return 0; } catch (...) { - assert(false && - "Caught exception on incorporate accelerometer"); + assert(false && "Caught exception on incorporate accelerometer"); return -1; } } @@ -116,17 +112,14 @@ imu_fusion_get_prediction(struct imu_fusion const *fusion, return -2; } - map_vec3(*out_ang_vel) = - fusion->simple_fusion.getAngVel().cast(); + map_vec3(*out_ang_vel) = fusion->simple_fusion.getAngVel().cast(); if (timestamp_ns == fusion->time_ns) { // No need to predict here. - map_quat(*out_quat) = - fusion->simple_fusion.getQuat().cast(); + map_quat(*out_quat) = fusion->simple_fusion.getQuat().cast(); return 0; } - Eigen::Quaterniond predicted_quat = - fusion->simple_fusion.getPredictedQuat(timestamp_ns); + Eigen::Quaterniond predicted_quat = fusion->simple_fusion.getPredictedQuat(timestamp_ns); map_quat(*out_quat) = predicted_quat.cast(); return 0; @@ -151,16 +144,10 @@ imu_fusion_get_prediction_rotation_vec(struct imu_fusion const *fusion, } if (timestamp_ns == fusion->time_ns) { // No need to predict here. - map_vec3(*out_rotation_vec) = - fusion->simple_fusion.getRotationVec() - .cast(); + map_vec3(*out_rotation_vec) = fusion->simple_fusion.getRotationVec().cast(); } else { - Eigen::Quaterniond predicted_quat = - fusion->simple_fusion.getPredictedQuat( - timestamp_ns); - map_vec3(*out_rotation_vec) = - flexkalman::util::quat_ln(predicted_quat) - .cast(); + Eigen::Quaterniond predicted_quat = fusion->simple_fusion.getPredictedQuat(timestamp_ns); + map_vec3(*out_rotation_vec) = flexkalman::util::quat_ln(predicted_quat).cast(); } return 0; } catch (...) { @@ -170,14 +157,13 @@ imu_fusion_get_prediction_rotation_vec(struct imu_fusion const *fusion, } int -imu_fusion_incorporate_gyros_and_accelerometer( - struct imu_fusion *fusion, - uint64_t timestamp_ns, - struct xrt_vec3 const *ang_vel, - struct xrt_vec3 const *ang_vel_variance, - struct xrt_vec3 const *accel, - struct xrt_vec3 const *accel_variance, - struct xrt_vec3 *out_world_accel) +imu_fusion_incorporate_gyros_and_accelerometer(struct imu_fusion *fusion, + uint64_t timestamp_ns, + struct xrt_vec3 const *ang_vel, + struct xrt_vec3 const *ang_vel_variance, + struct xrt_vec3 const *accel, + struct xrt_vec3 const *accel_variance, + struct xrt_vec3 *out_world_accel) { try { assert(fusion); @@ -193,16 +179,12 @@ imu_fusion_incorporate_gyros_and_accelerometer( fusion->simple_fusion.handleGyro(angVelVec, timestamp_ns); fusion->simple_fusion.postCorrect(); if (out_world_accel != NULL) { - Eigen::Vector3d worldAccel = - fusion->simple_fusion.getCorrectedWorldAccel( - accelVec); + Eigen::Vector3d worldAccel = fusion->simple_fusion.getCorrectedWorldAccel(accelVec); map_vec3(*out_world_accel) = worldAccel.cast(); } return 0; } catch (...) { - assert( - false && - "Caught exception on incorporate gyros and accelerometer"); + assert(false && "Caught exception on incorporate gyros and accelerometer"); return -1; } } diff --git a/src/xrt/auxiliary/tracking/t_imu.h b/src/xrt/auxiliary/tracking/t_imu.h index b3219f765..890c8162a 100644 --- a/src/xrt/auxiliary/tracking/t_imu.h +++ b/src/xrt/auxiliary/tracking/t_imu.h @@ -123,14 +123,13 @@ imu_fusion_incorporate_accelerometer(struct imu_fusion *fusion, * @ingroup aux_tracking */ int -imu_fusion_incorporate_gyros_and_accelerometer( - struct imu_fusion *fusion, - uint64_t timestamp_ns, - struct xrt_vec3 const *ang_vel, - struct xrt_vec3 const *ang_vel_variance, - struct xrt_vec3 const *accel, - struct xrt_vec3 const *accel_variance, - struct xrt_vec3 *out_world_accel); +imu_fusion_incorporate_gyros_and_accelerometer(struct imu_fusion *fusion, + uint64_t timestamp_ns, + struct xrt_vec3 const *ang_vel, + struct xrt_vec3 const *ang_vel_variance, + struct xrt_vec3 const *accel, + struct xrt_vec3 const *accel_variance, + struct xrt_vec3 *out_world_accel); /*! * Get the predicted state. Does not advance the internal state clock. diff --git a/src/xrt/auxiliary/tracking/t_imu_fusion.hpp b/src/xrt/auxiliary/tracking/t_imu_fusion.hpp index 890f4eabb..d16e3514c 100644 --- a/src/xrt/auxiliary/tracking/t_imu_fusion.hpp +++ b/src/xrt/auxiliary/tracking/t_imu_fusion.hpp @@ -43,8 +43,7 @@ public: * accelerometer should affect the orientation each second. */ explicit SimpleIMUFusion(double gravity_rate = 0.9) - : gravity_scale_(gravity_rate), - ll(debug_get_log_option_simple_imu_log()) + : gravity_scale_(gravity_rate), ll(debug_get_log_option_simple_imu_log()) { SIMPLE_IMU_DEBUG("Creating instance"); } @@ -142,8 +141,7 @@ public: getCorrectedWorldAccel(Eigen::Vector3d const &accel) const { Eigen::Vector3d adjusted_accel = accel * getAccelScaleFactor_(); - return (quat_ * adjusted_accel) - - (Eigen::Vector3d::UnitY() * MATH_GRAVITY_M_S2); + return (quat_ * adjusted_accel) - (Eigen::Vector3d::UnitY() * MATH_GRAVITY_M_S2); } /*! @@ -185,8 +183,7 @@ private: * user-caused acceleration, and do not reflect the direction of * gravity. */ - LowPassIIRVectorFilter<3, double> accel_filter_{ - 200 /* hz cutoff frequency */}; + LowPassIIRVectorFilter<3, double> accel_filter_{200 /* hz cutoff frequency */}; /*! * @brief Even-lower low pass filter on the length of the acceleration @@ -207,8 +204,7 @@ private: inline Eigen::Quaterniond SimpleIMUFusion::getPredictedQuat(timepoint_ns timestamp) const { - timepoint_ns state_time = - std::max(last_accel_timestamp_, last_gyro_timestamp_); + timepoint_ns state_time = std::max(last_accel_timestamp_, last_gyro_timestamp_); if (state_time == 0) { // no data yet. return Eigen::Quaterniond::Identity(); @@ -227,9 +223,7 @@ SimpleIMUFusion::handleGyro(Eigen::Vector3d const &gyro, timepoint_ns timestamp) "report"); return false; } - time_duration_ns delta_ns = (last_gyro_timestamp_ == 0) - ? 1e6 - : timestamp - last_gyro_timestamp_; + time_duration_ns delta_ns = (last_gyro_timestamp_ == 0) ? 1e6 : timestamp - last_gyro_timestamp_; if (delta_ns > 1e10) { SIMPLE_IMU_DEBUG("Clamping integration period"); @@ -242,8 +236,7 @@ SimpleIMUFusion::handleGyro(Eigen::Vector3d const &gyro, timepoint_ns timestamp) Eigen::Vector3d incRot = gyro * dt; // Crude handling of "approximately zero" if (incRot.squaredNorm() < gyro_min_squared_length_) { - SIMPLE_IMU_TRACE( - "Discarding gyro data that is approximately zero"); + SIMPLE_IMU_TRACE("Discarding gyro data that is approximately zero"); return false; } @@ -255,12 +248,9 @@ SimpleIMUFusion::handleGyro(Eigen::Vector3d const &gyro, timepoint_ns timestamp) return true; } inline bool -SimpleIMUFusion::handleAccel(Eigen::Vector3d const &accel, - timepoint_ns timestamp) +SimpleIMUFusion::handleAccel(Eigen::Vector3d const &accel, timepoint_ns timestamp) { - uint64_t delta_ns = (last_accel_timestamp_ == 0) - ? 1e6 - : timestamp - last_accel_timestamp_; + uint64_t delta_ns = (last_accel_timestamp_ == 0) ? 1e6 : timestamp - last_accel_timestamp_; float dt = time_ns_to_s(delta_ns); if (!started_) { auto diff = std::abs(accel.norm() - MATH_GRAVITY_M_S2); @@ -275,8 +265,7 @@ SimpleIMUFusion::handleAccel(Eigen::Vector3d const &accel, // Initially, just set it to totally trust gravity. started_ = true; - quat_ = Eigen::Quaterniond::FromTwoVectors( - accel.normalized(), Eigen::Vector3d::UnitY()); + quat_ = Eigen::Quaterniond::FromTwoVectors(accel.normalized(), Eigen::Vector3d::UnitY()); accel_filter_.addSample(accel, timestamp); gravity_filter_.addSample(accel.norm(), timestamp); last_accel_timestamp_ = timestamp; @@ -289,8 +278,7 @@ SimpleIMUFusion::handleAccel(Eigen::Vector3d const &accel, gravity_filter_.addSample(accel.norm(), timestamp); // Adjust scale of accelerometer - Eigen::Vector3d adjusted_accel = - accel_filter_.getState() * getAccelScaleFactor_(); + Eigen::Vector3d adjusted_accel = accel_filter_.getState() * getAccelScaleFactor_(); // How different is the acceleration length from gravity? auto diff = std::abs(adjusted_accel.norm() - MATH_GRAVITY_M_S2); @@ -304,14 +292,11 @@ SimpleIMUFusion::handleAccel(Eigen::Vector3d const &accel, // This should match the global gravity vector if the rotation // is right. - Eigen::Vector3d measuredGravityDirection = - (quat_ * adjusted_accel).normalized(); - auto incremental = Eigen::Quaterniond::FromTwoVectors( - measuredGravityDirection, Eigen::Vector3d::UnitY()); + Eigen::Vector3d measuredGravityDirection = (quat_ * adjusted_accel).normalized(); + auto incremental = Eigen::Quaterniond::FromTwoVectors(measuredGravityDirection, Eigen::Vector3d::UnitY()); double alpha = scale * gravity_scale_ * dt; - Eigen::Quaterniond scaledIncrementalQuat = - Eigen::Quaterniond::Identity().slerp(alpha, incremental); + Eigen::Quaterniond scaledIncrementalQuat = Eigen::Quaterniond::Identity().slerp(alpha, incremental); // Update orientation quat_ = scaledIncrementalQuat * quat_; diff --git a/src/xrt/auxiliary/tracking/t_lowpass.hpp b/src/xrt/auxiliary/tracking/t_lowpass.hpp index 2e1f124d3..6105ed103 100644 --- a/src/xrt/auxiliary/tracking/t_lowpass.hpp +++ b/src/xrt/auxiliary/tracking/t_lowpass.hpp @@ -30,10 +30,9 @@ namespace implementation { { // For fixed point, you'd need more bits of data storage. See // https://www.embeddedrelated.com/showarticle/779.php - static_assert( - std::is_floating_point::value, - "Filter is designed only for floating-point values. If " - "you want fixed-point, you must reimplement it."); + static_assert(std::is_floating_point::value, + "Filter is designed only for floating-point values. If " + "you want fixed-point, you must reimplement it."); // EIGEN_MAKE_ALIGNED_OPERATOR_NEW /*! @@ -73,9 +72,7 @@ namespace implementation { * state. For the first call, this is always assumed to be 1. */ void - addSample(Value const &sample, - timepoint_ns timestamp_ns, - Scalar weight = 1) + addSample(Value const &sample, timepoint_ns timestamp_ns, Scalar weight = 1) { if (!initialized) { initialized = true; @@ -84,8 +81,7 @@ namespace implementation { return; } // get dt in seconds - Scalar dt = - time_ns_to_s(timestamp_ns - filter_timestamp_ns); + Scalar dt = time_ns_to_s(timestamp_ns - filter_timestamp_ns); //! @todo limit max dt? Scalar weighted = dt * weight; Scalar alpha = weighted / (time_constant + weighted); @@ -121,9 +117,7 @@ public: * lower in frequency will be passed through the filter, while signal * changes much higher in frequency will be blocked. */ - explicit LowPassIIRFilter(Scalar cutoff_hz) noexcept - : impl_(cutoff_hz, 0) - {} + explicit LowPassIIRFilter(Scalar cutoff_hz) noexcept : impl_(cutoff_hz, 0) {} /*! diff --git a/src/xrt/auxiliary/tracking/t_lowpass_vector.hpp b/src/xrt/auxiliary/tracking/t_lowpass_vector.hpp index 046bba7ea..2e2dbc8fa 100644 --- a/src/xrt/auxiliary/tracking/t_lowpass_vector.hpp +++ b/src/xrt/auxiliary/tracking/t_lowpass_vector.hpp @@ -40,9 +40,7 @@ public: * lower in frequency will be passed through the filter, while signal * changes much higher in frequency will be blocked. */ - explicit LowPassIIRVectorFilter(Scalar cutoff_hz) noexcept - : impl_(cutoff_hz, Vector::Zero()) - {} + explicit LowPassIIRVectorFilter(Scalar cutoff_hz) noexcept : impl_(cutoff_hz, Vector::Zero()) {} /*! @@ -64,9 +62,7 @@ public: * the first call, this is always assumed to be 1. */ void - addSample(Vector const &sample, - std::uint64_t timestamp_ns, - Scalar weight = 1) + addSample(Vector const &sample, std::uint64_t timestamp_ns, Scalar weight = 1) { impl_.addSample(sample, timestamp_ns, weight); } diff --git a/src/xrt/auxiliary/tracking/t_tracker_hand.cpp b/src/xrt/auxiliary/tracking/t_tracker_hand.cpp index 0b96910f2..b2482d101 100644 --- a/src/xrt/auxiliary/tracking/t_tracker_hand.cpp +++ b/src/xrt/auxiliary/tracking/t_tracker_hand.cpp @@ -40,8 +40,7 @@ struct View cv::Mat frame_undist_rectified; void - populate_from_calib(t_camera_calibration &calib, - const RemapPair &rectification) + populate_from_calib(t_camera_calibration &calib, const RemapPair &rectification) { CameraCalibrationWrapper wrap(calib); intrinsics = wrap.intrinsics_mat; @@ -125,12 +124,11 @@ do_view(TrackerHand &t, View &view, cv::Mat &grey, cv::Mat &rgb) // Debug is wanted, draw the keypoints. if (rgb.cols > 0) { - cv::drawKeypoints( - view.frame_undist_rectified, // image - view.keypoints, // keypoints - rgb, // outImage - cv::Scalar(255, 0, 0), // color - cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); // flags + cv::drawKeypoints(view.frame_undist_rectified, // image + view.keypoints, // keypoints + rgb, // outImage + cv::Scalar(255, 0, 0), // color + cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); // flags } } @@ -163,8 +161,7 @@ process(TrackerHand &t, struct xrt_frame *xf) int rect_rows = t.view[0].undistort_rectify_map_x.rows; if (cols != rect_cols || rows != rect_rows) { - U_LOG_E("%dx%d rectification matrix does not fit %dx%d Image", - rect_cols, rect_rows, cols, rows); + U_LOG_E("%dx%d rectification matrix does not fit %dx%d Image", rect_cols, rect_rows, cols, rows); return; } @@ -398,10 +395,8 @@ t_hand_create(struct xrt_frame_context *xfctx, // Everything is safe, now setup the variable tracking. u_var_add_root(&t, "Hand Tracker", true); - u_var_add_vec3_f32(&t, &t.hand_data[0].hand_relation.pose.position, - "hand.tracker.pos.0"); - u_var_add_vec3_f32(&t, &t.hand_data[1].hand_relation.pose.position, - "hand.tracker.pos.1"); + u_var_add_vec3_f32(&t, &t.hand_data[0].hand_relation.pose.position, "hand.tracker.pos.0"); + u_var_add_vec3_f32(&t, &t.hand_data[1].hand_relation.pose.position, "hand.tracker.pos.1"); u_var_add_sink(&t, &t.debug.sink, "Debug"); *out_sink = &t.sink; diff --git a/src/xrt/auxiliary/tracking/t_tracker_psmv.cpp b/src/xrt/auxiliary/tracking/t_tracker_psmv.cpp index e4ae3ecbc..7cd6bf8ed 100644 --- a/src/xrt/auxiliary/tracking/t_tracker_psmv.cpp +++ b/src/xrt/auxiliary/tracking/t_tracker_psmv.cpp @@ -51,8 +51,7 @@ struct View cv::Mat frame_undist_rectified; void - populate_from_calib(t_camera_calibration &calib, - const RemapPair &rectification) + populate_from_calib(t_camera_calibration &calib, const RemapPair &rectification) { CameraCalibrationWrapper wrap(calib); intrinsics = wrap.intrinsics_mat; @@ -148,12 +147,11 @@ do_view(TrackerPSMV &t, View &view, cv::Mat &grey, cv::Mat &rgb) // Debug is wanted, draw the keypoints. if (rgb.cols > 0) { - cv::drawKeypoints( - view.frame_undist_rectified, // image - view.keypoints, // keypoints - rgb, // outImage - cv::Scalar(255, 0, 0), // color - cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); // flags + cv::drawKeypoints(view.frame_undist_rectified, // image + view.keypoints, // keypoints + rgb, // outImage + cv::Scalar(255, 0, 0), // color + cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); // flags } } @@ -204,9 +202,7 @@ make_lowest_score_finder(FunctionType scoreFunctor) //! Convert our 2d point + disparities into 3d points. static cv::Point3f -world_point_from_blobs(cv::Point2f left, - cv::Point2f right, - const cv::Matx44d &disparity_to_depth) +world_point_from_blobs(cv::Point2f left, cv::Point2f right, const cv::Matx44d &disparity_to_depth) { float disp = right.x - left.x; cv::Vec4d xydw(left.x, left.y, disp, 1.0f); @@ -215,9 +211,7 @@ world_point_from_blobs(cv::Point2f left, // Divide by scale to get 3D vector from homogeneous coordinate. we // also invert x here - cv::Point3f world_point(-h_world[0] / h_world[3], - h_world[1] / h_world[3], - h_world[2] / h_world[3]); + cv::Point3f world_point(-h_world[0] / h_world[3], h_world[1] / h_world[3], h_world[2] / h_world[3]); return world_point; } @@ -259,38 +253,32 @@ process(TrackerPSMV &t, struct xrt_frame *xf) do_view(t, t.view[0], l_grey, t.debug.rgb[0]); do_view(t, t.view[1], r_grey, t.debug.rgb[1]); - cv::Point3f last_point(t.tracked_object_position.x, - t.tracked_object_position.y, - t.tracked_object_position.z); - auto nearest_world = - make_lowest_score_finder([&](cv::Point3f world_point) { - //! @todo don't really need the square root to be done here. - return cv::norm(world_point - last_point); - }); + cv::Point3f last_point(t.tracked_object_position.x, t.tracked_object_position.y, t.tracked_object_position.z); + auto nearest_world = make_lowest_score_finder([&](cv::Point3f world_point) { + //! @todo don't really need the square root to be done here. + return cv::norm(world_point - last_point); + }); // do some basic matching to come up with likely disparity-pairs. - const cv::Matx44d disparity_to_depth = - static_cast(t.disparity_to_depth); + const cv::Matx44d disparity_to_depth = static_cast(t.disparity_to_depth); for (const cv::KeyPoint &l_keypoint : t.view[0].keypoints) { cv::Point2f l_blob = l_keypoint.pt; - auto nearest_blob = make_lowest_score_finder( - [&](cv::Point2f r_blob) { return l_blob.x - r_blob.x; }); + auto nearest_blob = + make_lowest_score_finder([&](cv::Point2f r_blob) { return l_blob.x - r_blob.x; }); for (const cv::KeyPoint &r_keypoint : t.view[1].keypoints) { cv::Point2f r_blob = r_keypoint.pt; // find closest point on same-ish scanline - if ((l_blob.y < r_blob.y + 3) && - (l_blob.y > r_blob.y - 3)) { + if ((l_blob.y < r_blob.y + 3) && (l_blob.y > r_blob.y - 3)) { nearest_blob.handle_candidate(r_blob); } } //! @todo do we need to avoid claiming the same counterpart //! several times? if (nearest_blob.got_one) { - cv::Point3f pt = world_point_from_blobs( - l_blob, nearest_blob.best, disparity_to_depth); + cv::Point3f pt = world_point_from_blobs(l_blob, nearest_blob.best, disparity_to_depth); nearest_world.handle_candidate(pt); } } @@ -298,8 +286,7 @@ process(TrackerPSMV &t, struct xrt_frame *xf) if (nearest_world.got_one) { cv::Point3f world_point = nearest_world.best; // update internal state - memcpy(&t.tracked_object_position, &world_point.x, - sizeof(t.tracked_object_position)); + memcpy(&t.tracked_object_position, &world_point.x, sizeof(t.tracked_object_position)); } else { t.filter->clear_position_tracked_flag(); } @@ -325,10 +312,9 @@ process(TrackerPSMV &t, struct xrt_frame *xf) // some research. xrt_vec3 variance{1.e-4f, 1.e-4f, 4.e-4f}; #endif - t.filter->process_3d_vision_data( - 0, &t.tracked_object_position, NULL, NULL, - //! @todo tune cutoff for residual arbitrarily "too large" - 15); + t.filter->process_3d_vision_data(0, &t.tracked_object_position, NULL, NULL, + //! @todo tune cutoff for residual arbitrarily "too large" + 15); } else { t.filter->clear_position_tracked_flag(); } @@ -377,10 +363,7 @@ run(TrackerPSMV &t) * @brief Retrieves a pose from the filter. */ static void -get_pose(TrackerPSMV &t, - enum xrt_input_name name, - timepoint_ns when_ns, - struct xrt_space_relation *out_relation) +get_pose(TrackerPSMV &t, enum xrt_input_name name, timepoint_ns when_ns, struct xrt_space_relation *out_relation) { os_thread_helper_lock(&t.oth); @@ -397,9 +380,8 @@ get_pose(TrackerPSMV &t, out_relation->pose.orientation.z = 0.0f; out_relation->pose.orientation.w = 1.0f; - out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT); + out_relation->relation_flags = (enum xrt_space_relation_flags)(XRT_SPACE_RELATION_POSITION_VALID_BIT | + XRT_SPACE_RELATION_POSITION_TRACKED_BIT); os_thread_helper_unlock(&t.oth); return; @@ -411,9 +393,7 @@ get_pose(TrackerPSMV &t, } static void -imu_data(TrackerPSMV &t, - timepoint_ns timestamp_ns, - struct xrt_tracking_sample *sample) +imu_data(TrackerPSMV &t, timepoint_ns timestamp_ns, struct xrt_tracking_sample *sample) { os_thread_helper_lock(&t.oth); @@ -459,9 +439,7 @@ break_apart(TrackerPSMV &t) */ extern "C" void -t_psmv_push_imu(struct xrt_tracked_psmv *xtmv, - timepoint_ns timestamp_ns, - struct xrt_tracking_sample *sample) +t_psmv_push_imu(struct xrt_tracked_psmv *xtmv, timepoint_ns timestamp_ns, struct xrt_tracking_sample *sample) { auto &t = *container_of(xtmv, TrackerPSMV, base); imu_data(t, timestamp_ns, sample); diff --git a/src/xrt/auxiliary/tracking/t_tracker_psmv_fusion.cpp b/src/xrt/auxiliary/tracking/t_tracker_psmv_fusion.cpp index f2f892012..5ea065e21 100644 --- a/src/xrt/auxiliary/tracking/t_tracker_psmv_fusion.cpp +++ b/src/xrt/auxiliary/tracking/t_tracker_psmv_fusion.cpp @@ -29,8 +29,7 @@ using State = flexkalman::pose_externalized_rotation::State; -using ProcessModel = - flexkalman::PoseSeparatelyDampedConstantVelocityProcessModel; +using ProcessModel = flexkalman::PoseSeparatelyDampedConstantVelocityProcessModel; namespace xrt_fusion { @@ -51,20 +50,16 @@ namespace { void process_imu_data(timepoint_ns timestamp_ns, const struct xrt_tracking_sample *sample, - const struct xrt_vec3 - *orientation_variance_optional) override; + const struct xrt_vec3 *orientation_variance_optional) override; void - process_3d_vision_data( - timepoint_ns timestamp_ns, - const struct xrt_vec3 *position, - const struct xrt_vec3 *variance_optional, - const struct xrt_vec3 *lever_arm_optional, - float residual_limit) override; + process_3d_vision_data(timepoint_ns timestamp_ns, + const struct xrt_vec3 *position, + const struct xrt_vec3 *variance_optional, + const struct xrt_vec3 *lever_arm_optional, + float residual_limit) override; void - get_prediction( - timepoint_ns when_ns, - struct xrt_space_relation *out_relation) override; + get_prediction(timepoint_ns when_ns, struct xrt_space_relation *out_relation) override; private: void @@ -107,21 +102,17 @@ namespace { } void - PSMVFusion::process_imu_data( - timepoint_ns timestamp_ns, - const struct xrt_tracking_sample *sample, - const struct xrt_vec3 *orientation_variance_optional) + PSMVFusion::process_imu_data(timepoint_ns timestamp_ns, + const struct xrt_tracking_sample *sample, + const struct xrt_vec3 *orientation_variance_optional) { Eigen::Vector3d variance = Eigen::Vector3d::Constant(0.01); if (orientation_variance_optional) { - variance = map_vec3(*orientation_variance_optional) - .cast(); + variance = map_vec3(*orientation_variance_optional).cast(); } - imu.handleAccel(map_vec3(sample->accel_m_s2).cast(), - timestamp_ns); - imu.handleGyro(map_vec3(sample->gyro_rad_secs).cast(), - timestamp_ns); + imu.handleAccel(map_vec3(sample->accel_m_s2).cast(), timestamp_ns); + imu.handleGyro(map_vec3(sample->gyro_rad_secs).cast(), timestamp_ns); imu.postCorrect(); //! @todo use better measurements instead of the above "simple @@ -134,9 +125,7 @@ namespace { filter_time_ns = timestamp_ns; auto meas = flexkalman::AbsoluteOrientationMeasurement{ // Must rotate by 180 to align - Eigen::Quaterniond( - Eigen::AngleAxisd(EIGEN_PI, Eigen::Vector3d::UnitY())) * - imu.getQuat(), + Eigen::Quaterniond(Eigen::AngleAxisd(EIGEN_PI, Eigen::Vector3d::UnitY())) * imu.getQuat(), variance}; if (flexkalman::correctUnscented(filter_state, meas)) { orientation_state.tracked = true; @@ -149,8 +138,7 @@ namespace { } // 7200 deg/sec constexpr double max_rad_per_sec = 20 * double(EIGEN_PI) * 2; - if (filter_state.angularVelocity().squaredNorm() > - max_rad_per_sec * max_rad_per_sec) { + if (filter_state.angularVelocity().squaredNorm() > max_rad_per_sec * max_rad_per_sec) { U_LOG_E( "Got excessive angular velocity when filtering " "IMU - resetting filter and IMU fusion!"); @@ -159,12 +147,11 @@ namespace { } void - PSMVFusion::process_3d_vision_data( - timepoint_ns timestamp_ns, - const struct xrt_vec3 *position, - const struct xrt_vec3 *variance_optional, - const struct xrt_vec3 *lever_arm_optional, - float residual_limit) + PSMVFusion::process_3d_vision_data(timepoint_ns timestamp_ns, + const struct xrt_vec3 *position, + const struct xrt_vec3 *variance_optional, + const struct xrt_vec3 *lever_arm_optional, + float residual_limit) { Eigen::Vector3f pos = map_vec3(*position); Eigen::Vector3d variance{1.e-4, 1.e-4, 4.e-4}; @@ -173,12 +160,10 @@ namespace { } Eigen::Vector3d lever_arm{0, 0.09, 0}; if (lever_arm_optional) { - lever_arm = - map_vec3(*lever_arm_optional).cast(); + lever_arm = map_vec3(*lever_arm_optional).cast(); } auto measurement = - xrt_fusion::AbsolutePositionLeverArmMeasurement{ - pos.cast(), lever_arm, variance}; + xrt_fusion::AbsolutePositionLeverArmMeasurement{pos.cast(), lever_arm, variance}; double resid = measurement.getResidual(filter_state).norm(); if (resid > residual_limit) { @@ -203,8 +188,7 @@ namespace { } void - PSMVFusion::get_prediction(timepoint_ns when_ns, - struct xrt_space_relation *out_relation) + PSMVFusion::get_prediction(timepoint_ns when_ns, struct xrt_space_relation *out_relation) { if (out_relation == NULL) { return; @@ -216,33 +200,26 @@ namespace { return; } float dt = time_ns_to_s(when_ns - filter_time_ns); - auto predicted_state = - flexkalman::getPrediction(filter_state, process_model, dt); + auto predicted_state = flexkalman::getPrediction(filter_state, process_model, dt); - map_vec3(out_relation->pose.position) = - predicted_state.position().cast(); - map_quat(out_relation->pose.orientation) = - predicted_state.getQuaternion().cast(); - map_vec3(out_relation->linear_velocity) = - predicted_state.velocity().cast(); - map_vec3(out_relation->angular_velocity) = - predicted_state.angularVelocity().cast(); + map_vec3(out_relation->pose.position) = predicted_state.position().cast(); + map_quat(out_relation->pose.orientation) = predicted_state.getQuaternion().cast(); + map_vec3(out_relation->linear_velocity) = predicted_state.velocity().cast(); + map_vec3(out_relation->angular_velocity) = predicted_state.angularVelocity().cast(); uint64_t flags = 0; if (position_state.valid) { flags |= XRT_SPACE_RELATION_POSITION_VALID_BIT; flags |= XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT; if (position_state.tracked) { - flags |= - XRT_SPACE_RELATION_POSITION_TRACKED_BIT; + flags |= XRT_SPACE_RELATION_POSITION_TRACKED_BIT; } } if (orientation_state.valid) { flags |= XRT_SPACE_RELATION_ORIENTATION_VALID_BIT; flags |= XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT; if (orientation_state.tracked) { - flags |= - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT; + flags |= XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT; } } out_relation->relation_flags = (xrt_space_relation_flags)flags; diff --git a/src/xrt/auxiliary/tracking/t_tracker_psmv_fusion.hpp b/src/xrt/auxiliary/tracking/t_tracker_psmv_fusion.hpp index 2850a798e..44f907a58 100644 --- a/src/xrt/auxiliary/tracking/t_tracker_psmv_fusion.hpp +++ b/src/xrt/auxiliary/tracking/t_tracker_psmv_fusion.hpp @@ -39,10 +39,9 @@ public: clear_position_tracked_flag() = 0; virtual void - process_imu_data( - timepoint_ns timestamp_ns, - const struct xrt_tracking_sample *sample, - const struct xrt_vec3 *orientation_variance_optional) = 0; + process_imu_data(timepoint_ns timestamp_ns, + const struct xrt_tracking_sample *sample, + const struct xrt_vec3 *orientation_variance_optional) = 0; virtual void process_3d_vision_data(timepoint_ns timestamp_ns, const struct xrt_vec3 *position, @@ -51,7 +50,6 @@ public: float residual_limit) = 0; virtual void - get_prediction(timepoint_ns when_ns, - struct xrt_space_relation *out_relation) = 0; + get_prediction(timepoint_ns when_ns, struct xrt_space_relation *out_relation) = 0; }; } // namespace xrt_fusion diff --git a/src/xrt/auxiliary/tracking/t_tracker_psvr.cpp b/src/xrt/auxiliary/tracking/t_tracker_psvr.cpp index 7981e4ba9..a598dc888 100644 --- a/src/xrt/auxiliary/tracking/t_tracker_psvr.cpp +++ b/src/xrt/auxiliary/tracking/t_tracker_psvr.cpp @@ -138,8 +138,7 @@ struct View cv::Mat frame_undist_rectified; void - populate_from_calib(t_camera_calibration &calib, - const RemapPair &rectification) + populate_from_calib(t_camera_calibration &calib, const RemapPair &rectification) { CameraCalibrationWrapper wrap(calib); intrinsics = wrap.intrinsics_mat; @@ -239,21 +238,16 @@ public: struct xrt_quat rot = {}; } optical; - Eigen::Quaternionf - target_optical_rotation_correction; // the calculated rotation to - // correct the imu - Eigen::Quaternionf - optical_rotation_correction; // currently applied (interpolated - // towards target) correction - Eigen::Matrix4f - corrected_imu_rotation; // imu rotation with correction applied - Eigen::Quaternionf - axis_align_rot; // used to rotate imu/tracking coordinates to world + Eigen::Quaternionf target_optical_rotation_correction; // the calculated rotation to + // correct the imu + Eigen::Quaternionf optical_rotation_correction; // currently applied (interpolated + // towards target) correction + Eigen::Matrix4f corrected_imu_rotation; // imu rotation with correction applied + Eigen::Quaternionf axis_align_rot; // used to rotate imu/tracking coordinates to world model_vertex_t model_vertices[PSVR_NUM_LEDS]; // the model we match our // measurements against - std::vector - last_vertices; // the last solved position of the HMD + std::vector last_vertices; // the last solved position of the HMD uint32_t last_optical_model; @@ -309,16 +303,13 @@ public: static float dist_3d(Eigen::Vector4f a, Eigen::Vector4f b) { - return sqrt((a[0] - b[0]) * (a[0] - b[0]) + - (a[1] - b[1]) * (a[1] - b[1]) + - (a[2] - b[2]) * (a[2] - b[2])); + return sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2])); } static float dist_3d_cv(cv::Point3f a, cv::Point3f b) { - return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + - (a.z - b.z) * (a.z - b.z)); + return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z)); } static void @@ -326,10 +317,8 @@ init_filter(cv::KalmanFilter &kf, float process_cov, float meas_cov, float dt) { kf.init(6, 3); kf.transitionMatrix = - (cv::Mat_(6, 6) << 1.0, 0.0, 0.0, dt, 0.0, 0.0, 0.0, 1.0, - 0.0, 0.0, dt, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, dt, 0.0, 0.0, 0.0, 1.0, - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 1.0); + (cv::Mat_(6, 6) << 1.0, 0.0, 0.0, dt, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, dt, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, + dt, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); cv::setIdentity(kf.measurementMatrix, cv::Scalar::all(1.0f)); cv::setIdentity(kf.errorCovPost, cv::Scalar::all(0.0f)); @@ -342,9 +331,7 @@ init_filter(cv::KalmanFilter &kf, float process_cov, float meas_cov, float dt) } static void -filter_predict(std::vector *pose, - cv::KalmanFilter *filters, - float dt) +filter_predict(std::vector *pose, cv::KalmanFilter *filters, float dt) { for (uint32_t i = 0; i < PSVR_NUM_LEDS; i++) { match_data_t current_led; @@ -366,9 +353,7 @@ filter_predict(std::vector *pose, } static void -filter_update(std::vector *pose, - cv::KalmanFilter *filters, - float dt) +filter_update(std::vector *pose, cv::KalmanFilter *filters, float dt) { for (uint32_t i = 0; i < PSVR_NUM_LEDS; i++) { match_data_t *current_led = &pose->at(i); @@ -404,9 +389,7 @@ pose_filter_predict(Eigen::Vector4f *pose, cv::KalmanFilter *filter, float dt) } static void -pose_filter_update(Eigen::Vector4f *position, - cv::KalmanFilter *filter, - float dt) +pose_filter_update(Eigen::Vector4f *position, cv::KalmanFilter *filter, float dt) { filter->transitionMatrix.at(0, 3) = dt; filter->transitionMatrix.at(1, 4) = dt; @@ -433,8 +416,7 @@ match_possible(match_model_t *match) } static void -verts_to_measurement(std::vector *meas_data, - std::vector *match_vertices) +verts_to_measurement(std::vector *meas_data, std::vector *match_vertices) { // create a data structure that holds the inter-point distances // and angles we will use to match the pose @@ -444,9 +426,8 @@ verts_to_measurement(std::vector *meas_data, for (uint32_t i = 0; i < meas_data->size(); i++) { match_data_t md; md.vertex_index = -1; - md.position = Eigen::Vector4f( - meas_data->at(i).p.x, meas_data->at(i).p.y, - meas_data->at(i).p.z, 1.0f); + md.position = + Eigen::Vector4f(meas_data->at(i).p.x, meas_data->at(i).p.y, meas_data->at(i).p.z, 1.0f); md.src_blob = meas_data->at(i); match_vertices->push_back(md); } @@ -466,20 +447,15 @@ verts_to_measurement(std::vector *meas_data, md.vertex_index = -1; md.position = Eigen::Vector4f(vp.p.x, vp.p.y, vp.p.z, 1.0f); Eigen::Vector3f ref_vec3(ref_vec.x, ref_vec.y, ref_vec.z); - Eigen::Vector3f point_vec3(point_vec.x, point_vec.y, - point_vec.z); + Eigen::Vector3f point_vec3(point_vec.x, point_vec.y, point_vec.z); Eigen::Vector3f vp_pos3(vp.p.x, vp.p.y, vp.p.z); if (i != 0) { - Eigen::Vector3f plane_norm = - ref_vec3.cross(point_vec3).normalized(); + Eigen::Vector3f plane_norm = ref_vec3.cross(point_vec3).normalized(); if (plane_norm.z() > 0) { - md.angle = - -1 * acos(point_vec3.normalized().dot( - ref_vec3.normalized())); + md.angle = -1 * acos(point_vec3.normalized().dot(ref_vec3.normalized())); } else { - md.angle = acos(point_vec3.normalized().dot( - ref_vec3.normalized())); + md.angle = acos(point_vec3.normalized().dot(ref_vec3.normalized())); } md.distance = dist_3d_cv(vp.p, ref_a.p) / ref_len; @@ -500,9 +476,7 @@ verts_to_measurement(std::vector *meas_data, } static float -last_diff(TrackerPSVR &t, - std::vector *meas_pose, - std::vector *last_pose) +last_diff(TrackerPSVR &t, std::vector *meas_pose, std::vector *last_pose) { // compute the aggregate difference (sum of distances between matching // indices)between two poses @@ -513,9 +487,8 @@ last_diff(TrackerPSVR &t, for (uint32_t j = 0; j < last_pose->size(); j++) { uint32_t last_index = last_pose->at(j).vertex_index; if (last_index == meas_index) { - float d = fabs(dist_3d( - meas_pose->at(meas_index).position, - last_pose->at(last_index).position)); + float d = fabs( + dist_3d(meas_pose->at(meas_index).position, last_pose->at(last_index).position)); diff += d; } } @@ -525,9 +498,7 @@ last_diff(TrackerPSVR &t, static void -remove_outliers(std::vector *orig_points, - std::vector *pruned_points, - float outlier_thresh) +remove_outliers(std::vector *orig_points, std::vector *pruned_points, float outlier_thresh) { if (orig_points->size() == 0) { @@ -563,17 +534,11 @@ remove_outliers(std::vector *orig_points, z_values.push_back(temp_points[i].p.z); } - std::nth_element(x_values.begin(), - x_values.begin() + x_values.size() / 2, - x_values.end()); + std::nth_element(x_values.begin(), x_values.begin() + x_values.size() / 2, x_values.end()); float median_x = x_values[x_values.size() / 2]; - std::nth_element(y_values.begin(), - y_values.begin() + y_values.size() / 2, - y_values.end()); + std::nth_element(y_values.begin(), y_values.begin() + y_values.size() / 2, y_values.end()); float median_y = y_values[y_values.size() / 2]; - std::nth_element(z_values.begin(), - z_values.begin() + z_values.size() / 2, - z_values.end()); + std::nth_element(z_values.begin(), z_values.begin() + z_values.size() / 2, z_values.end()); float median_z = z_values[z_values.size() / 2]; for (uint32_t i = 0; i < temp_points.size(); i++) { @@ -581,9 +546,7 @@ remove_outliers(std::vector *orig_points, float error_y = temp_points[i].p.y - median_y; float error_z = temp_points[i].p.z - median_z; - float rms_error = - sqrt((error_x * error_x) + (error_y * error_y) + - (error_z * error_z)); + float rms_error = sqrt((error_x * error_x) + (error_y * error_y) + (error_z * error_z)); // U_LOG_D("%f %f %f %f %f %f", temp_points[i].p.x, // temp_points[i].p.y, temp_points[i].p.z, error_x, @@ -602,9 +565,7 @@ struct close_pair }; static void -merge_close_points(std::vector *orig_points, - std::vector *merged_points, - float merge_thresh) +merge_close_points(std::vector *orig_points, std::vector *merged_points, float merge_thresh) { // if a pair of points in the supplied lists are closer than the // threshold, discard one of them. @@ -615,8 +576,7 @@ merge_close_points(std::vector *orig_points, for (uint32_t i = 0; i < orig_points->size(); i++) { for (uint32_t j = 0; j < orig_points->size(); j++) { if (i != j) { - float d = dist_3d_cv(orig_points->at(i).p, - orig_points->at(j).p); + float d = dist_3d_cv(orig_points->at(i).p, orig_points->at(j).p); if (d < merge_thresh) { struct close_pair p; p.index_a = i; @@ -668,13 +628,11 @@ match_triangles(Eigen::Matrix4f *t1_mat, Eigen::Matrix4f t2_mat = Eigen::Matrix4f().Identity(); Eigen::Vector3f t1_x_vec = (t1_b - t1_a).head<3>().normalized(); - Eigen::Vector3f t1_z_vec = - (t1_c - t1_a).head<3>().cross((t1_b - t1_a).head<3>()).normalized(); + Eigen::Vector3f t1_z_vec = (t1_c - t1_a).head<3>().cross((t1_b - t1_a).head<3>()).normalized(); Eigen::Vector3f t1_y_vec = t1_x_vec.cross(t1_z_vec).normalized(); Eigen::Vector3f t2_x_vec = (t2_b - t2_a).head<3>().normalized(); - Eigen::Vector3f t2_z_vec = - (t2_c - t2_a).head<3>().cross((t2_b - t2_a).head<3>()).normalized(); + Eigen::Vector3f t2_z_vec = (t2_c - t2_a).head<3>().cross((t2_b - t2_a).head<3>()).normalized(); Eigen::Vector3f t2_y_vec = t2_x_vec.cross(t2_z_vec).normalized(); t1_mat->col(0) << t1_x_vec[0], t1_x_vec[1], t1_x_vec[2], 0.0f; @@ -691,9 +649,7 @@ match_triangles(Eigen::Matrix4f *t1_mat, } static Eigen::Matrix4f -solve_for_measurement(TrackerPSVR *t, - std::vector *measurement, - std::vector *solved) +solve_for_measurement(TrackerPSVR *t, std::vector *measurement, std::vector *solved) { // use the vertex positions (at least 3) in the measurement to // construct a pair of triangles which are used to calculate the @@ -719,10 +675,8 @@ solve_for_measurement(TrackerPSVR *t, for (uint32_t i = 0; i < measurement->size(); i++) { int model_tag_index = measurement->at(i).vertex_index; - Eigen::Vector4f model_vert = - t->model_vertices[model_tag_index].position; - if (most_distant_index > 1 && - dist_3d(model_vert, model_ref_a) > highest_length) { + Eigen::Vector4f model_vert = t->model_vertices[model_tag_index].position; + if (most_distant_index > 1 && dist_3d(model_vert, model_ref_a) > highest_length) { best_model_index = most_distant_index; } most_distant_index++; @@ -733,11 +687,9 @@ solve_for_measurement(TrackerPSVR *t, Eigen::Vector4f model_ref_c = t->model_vertices[meas_index_c].position; - match_triangles(&tri_basis, &model_to_measurement, model_ref_a, - model_ref_b, model_ref_c, meas_ref_a, meas_ref_b, - meas_ref_c); - Eigen::Matrix4f model_center_transform_f = - tri_basis * model_to_measurement * tri_basis.inverse(); + match_triangles(&tri_basis, &model_to_measurement, model_ref_a, model_ref_b, model_ref_c, meas_ref_a, + meas_ref_b, meas_ref_c); + Eigen::Matrix4f model_center_transform_f = tri_basis * model_to_measurement * tri_basis.inverse(); // now reverse the order of our verts to contribute to a more accurate // estimate. @@ -756,8 +708,7 @@ solve_for_measurement(TrackerPSVR *t, for (uint32_t i = 0; i < measurement->size(); i++) { int model_tag_index = measurement->at(i).vertex_index; - Eigen::Vector4f model_vert = - t->model_vertices[model_tag_index].position; + Eigen::Vector4f model_vert = t->model_vertices[model_tag_index].position; if (most_distant_index < (int)measurement->size() - 2 && dist_3d(model_vert, model_ref_a) > highest_length) { best_model_index = most_distant_index; @@ -770,11 +721,9 @@ solve_for_measurement(TrackerPSVR *t, model_ref_c = t->model_vertices[meas_index_c].position; - match_triangles(&tri_basis, &model_to_measurement, model_ref_a, - model_ref_b, model_ref_c, meas_ref_a, meas_ref_b, - meas_ref_c); - Eigen::Matrix4f model_center_transform_r = - tri_basis * model_to_measurement * tri_basis.inverse(); + match_triangles(&tri_basis, &model_to_measurement, model_ref_a, model_ref_b, model_ref_c, meas_ref_a, + meas_ref_b, meas_ref_c); + Eigen::Matrix4f model_center_transform_r = tri_basis * model_to_measurement * tri_basis.inverse(); // decompose our transforms and slerp between them to get the avg of the // rotation determined from the first 2 + most distant , and last 2 + @@ -789,8 +738,7 @@ solve_for_measurement(TrackerPSVR *t, Eigen::Vector4f r_trans_part = model_center_transform_r.col(3); Eigen::Matrix4f pose = Eigen::Matrix4f().Identity(); - pose.block(0, 0, 3, 3) = - f_rot_part.slerp(0.5, r_rot_part).toRotationMatrix(); + pose.block(0, 0, 3, 3) = f_rot_part.slerp(0.5, r_rot_part).toRotationMatrix(); pose.col(3) = (f_trans_part + r_trans_part) / 2.0f; solved->clear(); @@ -827,9 +775,8 @@ solve_with_imu(TrackerPSVR &t, // distances for points we don't have std::vector > costMatrix = { + {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0}, }; HungarianAlgorithm HungAlgo; @@ -845,19 +792,13 @@ solve_with_imu(TrackerPSVR &t, for (uint32_t i = 0; i < measurements->size(); i++) { for (uint32_t j = 0; j < match_measurements->size(); j++) { - costMatrix[i][j] = - dist_3d(measurements->at(i).position, - match_measurements->at(j).position); - if (measurements->at(i).src_blob.btype == - BLOB_TYPE_SIDE && - match_measurements->at(j).src_blob.btype == - BLOB_TYPE_FRONT) { + costMatrix[i][j] = dist_3d(measurements->at(i).position, match_measurements->at(j).position); + if (measurements->at(i).src_blob.btype == BLOB_TYPE_SIDE && + match_measurements->at(j).src_blob.btype == BLOB_TYPE_FRONT) { costMatrix[i][j] += 10.0f; } - if (measurements->at(i).src_blob.btype == - BLOB_TYPE_FRONT && - match_measurements->at(j).src_blob.btype == - BLOB_TYPE_SIDE) { + if (measurements->at(i).src_blob.btype == BLOB_TYPE_FRONT && + match_measurements->at(j).src_blob.btype == BLOB_TYPE_SIDE) { costMatrix[i][j] += 10.0f; } } @@ -896,21 +837,16 @@ solve_with_imu(TrackerPSVR &t, std::vector temp_measurement_list; for (uint32_t i = 0; i < proximity_data.size(); i++) { proximity_data_t p = proximity_data[i]; - Eigen::Vector4f model_vertex = - t.model_vertices[p.vertex_index].position; + Eigen::Vector4f model_vertex = t.model_vertices[p.vertex_index].position; Eigen::Vector4f measurement_vertex = p.position; - Eigen::Vector4f measurement_offset = - t.corrected_imu_rotation * model_vertex; - Eigen::Affine3f translation(Eigen::Translation3f( - (measurement_vertex - measurement_offset) - .head<3>())); - Eigen::Matrix4f model_to_measurement = - translation.matrix() * t.corrected_imu_rotation; + Eigen::Vector4f measurement_offset = t.corrected_imu_rotation * model_vertex; + Eigen::Affine3f translation( + Eigen::Translation3f((measurement_vertex - measurement_offset).head<3>())); + Eigen::Matrix4f model_to_measurement = translation.matrix() * t.corrected_imu_rotation; match_model_t temp_measurement; for (uint32_t j = 0; j < PSVR_NUM_LEDS; j++) { match_data_t md; - md.position = model_to_measurement * - t.model_vertices[j].position; + md.position = model_to_measurement * t.model_vertices[j].position; md.vertex_index = j; temp_measurement.measurements.push_back(md); } @@ -919,24 +855,17 @@ solve_with_imu(TrackerPSVR &t, for (uint32_t i = 0; i < PSVR_NUM_LEDS; i++) { match_data_t avg_data; - avg_data.position = - Eigen::Vector4f(0.0f, 0.0f, 0.0f, 1.0f); - for (uint32_t j = 0; j < temp_measurement_list.size(); - j++) { - avg_data.position += temp_measurement_list[j] - .measurements[i] - .position; + avg_data.position = Eigen::Vector4f(0.0f, 0.0f, 0.0f, 1.0f); + for (uint32_t j = 0; j < temp_measurement_list.size(); j++) { + avg_data.position += temp_measurement_list[j].measurements[i].position; } - avg_data.position /= - float(temp_measurement_list.size()); + avg_data.position /= float(temp_measurement_list.size()); avg_data.vertex_index = i; solved->push_back(avg_data); } std::vector _solved; - Eigen::Matrix4f pose = - solve_for_measurement(&t, solved, &_solved) * - t.corrected_imu_rotation; + Eigen::Matrix4f pose = solve_for_measurement(&t, solved, &_solved) * t.corrected_imu_rotation; t.last_pose = pose; return pose; } @@ -960,11 +889,10 @@ disambiguate(TrackerPSVR &t, // do our imu-based solve up front - we can use this to compute a more // likely match (currently disabled) - Eigen::Matrix4f imu_solved_pose = solve_with_imu( - t, measured_points, last_measurement, solved, PSVR_SEARCH_RADIUS); + Eigen::Matrix4f imu_solved_pose = + solve_with_imu(t, measured_points, last_measurement, solved, PSVR_SEARCH_RADIUS); - if (measured_points->size() < PSVR_OPTICAL_SOLVE_THRESH && - last_measurement->size() > 0) { + if (measured_points->size() < PSVR_OPTICAL_SOLVE_THRESH && last_measurement->size() > 0) { return imu_solved_pose; } @@ -986,11 +914,9 @@ disambiguate(TrackerPSVR &t, match_model_t m = t.matches[t.last_optical_model]; for (uint32_t i = 0; i < measured_points->size(); i++) { - measured_points->at(i).vertex_index = - m.measurements.at(i).vertex_index; + measured_points->at(i).vertex_index = m.measurements.at(i).vertex_index; } - Eigen::Matrix4f res = - solve_for_measurement(&t, measured_points, solved); + Eigen::Matrix4f res = solve_for_measurement(&t, measured_points, solved); float diff = last_diff(t, solved, &t.last_vertices); if (diff < PSVR_HOLD_THRESH) { // U_LOG_D("diff from last: %f", diff); @@ -1015,8 +941,7 @@ disambiguate(TrackerPSVR &t, // data (this will be overwritten once our best model is // selected for (uint32_t j = 0; j < measured_points->size(); j++) { - measured_points->at(j).vertex_index = - m.measurements.at(j).vertex_index; + measured_points->at(j).vertex_index = m.measurements.at(j).vertex_index; } bool ignore = false; @@ -1028,14 +953,12 @@ disambiguate(TrackerPSVR &t, for (uint32_t j = 0; j < measured_points->size(); j++) { - if (measured_points->at(j).src_blob.btype == - BLOB_TYPE_FRONT && + if (measured_points->at(j).src_blob.btype == BLOB_TYPE_FRONT && measured_points->at(j).vertex_index > 4) { error_sum += 50.0f; } - if (measured_points->at(j).src_blob.btype == - BLOB_TYPE_SIDE && + if (measured_points->at(j).src_blob.btype == BLOB_TYPE_SIDE && measured_points->at(j).vertex_index < 5) { error_sum += 50.0f; } @@ -1043,36 +966,29 @@ disambiguate(TrackerPSVR &t, // if the distance is between a measured point // and its last-known position is significantly // different, discard this - float dist = fabs(measured_points->at(j).distance - - m.measurements.at(j).distance); + float dist = fabs(measured_points->at(j).distance - m.measurements.at(j).distance); if (dist > PSVR_DISAMBIG_REJECT_DIST) { error_sum += 50.0f; } else { - error_sum += - fabs(measured_points->at(j).distance - - m.measurements.at(j).distance); + error_sum += fabs(measured_points->at(j).distance - m.measurements.at(j).distance); } // if the angle is significantly different, // discard this - float angdiff = fabs(measured_points->at(j).angle - - m.measurements.at(j).angle); + float angdiff = fabs(measured_points->at(j).angle - m.measurements.at(j).angle); if (angdiff > PSVR_DISAMBIG_REJECT_ANG) { error_sum += 50.0f; } else { - error_sum += fabs(measured_points->at(j).angle - - m.measurements.at(j).angle); + error_sum += fabs(measured_points->at(j).angle - m.measurements.at(j).angle); } } float avg_error = (error_sum / measured_points->size()); if (error_sum < 50) { std::vector meas_solved; - solve_for_measurement(&t, measured_points, - &meas_solved); - float prev_diff = - last_diff(t, &meas_solved, &t.last_vertices); + solve_for_measurement(&t, measured_points, &meas_solved); + float prev_diff = last_diff(t, &meas_solved, &t.last_vertices); float imu_diff = last_diff(t, &meas_solved, solved); Eigen::Vector4f tl_pos, tr_pos, bl_pos, br_pos; @@ -1137,8 +1053,7 @@ disambiguate(TrackerPSVR &t, lowest_error = avg_error; best_model = i; for (uint32_t i = 0; i < measured_points->size(); i++) { - matched_vertex_indices[i] = - measured_points->at(i).vertex_index; + matched_vertex_indices[i] = measured_points->at(i).vertex_index; } } } @@ -1154,10 +1069,8 @@ disambiguate(TrackerPSVR &t, measured_points->at(i).vertex_index = matched_vertex_indices[i]; cv::putText( t.debug.rgb[0], - cv::format("%d %d", measured_points->at(i).vertex_index, - measured_points->at(i).src_blob.btype), - measured_points->at(i).src_blob.lkp.pt, - cv::FONT_HERSHEY_SIMPLEX, 1.0f, cv::Scalar(0, 255, 0)); + cv::format("%d %d", measured_points->at(i).vertex_index, measured_points->at(i).src_blob.btype), + measured_points->at(i).src_blob.lkp.pt, cv::FONT_HERSHEY_SIMPLEX, 1.0f, cv::Scalar(0, 255, 0)); } t.last_pose = solve_for_measurement(&t, measured_points, solved); @@ -1263,39 +1176,26 @@ create_match_list(TrackerPSVR &t) model_vertex_t ref_pt_a = mp.vec[0]; model_vertex_t ref_pt_b = mp.vec[1]; - Eigen::Vector3f ref_vec3 = - (ref_pt_b.position - ref_pt_a.position).head<3>(); + Eigen::Vector3f ref_vec3 = (ref_pt_b.position - ref_pt_a.position).head<3>(); float normScale = dist_3d(ref_pt_a.position, ref_pt_b.position); match_data_t md; for (auto &&i : mp.vec) { - Eigen::Vector3f point_vec3 = - (i.position - ref_pt_a.position).head<3>(); + Eigen::Vector3f point_vec3 = (i.position - ref_pt_a.position).head<3>(); md.vertex_index = i.vertex_index; - md.distance = - dist_3d(i.position, ref_pt_a.position) / normScale; - if (i.position.head<3>().dot( - Eigen::Vector3f(0.0, 0.0, 1.0f)) < 0) { + md.distance = dist_3d(i.position, ref_pt_a.position) / normScale; + if (i.position.head<3>().dot(Eigen::Vector3f(0.0, 0.0, 1.0f)) < 0) { md.distance *= -1; } - Eigen::Vector3f plane_norm = - ref_vec3.cross(point_vec3).normalized(); + Eigen::Vector3f plane_norm = ref_vec3.cross(point_vec3).normalized(); if (ref_pt_a.position != i.position) { if (plane_norm.normalized().z() > 0) { - md.angle = - -1 * - acos( - (point_vec3) - .normalized() - .dot( - ref_vec3.normalized())); + md.angle = -1 * acos((point_vec3).normalized().dot(ref_vec3.normalized())); } else { - md.angle = - acos(point_vec3.normalized().dot( - ref_vec3.normalized())); + md.angle = acos(point_vec3.normalized().dot(ref_vec3.normalized())); } } else { md.angle = 0.0f; @@ -1341,12 +1241,11 @@ do_view(TrackerPSVR &t, View &view, cv::Mat &grey, cv::Mat &rgb) // Debug is wanted, draw the keypoints. if (rgb.cols > 0) { - cv::drawKeypoints( - view.frame_undist_rectified, // image - view.keypoints, // keypoints - rgb, // outImage - cv::Scalar(255, 0, 0), // color - cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); // flags + cv::drawKeypoints(view.frame_undist_rectified, // image + view.keypoints, // keypoints + rgb, // outImage + cv::Scalar(255, 0, 0), // color + cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); // flags } } @@ -1363,10 +1262,7 @@ typedef struct blob_data static void -sample_line(cv::Mat &src, - cv::Point2i start, - cv::Point2i end, - int *inside_length) +sample_line(cv::Mat &src, cv::Point2i start, cv::Point2i end, int *inside_length) { // use bresenhams algorithm to sample the // pixels between two points in an image @@ -1424,22 +1320,18 @@ blob_intersections(cv::Mat &src, cv::KeyPoint *kp, struct blob_data *bd) // to the others int radius = kp->size / 2; - cv::Rect2i sq_b(kp->pt.x - radius, kp->pt.y - radius, kp->size, - kp->size); + cv::Rect2i sq_b(kp->pt.x - radius, kp->pt.y - radius, kp->size, kp->size); - sample_line(src, cv::Point2i(sq_b.x, sq_b.y), - cv::Point2i(sq_b.x + sq_b.width, sq_b.y + sq_b.height), + sample_line(src, cv::Point2i(sq_b.x, sq_b.y), cv::Point2i(sq_b.x + sq_b.width, sq_b.y + sq_b.height), &bd->tl_to_br); - sample_line(src, cv::Point2i(sq_b.x, sq_b.y + sq_b.height), - cv::Point2i(sq_b.x + sq_b.width, sq_b.y), &bd->bl_to_tr); + sample_line(src, cv::Point2i(sq_b.x, sq_b.y + sq_b.height), cv::Point2i(sq_b.x + sq_b.width, sq_b.y), + &bd->bl_to_tr); sample_line(src, cv::Point2i(sq_b.x, sq_b.y + sq_b.height / 2), - cv::Point2i(sq_b.x + sq_b.width, sq_b.y + sq_b.height / 2), - &bd->tc_to_bc); + cv::Point2i(sq_b.x + sq_b.width, sq_b.y + sq_b.height / 2), &bd->tc_to_bc); sample_line(src, cv::Point2i(sq_b.x + sq_b.width / 2, sq_b.y), - cv::Point2i(sq_b.x + sq_b.width / 2, sq_b.y + sq_b.height), - &bd->lc_to_rc); + cv::Point2i(sq_b.x + sq_b.width / 2, sq_b.y + sq_b.height), &bd->lc_to_rc); bd->diff_a = bd->tl_to_br - bd->bl_to_tr; bd->diff_b = bd->tc_to_bc - bd->lc_to_rc; @@ -1499,8 +1391,7 @@ tag_points(TrackerPSVR &t, std::vector *blob_datas) int side_count = 0; if (channel_a_total > channel_b_total) { // use channel a - float channel_dev = - (channel_a_total / float(blob_datas->size())) / 2.0f; + float channel_dev = (channel_a_total / float(blob_datas->size())) / 2.0f; int usable_count = 0; for (uint32_t i = 0; i < blob_datas->size(); i++) { @@ -1531,28 +1422,18 @@ tag_points(TrackerPSVR &t, std::vector *blob_datas) // FRONT and all the // negative ones with // SIDE - if (blob_datas->at(i).diff_a >= - 0) { - t.world_points[i] - .btype = - BLOB_TYPE_FRONT; + if (blob_datas->at(i).diff_a >= 0) { + t.world_points[i].btype = BLOB_TYPE_FRONT; } else { - t.world_points[i] - .btype = - BLOB_TYPE_SIDE; + t.world_points[i].btype = BLOB_TYPE_SIDE; side_count++; } } else { - if (blob_datas->at(i).diff_a < - 0) { - t.world_points[i] - .btype = - BLOB_TYPE_FRONT; + if (blob_datas->at(i).diff_a < 0) { + t.world_points[i].btype = BLOB_TYPE_FRONT; } else { - t.world_points[i] - .btype = - BLOB_TYPE_SIDE; + t.world_points[i].btype = BLOB_TYPE_SIDE; side_count++; } } @@ -1561,8 +1442,7 @@ tag_points(TrackerPSVR &t, std::vector *blob_datas) } } else { // use channel b - float channel_dev = - (channel_b_total / float(blob_datas->size())) / 2.0f; + float channel_dev = (channel_b_total / float(blob_datas->size())) / 2.0f; int usable_count = 0; for (uint32_t i = 0; i < blob_datas->size(); i++) { if (abs(blob_datas->at(i).diff_b) > channel_dev) { @@ -1592,21 +1472,17 @@ tag_points(TrackerPSVR &t, std::vector *blob_datas) // FRONT and all the egative ones with // SIDE if (blob_datas->at(i).diff_b >= 0) { - t.world_points[i].btype = - BLOB_TYPE_FRONT; + t.world_points[i].btype = BLOB_TYPE_FRONT; } else { - t.world_points[i].btype = - BLOB_TYPE_SIDE; + t.world_points[i].btype = BLOB_TYPE_SIDE; side_count++; } } else { if (blob_datas->at(i).diff_b < 0) { - t.world_points[i].btype = - BLOB_TYPE_FRONT; + t.world_points[i].btype = BLOB_TYPE_FRONT; } else { - t.world_points[i].btype = - BLOB_TYPE_SIDE; + t.world_points[i].btype = BLOB_TYPE_SIDE; side_count++; } } @@ -1685,8 +1561,7 @@ process(TrackerPSVR &t, struct xrt_frame *xf) // find closest point on same-ish scanline float xdiff = r_blob.pt.x - l_blob.pt.x; float ydiff = r_blob.pt.y - l_blob.pt.y; - if ((ydiff < 3.0f) && (ydiff > -3.0f) && - (abs(xdiff) < lowest_dist)) { + if ((ydiff < 3.0f) && (ydiff > -3.0f) && (abs(xdiff) < lowest_dist)) { lowest_dist = abs(xdiff); r_index = j; l_index = i; @@ -1710,18 +1585,15 @@ process(TrackerPSVR &t, struct xrt_frame *xf) if (t.l_blobs.size() > 0) { for (uint32_t i = 0; i < t.l_blobs.size(); i++) { float disp = t.r_blobs[i].pt.x - t.l_blobs[i].pt.x; - cv::Vec4d xydw(t.l_blobs[i].pt.x, t.l_blobs[i].pt.y, - disp, 1.0f); + cv::Vec4d xydw(t.l_blobs[i].pt.x, t.l_blobs[i].pt.y, disp, 1.0f); // Transform - cv::Vec4d h_world = - (cv::Matx44d)t.disparity_to_depth * xydw; + cv::Vec4d h_world = (cv::Matx44d)t.disparity_to_depth * xydw; // Divide by scale to get 3D vector from // homogeneous coordinate. we also invert x here blob_point_t bp; - bp.p = cv::Point3f(-h_world[0] / h_world[3], - h_world[1] / h_world[3], - (h_world[2] / h_world[3])); + bp.p = + cv::Point3f(-h_world[0] / h_world[3], h_world[1] / h_world[3], (h_world[2] / h_world[3])); bp.lkp = t.l_blobs[i]; bp.rkp = t.r_blobs[i]; bp.btype = BLOB_TYPE_UNKNOWN; @@ -1730,8 +1602,7 @@ process(TrackerPSVR &t, struct xrt_frame *xf) // compute the shape data for each blob blob_data_t intersections; - blob_intersections(t.view[0].frame_undist_rectified, - &bp.lkp, &intersections); + blob_intersections(t.view[0].frame_undist_rectified, &bp.lkp, &intersections); blob_datas.push_back(intersections); } } @@ -1748,24 +1619,20 @@ process(TrackerPSVR &t, struct xrt_frame *xf) // remove any points that are too close to be // treated as separate leds - merge_close_points(&t.pruned_points, &t.merged_points, - PSVR_MERGE_THRESH); + merge_close_points(&t.pruned_points, &t.merged_points, PSVR_MERGE_THRESH); // uncomment to debug 'overpruning' or other issues // that may be related to calibration scale - PSVR_INFO("world points: %d pruned points: %d merged points %d", - (uint32_t)t.world_points.size(), - (uint32_t)t.pruned_points.size(), - (uint32_t)t.merged_points.size()); + PSVR_INFO("world points: %d pruned points: %d merged points %d", (uint32_t)t.world_points.size(), + (uint32_t)t.pruned_points.size(), (uint32_t)t.merged_points.size()); // put our blob positions in a slightly more // useful data structure if (t.merged_points.size() > PSVR_NUM_LEDS) { - PSVR_INFO("Too many blobs to be a PSVR! %d", - (uint32_t)t.merged_points.size()); + PSVR_INFO("Too many blobs to be a PSVR! %d", (uint32_t)t.merged_points.size()); } else { // convert our points to match data, // this tags our match_vertices with @@ -1781,8 +1648,7 @@ process(TrackerPSVR &t, struct xrt_frame *xf) cv::Point3f unscaled = t.merged_points.at(i).p; - fprintf(t.dump_file, "P,%" PRIu64 ",%f,%f,%f\n", - xf->source_sequence, unscaled.x, unscaled.y, + fprintf(t.dump_file, "P,%" PRIu64 ",%f,%f,%f\n", xf->source_sequence, unscaled.x, unscaled.y, unscaled.z); } fprintf(t.dump_file, "\n"); @@ -1796,8 +1662,7 @@ process(TrackerPSVR &t, struct xrt_frame *xf) // in world space, and model_center_transform will // contain the pose matrix std::vector solved; - Eigen::Matrix4f model_center_transform = - disambiguate(t, &t.match_vertices, &predicted_pose, &solved, 0); + Eigen::Matrix4f model_center_transform = disambiguate(t, &t.match_vertices, &predicted_pose, &solved, 0); // derive our optical rotation correction from the @@ -1811,13 +1676,9 @@ process(TrackerPSVR &t, struct xrt_frame *xf) // leds. if (t.merged_points.size() >= PSVR_OPTICAL_SOLVE_THRESH) { Eigen::Quaternionf correction = - rot * Eigen::Quaternionf(t.fusion.rot.w, t.fusion.rot.x, - t.fusion.rot.y, t.fusion.rot.z) - .inverse(); + rot * Eigen::Quaternionf(t.fusion.rot.w, t.fusion.rot.x, t.fusion.rot.y, t.fusion.rot.z).inverse(); - float correction_magnitude = - t.target_optical_rotation_correction.angularDistance( - correction); + float correction_magnitude = t.target_optical_rotation_correction.angularDistance(correction); // for corrections subsequent to the // first, we never want to depart @@ -1828,15 +1689,11 @@ process(TrackerPSVR &t, struct xrt_frame *xf) // uncomment to debug rotation correction convergence // issues - PSVR_TRACE("Q1: %f %f %f %f Q2: %f %f %f %f", - t.target_optical_rotation_correction.x(), - t.target_optical_rotation_correction.y(), - t.target_optical_rotation_correction.z(), - t.target_optical_rotation_correction.w(), - correction.x(), correction.y(), correction.z(), + PSVR_TRACE("Q1: %f %f %f %f Q2: %f %f %f %f", t.target_optical_rotation_correction.x(), + t.target_optical_rotation_correction.y(), t.target_optical_rotation_correction.z(), + t.target_optical_rotation_correction.w(), correction.x(), correction.y(), correction.z(), correction.w()); - PSVR_TRACE("correction mag: %f avg %f", correction_magnitude, - t.avg_optical_correction); + PSVR_TRACE("correction mag: %f avg %f", correction_magnitude, t.avg_optical_correction); // keep a running average of the last 10 corrections - // so we can apply the correction only when we are @@ -1870,8 +1727,7 @@ process(TrackerPSVR &t, struct xrt_frame *xf) if (t.bad_correction_count > PSVR_MAX_BAD_CORR) { t.max_correction = PSVR_SLOW_CORRECTION; t.target_optical_rotation_correction = - t.target_optical_rotation_correction.slerp( - t.max_correction, correction); + t.target_optical_rotation_correction.slerp(t.max_correction, correction); t.bad_correction_count = 0; PSVR_INFO("TOO MANY BAD CORRECTIONS. DRIFTED?"); } @@ -1881,22 +1737,20 @@ process(TrackerPSVR &t, struct xrt_frame *xf) resolved.push_back(solved[i]); } solved.clear(); - model_center_transform = solve_with_imu( - t, &resolved, &predicted_pose, &solved, PSVR_SEARCH_RADIUS); + model_center_transform = solve_with_imu(t, &resolved, &predicted_pose, &solved, PSVR_SEARCH_RADIUS); } // move our applied correction towards the // target correction, rather than applying it // immediately to smooth things out. - t.optical_rotation_correction = t.optical_rotation_correction.slerp( - t.max_correction, t.target_optical_rotation_correction); + t.optical_rotation_correction = + t.optical_rotation_correction.slerp(t.max_correction, t.target_optical_rotation_correction); #ifdef PSVR_DUMP_FOR_OFFLINE_ANALYSIS fprintf(t.dump_file, "\n"); for (uint32_t i = 0; i < solved.size(); i++) { - fprintf(t.dump_file, "S,%" PRIu64 ",%f,%f,%f\n", - xf->source_sequence, solved[i].position.x(), + fprintf(t.dump_file, "S,%" PRIu64 ",%f,%f,%f\n", xf->source_sequence, solved[i].position.x(), solved[i].position.y(), solved[i].position.z()); } fprintf(t.dump_file, "\n"); @@ -1986,9 +1840,7 @@ run(TrackerPSVR &t) } static void -get_pose(TrackerPSVR &t, - timepoint_ns when_ns, - struct xrt_space_relation *out_relation) +get_pose(TrackerPSVR &t, timepoint_ns when_ns, struct xrt_space_relation *out_relation) { os_thread_helper_lock(&t.oth); @@ -2004,18 +1856,14 @@ get_pose(TrackerPSVR &t, //! @todo assuming that orientation is actually //! currently tracked. out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT | - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + XRT_SPACE_RELATION_POSITION_VALID_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT | + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); os_thread_helper_unlock(&t.oth); } static void -imu_data(TrackerPSVR &t, - timepoint_ns timestamp_ns, - struct xrt_tracking_sample *sample) +imu_data(TrackerPSVR &t, timepoint_ns timestamp_ns, struct xrt_tracking_sample *sample) { os_thread_helper_lock(&t.oth); @@ -2028,8 +1876,7 @@ imu_data(TrackerPSVR &t, time_duration_ns delta_ns = timestamp_ns - t.last_imu; float dt = time_ns_to_s(delta_ns); // Super simple fusion. - math_quat_integrate_velocity( - &t.fusion.rot, &sample->gyro_rad_secs, dt, &t.fusion.rot); + math_quat_integrate_velocity(&t.fusion.rot, &sample->gyro_rad_secs, dt, &t.fusion.rot); } // apply our optical correction to imu rotation @@ -2037,8 +1884,7 @@ imu_data(TrackerPSVR &t, Eigen::Quaternionf corrected_rot_q = t.optical_rotation_correction * - Eigen::Quaternionf(t.fusion.rot.w, t.fusion.rot.x, t.fusion.rot.y, - t.fusion.rot.z); + Eigen::Quaternionf(t.fusion.rot.w, t.fusion.rot.x, t.fusion.rot.y, t.fusion.rot.z); Eigen::Matrix4f corrected_rot = Eigen::Matrix4f::Identity(); corrected_rot.block(0, 0, 3, 3) = corrected_rot_q.toRotationMatrix(); @@ -2057,12 +1903,11 @@ imu_data(TrackerPSVR &t, t.last_imu = timestamp_ns; #ifdef PSVR_DUMP_IMU_FOR_OFFLINE_ANALYSIS - fprintf(t.dump_file, "I,%" PRIu64 ", %f,%f,%f,%f\n\n", timestamp_ns, - t.fusion.rot.x, t.fusion.rot.y, t.fusion.rot.z, t.fusion.rot.w); + fprintf(t.dump_file, "I,%" PRIu64 ", %f,%f,%f,%f\n\n", timestamp_ns, t.fusion.rot.x, t.fusion.rot.y, + t.fusion.rot.z, t.fusion.rot.w); - fprintf(t.dump_file, "C,%" PRIu64 ", %f,%f,%f,%f\n\n", timestamp_ns, - corrected_rot_q.x(), corrected_rot_q.y(), corrected_rot_q.z(), - corrected_rot_q.w()); + fprintf(t.dump_file, "C,%" PRIu64 ", %f,%f,%f,%f\n\n", timestamp_ns, corrected_rot_q.x(), corrected_rot_q.y(), + corrected_rot_q.z(), corrected_rot_q.w()); #endif @@ -2102,18 +1947,14 @@ break_apart(TrackerPSVR &t) */ extern "C" void -t_psvr_push_imu(struct xrt_tracked_psvr *xtvr, - timepoint_ns timestamp_ns, - struct xrt_tracking_sample *sample) +t_psvr_push_imu(struct xrt_tracked_psvr *xtvr, timepoint_ns timestamp_ns, struct xrt_tracking_sample *sample) { auto &t = *container_of(xtvr, TrackerPSVR, base); imu_data(t, timestamp_ns, sample); } extern "C" void -t_psvr_get_tracked_pose(struct xrt_tracked_psvr *xtvr, - timepoint_ns when_ns, - struct xrt_space_relation *out_relation) +t_psvr_get_tracked_pose(struct xrt_tracked_psvr *xtvr, timepoint_ns when_ns, struct xrt_space_relation *out_relation) { auto &t = *container_of(xtvr, TrackerPSVR, base); get_pose(t, when_ns, out_relation); @@ -2194,12 +2035,10 @@ t_psvr_create(struct xrt_frame_context *xfctx, int ret; for (uint32_t i = 0; i < PSVR_NUM_LEDS; i++) { - init_filter(t.track_filters[i], PSVR_BLOB_PROCESS_NOISE, - PSVR_BLOB_MEASUREMENT_NOISE, 1.0f); + init_filter(t.track_filters[i], PSVR_BLOB_PROCESS_NOISE, PSVR_BLOB_MEASUREMENT_NOISE, 1.0f); } - init_filter(t.pose_filter, PSVR_POSE_PROCESS_NOISE, - PSVR_POSE_MEASUREMENT_NOISE, 1.0f); + init_filter(t.pose_filter, PSVR_POSE_PROCESS_NOISE, PSVR_POSE_MEASUREMENT_NOISE, 1.0f); StereoRectificationMaps rectify(data); t.view[0].populate_from_calib(data->view[0], rectify.view[0].rectify); @@ -2230,10 +2069,8 @@ t_psvr_create(struct xrt_frame_context *xfctx, t.sbd = cv::SimpleBlobDetector::create(blob_params); - t.target_optical_rotation_correction = - Eigen::Quaternionf(1.0f, 0.0f, 0.0f, 0.0f); - t.optical_rotation_correction = - Eigen::Quaternionf(1.0f, 0.0f, 0.0f, 0.0f); + t.target_optical_rotation_correction = Eigen::Quaternionf(1.0f, 0.0f, 0.0f, 0.0f); + t.optical_rotation_correction = Eigen::Quaternionf(1.0f, 0.0f, 0.0f, 0.0f); t.axis_align_rot = Eigen::Quaternionf(1.0f, 0.0f, 0.0f, 0.0f); t.corrected_imu_rotation = Eigen::Matrix4f().Identity(); t.avg_optical_correction = 10.0f; // initialise to a high value, so we @@ -2241,10 +2078,8 @@ t_psvr_create(struct xrt_frame_context *xfctx, t.max_correction = PSVR_FAST_CORRECTION; t.bad_correction_count = 0; - Eigen::Quaternionf align(Eigen::AngleAxis( - -M_PI / 2, Eigen::Vector3f(0.0f, 0.0f, 1.0f))); - Eigen::Quaternionf align2( - Eigen::AngleAxis(M_PI, Eigen::Vector3f(0.0f, 1.0f, 0.0f))); + Eigen::Quaternionf align(Eigen::AngleAxis(-M_PI / 2, Eigen::Vector3f(0.0f, 0.0f, 1.0f))); + Eigen::Quaternionf align2(Eigen::AngleAxis(M_PI, Eigen::Vector3f(0.0f, 1.0f, 0.0f))); t.axis_align_rot = align2; // * align; diff --git a/src/xrt/auxiliary/tracking/t_tracking.h b/src/xrt/auxiliary/tracking/t_tracking.h index 5f67cfa47..8f621fdec 100644 --- a/src/xrt/auxiliary/tracking/t_tracking.h +++ b/src/xrt/auxiliary/tracking/t_tracking.h @@ -156,8 +156,7 @@ t_stereo_camera_calibration_destroy(struct t_stereo_camera_calibration *c); * @relates t_stereo_camera_calibration */ static inline void -t_stereo_camera_calibration_reference(struct t_stereo_camera_calibration **dst, - struct t_stereo_camera_calibration *src) +t_stereo_camera_calibration_reference(struct t_stereo_camera_calibration **dst, struct t_stereo_camera_calibration *src) { struct t_stereo_camera_calibration *old_dst = *dst; @@ -182,15 +181,13 @@ t_stereo_camera_calibration_reference(struct t_stereo_camera_calibration **dst, * Load stereo calibration data from a given file. */ bool -t_stereo_camera_calibration_load_v1( - FILE *calib_file, struct t_stereo_camera_calibration **out_data); +t_stereo_camera_calibration_load_v1(FILE *calib_file, struct t_stereo_camera_calibration **out_data); /*! * Save the given stereo calibration data to the given file. */ bool -t_stereo_camera_calibration_save_v1(FILE *calib_file, - struct t_stereo_camera_calibration *data); +t_stereo_camera_calibration_save_v1(FILE *calib_file, struct t_stereo_camera_calibration *data); /* @@ -217,22 +214,13 @@ void t_convert_make_h8s8v8_to_r8g8b8(struct t_convert_table *t); void -t_convert_in_place_y8u8v8_to_r8g8b8(uint32_t width, - uint32_t height, - size_t stride, - void *data_ptr); +t_convert_in_place_y8u8v8_to_r8g8b8(uint32_t width, uint32_t height, size_t stride, void *data_ptr); void -t_convert_in_place_y8u8v8_to_h8s8v8(uint32_t width, - uint32_t height, - size_t stride, - void *data_ptr); +t_convert_in_place_y8u8v8_to_h8s8v8(uint32_t width, uint32_t height, size_t stride, void *data_ptr); void -t_convert_in_place_h8s8v8_to_r8g8b8(uint32_t width, - uint32_t height, - size_t stride, - void *data_ptr); +t_convert_in_place_h8s8v8_to_r8g8b8(uint32_t width, uint32_t height, size_t stride, void *data_ptr); /* @@ -244,14 +232,14 @@ t_convert_in_place_h8s8v8_to_r8g8b8(uint32_t width, #define T_HSV_SIZE 32 #define T_HSV_STEP (256 / T_HSV_SIZE) -#define T_HSV_DEFAULT_PARAMS() \ - { \ - { \ - {165, 30, 160, 100}, \ - {135, 30, 160, 100}, \ - {95, 30, 160, 100}, \ - }, \ - {128, 80}, \ +#define T_HSV_DEFAULT_PARAMS() \ + { \ + { \ + {165, 30, 160, 100}, \ + {135, 30, 160, 100}, \ + {95, 30, 160, 100}, \ + }, \ + {128, 80}, \ } struct t_hsv_filter_color @@ -290,22 +278,16 @@ struct t_hsv_filter_optimized_table }; void -t_hsv_build_convert_table(struct t_hsv_filter_params *params, - struct t_convert_table *t); +t_hsv_build_convert_table(struct t_hsv_filter_params *params, struct t_convert_table *t); void -t_hsv_build_large_table(struct t_hsv_filter_params *params, - struct t_hsv_filter_large_table *t); +t_hsv_build_large_table(struct t_hsv_filter_params *params, struct t_hsv_filter_large_table *t); void -t_hsv_build_optimized_table(struct t_hsv_filter_params *params, - struct t_hsv_filter_optimized_table *t); +t_hsv_build_optimized_table(struct t_hsv_filter_params *params, struct t_hsv_filter_optimized_table *t); static inline uint8_t -t_hsv_filter_sample(struct t_hsv_filter_optimized_table *t, - uint32_t y, - uint32_t u, - uint32_t v) +t_hsv_filter_sample(struct t_hsv_filter_optimized_table *t, uint32_t y, uint32_t u, uint32_t v) { return t->v[y / T_HSV_STEP][u / T_HSV_STEP][v / T_HSV_STEP]; } @@ -538,8 +520,7 @@ t_calibration_stereo_create(struct xrt_frame_context *xfctx, * @relates xrt_frame_context */ int -t_convert_yuv_or_yuyv_create(struct xrt_frame_sink *next, - struct xrt_frame_sink **out_sink); +t_convert_yuv_or_yuyv_create(struct xrt_frame_sink *next, struct xrt_frame_sink **out_sink); diff --git a/src/xrt/auxiliary/util/u_debug.c b/src/xrt/auxiliary/util/u_debug.c index 36b31a9bb..a1493ed3c 100644 --- a/src/xrt/auxiliary/util/u_debug.c +++ b/src/xrt/auxiliary/util/u_debug.c @@ -84,8 +84,7 @@ debug_get_bool_option(const char *name, bool _default) } if (debug_get_bool_option_print()) { - U_LOG_RAW("%s=%s (%s)", name, ret ? "TRUE" : "FALSE", - raw == NULL ? "nil" : raw); + U_LOG_RAW("%s=%s (%s)", name, ret ? "TRUE" : "FALSE", raw == NULL ? "nil" : raw); } return ret; @@ -201,8 +200,7 @@ debug_get_log_option(const char *name, enum u_logging_level _default) } if (debug_get_bool_option_print()) { - U_LOG_RAW("%s=%s (%s)", name, level_to_str(ret), - raw == NULL ? "nil" : raw); + U_LOG_RAW("%s=%s (%s)", name, level_to_str(ret), raw == NULL ? "nil" : raw); } return ret; diff --git a/src/xrt/auxiliary/util/u_debug.h b/src/xrt/auxiliary/util/u_debug.h index ed12a7fa1..0db7578b8 100644 --- a/src/xrt/auxiliary/util/u_debug.h +++ b/src/xrt/auxiliary/util/u_debug.h @@ -35,64 +35,64 @@ debug_get_float_option(const char *name, float _default); enum u_logging_level debug_get_log_option(const char *name, enum u_logging_level _default); -#define DEBUG_GET_ONCE_OPTION(suffix, name, _default) \ - static const char *debug_get_option_##suffix() \ - { \ - static bool gotten = false; \ - static const char *stored; \ - if (!gotten) { \ - gotten = true; \ - stored = debug_get_option(name, _default); \ - } \ - return stored; \ +#define DEBUG_GET_ONCE_OPTION(suffix, name, _default) \ + static const char *debug_get_option_##suffix() \ + { \ + static bool gotten = false; \ + static const char *stored; \ + if (!gotten) { \ + gotten = true; \ + stored = debug_get_option(name, _default); \ + } \ + return stored; \ } -#define DEBUG_GET_ONCE_BOOL_OPTION(suffix, name, _default) \ - static bool debug_get_bool_option_##suffix() \ - { \ - static bool gotten = false; \ - static bool stored; \ - if (!gotten) { \ - gotten = true; \ - stored = debug_get_bool_option(name, _default); \ - } \ - return stored; \ +#define DEBUG_GET_ONCE_BOOL_OPTION(suffix, name, _default) \ + static bool debug_get_bool_option_##suffix() \ + { \ + static bool gotten = false; \ + static bool stored; \ + if (!gotten) { \ + gotten = true; \ + stored = debug_get_bool_option(name, _default); \ + } \ + return stored; \ } -#define DEBUG_GET_ONCE_NUM_OPTION(suffix, name, _default) \ - static long debug_get_num_option_##suffix() \ - { \ - static long gotten = false; \ - static long stored; \ - if (!gotten) { \ - gotten = true; \ - stored = debug_get_num_option(name, _default); \ - } \ - return stored; \ +#define DEBUG_GET_ONCE_NUM_OPTION(suffix, name, _default) \ + static long debug_get_num_option_##suffix() \ + { \ + static long gotten = false; \ + static long stored; \ + if (!gotten) { \ + gotten = true; \ + stored = debug_get_num_option(name, _default); \ + } \ + return stored; \ } -#define DEBUG_GET_ONCE_FLOAT_OPTION(suffix, name, _default) \ - static float debug_get_float_option_##suffix() \ - { \ - static long gotten = false; \ - static float stored; \ - if (!gotten) { \ - gotten = true; \ - stored = debug_get_float_option(name, _default); \ - } \ - return stored; \ +#define DEBUG_GET_ONCE_FLOAT_OPTION(suffix, name, _default) \ + static float debug_get_float_option_##suffix() \ + { \ + static long gotten = false; \ + static float stored; \ + if (!gotten) { \ + gotten = true; \ + stored = debug_get_float_option(name, _default); \ + } \ + return stored; \ } -#define DEBUG_GET_ONCE_LOG_OPTION(suffix, name, _default) \ - static enum u_logging_level debug_get_log_option_##suffix() \ - { \ - static long gotten = false; \ - static enum u_logging_level stored; \ - if (!gotten) { \ - gotten = true; \ - stored = debug_get_log_option(name, _default); \ - } \ - return stored; \ +#define DEBUG_GET_ONCE_LOG_OPTION(suffix, name, _default) \ + static enum u_logging_level debug_get_log_option_##suffix() \ + { \ + static long gotten = false; \ + static enum u_logging_level stored; \ + if (!gotten) { \ + gotten = true; \ + stored = debug_get_log_option(name, _default); \ + } \ + return stored; \ } #ifdef __cplusplus diff --git a/src/xrt/auxiliary/util/u_device.c b/src/xrt/auxiliary/util/u_device.c index 60036d511..27d131c2c 100644 --- a/src/xrt/auxiliary/util/u_device.c +++ b/src/xrt/auxiliary/util/u_device.c @@ -70,24 +70,18 @@ const struct xrt_matrix_2x2 u_device_rotation_180 = {{ #define PRINT_INT(name, val) U_LOG_RAW("\t%s = %u", name, val) -#define PRINT_MM(name, val) \ - U_LOG_RAW("\t%s = %f (%i.%02imm)", name, val, (int32_t)(val * 1000.f), \ - abs((int32_t)(val * 100000.f)) % 100) +#define PRINT_MM(name, val) \ + U_LOG_RAW("\t%s = %f (%i.%02imm)", name, val, (int32_t)(val * 1000.f), abs((int32_t)(val * 100000.f)) % 100) -#define PRINT_ANGLE(name, val) \ - U_LOG_RAW("\t%s = %f (%i°)", name, val, (int32_t)(val * (180 / M_PI))) +#define PRINT_ANGLE(name, val) U_LOG_RAW("\t%s = %f (%i°)", name, val, (int32_t)(val * (180 / M_PI))) -#define PRINT_MAT2X2(name, rot) \ - U_LOG_RAW("\t%s = {%f, %f} {%f, %f}", name, rot.v[0], rot.v[1], \ - rot.v[2], rot.v[3]) +#define PRINT_MAT2X2(name, rot) U_LOG_RAW("\t%s = {%f, %f} {%f, %f}", name, rot.v[0], rot.v[1], rot.v[2], rot.v[3]) /*! * Dump the device config to stderr. */ void -u_device_dump_config(struct xrt_device *xdev, - const char *prefix, - const char *prod) +u_device_dump_config(struct xrt_device *xdev, const char *prefix, const char *prod) { // clang-format off U_LOG_RAW("%s - device_setup", prefix); @@ -137,8 +131,7 @@ u_device_dump_config(struct xrt_device *xdev, */ bool -u_device_setup_split_side_by_side(struct xrt_device *xdev, - const struct u_device_simple_info *info) +u_device_setup_split_side_by_side(struct xrt_device *xdev, const struct u_device_simple_info *info) { uint32_t w_pixels = info->display.w_pixels / 2; uint32_t h_pixels = info->display.h_pixels; @@ -188,34 +181,25 @@ u_device_setup_split_side_by_side(struct xrt_device *xdev, { /* right eye */ - if (!math_compute_fovs(w_meters, lens_center_x_meters[1], - info->views[1].fov, h_meters, - lens_center_y_meters[1], 0, - &xdev->hmd->views[1].fov)) { + if (!math_compute_fovs(w_meters, lens_center_x_meters[1], info->views[1].fov, h_meters, + lens_center_y_meters[1], 0, &xdev->hmd->views[1].fov)) { return false; } } { /* left eye - just mirroring right eye now */ - xdev->hmd->views[0].fov.angle_up = - xdev->hmd->views[1].fov.angle_up; - xdev->hmd->views[0].fov.angle_down = - xdev->hmd->views[1].fov.angle_down; - - xdev->hmd->views[0].fov.angle_left = - -xdev->hmd->views[1].fov.angle_right; - xdev->hmd->views[0].fov.angle_right = - -xdev->hmd->views[1].fov.angle_left; + xdev->hmd->views[0].fov.angle_up = xdev->hmd->views[1].fov.angle_up; + xdev->hmd->views[0].fov.angle_down = xdev->hmd->views[1].fov.angle_down; + + xdev->hmd->views[0].fov.angle_left = -xdev->hmd->views[1].fov.angle_right; + xdev->hmd->views[0].fov.angle_right = -xdev->hmd->views[1].fov.angle_left; } return true; } void * -u_device_allocate(enum u_device_alloc_flags flags, - size_t size, - size_t num_inputs, - size_t num_outputs) +u_device_allocate(enum u_device_alloc_flags flags, size_t size, size_t num_inputs, size_t num_outputs) { bool alloc_hmd = (flags & U_DEVICE_ALLOC_HMD) != 0; bool alloc_tracking = (flags & U_DEVICE_ALLOC_TRACKING_NONE) != 0; @@ -262,12 +246,10 @@ u_device_allocate(enum u_device_alloc_flags flags, } if (alloc_tracking) { - xdev->tracking_origin = - (struct xrt_tracking_origin *)(ptr + offset_tracking); + xdev->tracking_origin = (struct xrt_tracking_origin *)(ptr + offset_tracking); xdev->tracking_origin->type = XRT_TRACKING_TYPE_NONE; xdev->tracking_origin->offset.orientation.w = 1.0f; - snprintf(xdev->tracking_origin->name, XRT_TRACKING_NAME_LEN, - "%s", "No tracking"); + snprintf(xdev->tracking_origin->name, XRT_TRACKING_NAME_LEN, "%s", "No tracking"); } return xdev; @@ -295,8 +277,7 @@ u_device_free(struct xrt_device *xdev) static void try_move_assignment(struct xrt_device **xdevs, int *hand, int *other_hand) { - if (*hand != XRT_DEVICE_ROLE_UNASSIGNED && - xdevs[*hand]->device_type == XRT_DEVICE_TYPE_ANY_HAND_CONTROLLER && + if (*hand != XRT_DEVICE_ROLE_UNASSIGNED && xdevs[*hand]->device_type == XRT_DEVICE_TYPE_ANY_HAND_CONTROLLER && *other_hand == XRT_DEVICE_ROLE_UNASSIGNED) { *other_hand = *hand; @@ -305,11 +286,7 @@ try_move_assignment(struct xrt_device **xdevs, int *hand, int *other_hand) } void -u_device_assign_xdev_roles(struct xrt_device **xdevs, - size_t num_xdevs, - int *head, - int *left, - int *right) +u_device_assign_xdev_roles(struct xrt_device **xdevs, size_t num_xdevs, int *head, int *left, int *right) { *head = XRT_DEVICE_ROLE_UNASSIGNED; *left = XRT_DEVICE_ROLE_UNASSIGNED; @@ -389,38 +366,29 @@ u_device_setup_tracking_origins(struct xrt_device *head, head->tracking_origin->offset.position.z = 0.0f; } - if (left != NULL && - left->tracking_origin->type == XRT_TRACKING_TYPE_NONE) { + if (left != NULL && left->tracking_origin->type == XRT_TRACKING_TYPE_NONE) { left->tracking_origin->offset.position.x = -0.2f; left->tracking_origin->offset.position.y = 1.3f; left->tracking_origin->offset.position.z = -0.5f; } - if (right != NULL && - right->tracking_origin->type == XRT_TRACKING_TYPE_NONE) { + if (right != NULL && right->tracking_origin->type == XRT_TRACKING_TYPE_NONE) { right->tracking_origin->offset.position.x = 0.2f; right->tracking_origin->offset.position.y = 1.3f; right->tracking_origin->offset.position.z = -0.5f; } - struct xrt_tracking_origin *head_origin = - head ? head->tracking_origin : NULL; - struct xrt_tracking_origin *left_origin = - left ? left->tracking_origin : NULL; - struct xrt_tracking_origin *right_origin = - right ? right->tracking_origin : NULL; + struct xrt_tracking_origin *head_origin = head ? head->tracking_origin : NULL; + struct xrt_tracking_origin *left_origin = left ? left->tracking_origin : NULL; + struct xrt_tracking_origin *right_origin = right ? right->tracking_origin : NULL; if (head_origin) { - apply_offset(&head_origin->offset.position, - global_tracking_origin_offset); + apply_offset(&head_origin->offset.position, global_tracking_origin_offset); } if (left_origin && left_origin != head_origin) { - apply_offset(&left->tracking_origin->offset.position, - global_tracking_origin_offset); + apply_offset(&left->tracking_origin->offset.position, global_tracking_origin_offset); } - if (right_origin && right_origin != head_origin && - right_origin != left_origin) { - apply_offset(&right->tracking_origin->offset.position, - global_tracking_origin_offset); + if (right_origin && right_origin != head_origin && right_origin != left_origin) { + apply_offset(&right->tracking_origin->offset.position, global_tracking_origin_offset); } } diff --git a/src/xrt/auxiliary/util/u_device.h b/src/xrt/auxiliary/util/u_device.h index c6bfabd6c..c3251dfc5 100644 --- a/src/xrt/auxiliary/util/u_device.h +++ b/src/xrt/auxiliary/util/u_device.h @@ -58,8 +58,7 @@ struct u_device_simple_info * @ingroup aux_util */ bool -u_device_setup_split_side_by_side(struct xrt_device *xdev, - const struct u_device_simple_info *info); +u_device_setup_split_side_by_side(struct xrt_device *xdev, const struct u_device_simple_info *info); /*! * Dump the device config to stderr. @@ -67,13 +66,10 @@ u_device_setup_split_side_by_side(struct xrt_device *xdev, * @ingroup aux_util */ void -u_device_dump_config(struct xrt_device *xdev, - const char *prefix, - const char *prod); +u_device_dump_config(struct xrt_device *xdev, const char *prefix, const char *prod); -#define U_DEVICE_ALLOCATE(type, flags, num_inputs, num_outputs) \ - ((type *)u_device_allocate(flags, sizeof(type), num_inputs, \ - num_outputs)) +#define U_DEVICE_ALLOCATE(type, flags, num_inputs, num_outputs) \ + ((type *)u_device_allocate(flags, sizeof(type), num_inputs, num_outputs)) /*! @@ -85,10 +81,7 @@ u_device_dump_config(struct xrt_device *xdev, * @ingroup aux_util */ void * -u_device_allocate(enum u_device_alloc_flags flags, - size_t size, - size_t num_inputs, - size_t num_outputs); +u_device_allocate(enum u_device_alloc_flags flags, size_t size, size_t num_inputs, size_t num_outputs); /*! * Helper function to free a device and any data hanging of it. @@ -107,11 +100,7 @@ u_device_free(struct xrt_device *xdev); * @ingroup aux_util */ void -u_device_assign_xdev_roles(struct xrt_device **xdevs, - size_t num_xdevs, - int *head, - int *left, - int *right); +u_device_assign_xdev_roles(struct xrt_device **xdevs, size_t num_xdevs, int *head, int *left, int *right); /*! * Helper function to assign head, left hand and right hand roles. diff --git a/src/xrt/auxiliary/util/u_distortion.c b/src/xrt/auxiliary/util/u_distortion.c index 3f14ea3f5..1d4790f28 100644 --- a/src/xrt/auxiliary/util/u_distortion.c +++ b/src/xrt/auxiliary/util/u_distortion.c @@ -17,10 +17,9 @@ void -u_distortion_cardboard_calculate( - const struct u_cardboard_distortion_arguments *args, - struct xrt_hmd_parts *parts, - struct u_cardboard_distortion *out_dist) +u_distortion_cardboard_calculate(const struct u_cardboard_distortion_arguments *args, + struct xrt_hmd_parts *parts, + struct u_cardboard_distortion *out_dist) { /* * HMD parts diff --git a/src/xrt/auxiliary/util/u_distortion.h b/src/xrt/auxiliary/util/u_distortion.h index 74c3d98aa..3ec32cb55 100644 --- a/src/xrt/auxiliary/util/u_distortion.h +++ b/src/xrt/auxiliary/util/u_distortion.h @@ -101,10 +101,9 @@ struct u_cardboard_distortion * @ingroup aux_distortion */ void -u_distortion_cardboard_calculate( - const struct u_cardboard_distortion_arguments *args, - struct xrt_hmd_parts *parts, - struct u_cardboard_distortion *out_dist); +u_distortion_cardboard_calculate(const struct u_cardboard_distortion_arguments *args, + struct xrt_hmd_parts *parts, + struct u_cardboard_distortion *out_dist); #ifdef __cplusplus diff --git a/src/xrt/auxiliary/util/u_distortion_mesh.c b/src/xrt/auxiliary/util/u_distortion_mesh.c index 3c16d917e..51dc57d62 100644 --- a/src/xrt/auxiliary/util/u_distortion_mesh.c +++ b/src/xrt/auxiliary/util/u_distortion_mesh.c @@ -22,11 +22,7 @@ DEBUG_GET_ONCE_NUM_OPTION(mesh_size, "XRT_MESH_SIZE", 64) -typedef bool (*func_calc)(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result); +typedef bool (*func_calc)(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result); static int index_for(int row, int col, int stride, int offset) @@ -35,11 +31,7 @@ index_for(int row, int col, int stride, int offset) } void -run_func(struct xrt_device *xdev, - func_calc calc, - int num_views, - struct xrt_hmd_parts *target, - size_t num) +run_func(struct xrt_device *xdev, func_calc calc, int num_views, struct xrt_hmd_parts *target, size_t num) { assert(calc != NULL); assert(num_views == 2); @@ -79,9 +71,7 @@ run_func(struct xrt_device *xdev, verts[i + 0] = u * 2.0 - 1.0; verts[i + 1] = v * 2.0 - 1.0; - if (!calc(xdev, view, u, v, - (struct xrt_uv_triplet - *)&verts[i + 2])) { + if (!calc(xdev, view, u, v, (struct xrt_uv_triplet *)&verts[i + 2])) { // bail on error, without updating // distortion.preferred return; @@ -109,14 +99,12 @@ run_func(struct xrt_device *xdev, for (int c = 0; c < vert_cols; c++) { indices[i++] = index_for(r, c, vert_cols, off); - indices[i++] = - index_for(r + 1, c, vert_cols, off); + indices[i++] = index_for(r + 1, c, vert_cols, off); } // Bottom vertex row for this cell row, right most // vertex. - indices[i++] = - index_for(r + 1, vert_cols - 1, vert_cols, off); + indices[i++] = index_for(r + 1, vert_cols - 1, vert_cols, off); } } @@ -134,16 +122,12 @@ run_func(struct xrt_device *xdev, } bool -u_compute_distortion_vive(struct u_vive_values *values, - float u, - float v, - struct xrt_uv_triplet *result) +u_compute_distortion_vive(struct u_vive_values *values, float u, float v, struct xrt_uv_triplet *result) { const struct u_vive_values val = *values; struct xrt_vec2 factor = {0.5 / (1.0 + val.grow_for_undistort), - val.aspect_x_over_y * 0.5 / - (1.0 + val.grow_for_undistort)}; + val.aspect_x_over_y * 0.5 / (1.0 + val.grow_for_undistort)}; struct xrt_vec2 texCoord = {2.0 * u - 1.0, 2.0 * v - 1.0}; @@ -155,27 +139,21 @@ u_compute_distortion_vive(struct u_vive_values *values, struct xrt_vec3 d_inv = { - (r2 * val.coefficients[2][0] + val.coefficients[1][0]) * r2 + - val.coefficients[0][0] * r2 + 1.0, - (r2 * val.coefficients[2][1] + val.coefficients[1][1]) * r2 + - val.coefficients[0][1] * r2 + 1.0, - (r2 * val.coefficients[2][2] + val.coefficients[1][2]) * r2 + - val.coefficients[0][2] * r2 + 1.0}; + (r2 * val.coefficients[2][0] + val.coefficients[1][0]) * r2 + val.coefficients[0][0] * r2 + 1.0, + (r2 * val.coefficients[2][1] + val.coefficients[1][1]) * r2 + val.coefficients[0][1] * r2 + 1.0, + (r2 * val.coefficients[2][2] + val.coefficients[1][2]) * r2 + val.coefficients[0][2] * r2 + 1.0}; struct xrt_vec3 d = {1.0 / d_inv.x, 1.0 / d_inv.y, 1.0 / d_inv.z}; struct xrt_vec2 offset = {0.5, 0.5}; - struct xrt_vec2 tc_r = { - offset.x + (texCoord.x * d.x + val.center[0]) * factor.x, - offset.y + (texCoord.y * d.x + val.center[1]) * factor.y}; + struct xrt_vec2 tc_r = {offset.x + (texCoord.x * d.x + val.center[0]) * factor.x, + offset.y + (texCoord.y * d.x + val.center[1]) * factor.y}; - struct xrt_vec2 tc_g = { - offset.x + (texCoord.x * d.y + val.center[0]) * factor.x, - offset.y + (texCoord.y * d.y + val.center[1]) * factor.y}; - struct xrt_vec2 tc_b = { - offset.x + (texCoord.x * d.z + val.center[0]) * factor.x, - offset.y + (texCoord.y * d.z + val.center[1]) * factor.y}; + struct xrt_vec2 tc_g = {offset.x + (texCoord.x * d.y + val.center[0]) * factor.x, + offset.y + (texCoord.y * d.y + val.center[1]) * factor.y}; + struct xrt_vec2 tc_b = {offset.x + (texCoord.x * d.z + val.center[0]) * factor.x, + offset.y + (texCoord.y * d.z + val.center[1]) * factor.y}; result->r = tc_r; result->g = tc_g; @@ -193,10 +171,7 @@ u_compute_distortion_vive(struct u_vive_values *values, #define len_sqrd m_vec2_len_sqrd bool -u_compute_distortion_panotools(struct u_panotools_values *values, - float u, - float v, - struct xrt_uv_triplet *result) +u_compute_distortion_panotools(struct u_panotools_values *values, float u, float v, struct xrt_uv_triplet *result) { const struct u_panotools_values val = *values; @@ -289,11 +264,7 @@ u_compute_distortion_none(float u, float v, struct xrt_uv_triplet *result) */ bool -u_distortion_mesh_none(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result) +u_distortion_mesh_none(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result) { return u_compute_distortion_none(u, v, result); } diff --git a/src/xrt/auxiliary/util/u_distortion_mesh.h b/src/xrt/auxiliary/util/u_distortion_mesh.h index 554c8297b..5b786a319 100644 --- a/src/xrt/auxiliary/util/u_distortion_mesh.h +++ b/src/xrt/auxiliary/util/u_distortion_mesh.h @@ -51,10 +51,7 @@ struct u_panotools_values * @ingroup aux_distortion */ bool -u_compute_distortion_panotools(struct u_panotools_values *values, - float u, - float v, - struct xrt_uv_triplet *result); +u_compute_distortion_panotools(struct u_panotools_values *values, float u, float v, struct xrt_uv_triplet *result); /* @@ -90,10 +87,7 @@ struct u_vive_values * @ingroup aux_distortion */ bool -u_compute_distortion_vive(struct u_vive_values *values, - float u, - float v, - struct xrt_uv_triplet *result); +u_compute_distortion_vive(struct u_vive_values *values, float u, float v, struct xrt_uv_triplet *result); /* @@ -134,11 +128,7 @@ u_compute_distortion_none(float u, float v, struct xrt_uv_triplet *result); * @ingroup aux_distortion */ bool -u_distortion_mesh_none(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result); +u_distortion_mesh_none(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result); /* diff --git a/src/xrt/auxiliary/util/u_file.c b/src/xrt/auxiliary/util/u_file.c index 5a3108600..ef90e6a07 100644 --- a/src/xrt/auxiliary/util/u_file.c +++ b/src/xrt/auxiliary/util/u_file.c @@ -60,16 +60,13 @@ u_file_get_config_dir(char *out_path, size_t out_path_size) return snprintf(out_path, out_path_size, "%s/monado", xgd_home); } if (home != NULL) { - return snprintf(out_path, out_path_size, "%s/.config/monado", - home); + return snprintf(out_path, out_path_size, "%s/.config/monado", home); } return -1; } ssize_t -u_file_get_path_in_config_dir(const char *filename, - char *out_path, - size_t out_path_size) +u_file_get_path_in_config_dir(const char *filename, char *out_path, size_t out_path_size) { char tmp[PATH_MAX]; ssize_t i = u_file_get_config_dir(tmp, sizeof(tmp)); diff --git a/src/xrt/auxiliary/util/u_file.h b/src/xrt/auxiliary/util/u_file.h index d6b16628f..fddf662f0 100644 --- a/src/xrt/auxiliary/util/u_file.h +++ b/src/xrt/auxiliary/util/u_file.h @@ -23,9 +23,7 @@ ssize_t u_file_get_config_dir(char *out_path, size_t out_path_size); ssize_t -u_file_get_path_in_config_dir(const char *suffix, - char *out_path, - size_t out_path_size); +u_file_get_path_in_config_dir(const char *suffix, char *out_path, size_t out_path_size); FILE * u_file_open_file_in_config_dir(const char *filename, const char *mode); diff --git a/src/xrt/auxiliary/util/u_format.c b/src/xrt/auxiliary/util/u_format.c index 5ed2393c1..b6fd6d726 100644 --- a/src/xrt/auxiliary/util/u_format.c +++ b/src/xrt/auxiliary/util/u_format.c @@ -133,11 +133,7 @@ u_format_block_size(enum xrt_format f) } void -u_format_size_for_dimensions(enum xrt_format f, - uint32_t width, - uint32_t height, - size_t *out_stride, - size_t *out_size) +u_format_size_for_dimensions(enum xrt_format f, uint32_t width, uint32_t height, size_t *out_stride, size_t *out_size) { uint32_t sw = u_format_block_width(f); uint32_t sh = u_format_block_height(f); diff --git a/src/xrt/auxiliary/util/u_format.h b/src/xrt/auxiliary/util/u_format.h index 0ba387d0a..56d539af0 100644 --- a/src/xrt/auxiliary/util/u_format.h +++ b/src/xrt/auxiliary/util/u_format.h @@ -62,11 +62,7 @@ u_format_block_size(enum xrt_format f); * @ingroup aux_util */ void -u_format_size_for_dimensions(enum xrt_format f, - uint32_t width, - uint32_t height, - size_t *out_stride, - size_t *out_size); +u_format_size_for_dimensions(enum xrt_format f, uint32_t width, uint32_t height, size_t *out_stride, size_t *out_size); #ifdef __cplusplus diff --git a/src/xrt/auxiliary/util/u_frame.c b/src/xrt/auxiliary/util/u_frame.c index 965454514..92337a1dd 100644 --- a/src/xrt/auxiliary/util/u_frame.c +++ b/src/xrt/auxiliary/util/u_frame.c @@ -23,10 +23,7 @@ free_one_off(struct xrt_frame *xf) } void -u_frame_create_one_off(enum xrt_format f, - uint32_t width, - uint32_t height, - struct xrt_frame **out_frame) +u_frame_create_one_off(enum xrt_format f, uint32_t width, uint32_t height, struct xrt_frame **out_frame) { assert(width > 0); assert(height > 0); diff --git a/src/xrt/auxiliary/util/u_frame.h b/src/xrt/auxiliary/util/u_frame.h index 92f15fd4a..290aa03d0 100644 --- a/src/xrt/auxiliary/util/u_frame.h +++ b/src/xrt/auxiliary/util/u_frame.h @@ -21,10 +21,7 @@ extern "C" { * freed. */ void -u_frame_create_one_off(enum xrt_format f, - uint32_t width, - uint32_t height, - struct xrt_frame **out_frame); +u_frame_create_one_off(enum xrt_format f, uint32_t width, uint32_t height, struct xrt_frame **out_frame); #ifdef __cplusplus diff --git a/src/xrt/auxiliary/util/u_hand_tracking.c b/src/xrt/auxiliary/util/u_hand_tracking.c index 2973892a2..8019f9b0c 100644 --- a/src/xrt/auxiliary/util/u_hand_tracking.c +++ b/src/xrt/auxiliary/util/u_hand_tracking.c @@ -17,15 +17,12 @@ #define DEG_TO_RAD(DEG) (DEG * M_PI / 180.) -#define VELOCIY_VALID_FLAGS \ - (XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT | \ - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT) +#define VELOCIY_VALID_FLAGS \ + (XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT | XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT) -#define POSE_VALID_FLAGS \ - (XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | \ - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | \ - XRT_SPACE_RELATION_POSITION_VALID_BIT | \ - XRT_SPACE_RELATION_POSITION_VALID_BIT) +#define POSE_VALID_FLAGS \ + (XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | \ + XRT_SPACE_RELATION_POSITION_VALID_BIT | XRT_SPACE_RELATION_POSITION_VALID_BIT) struct u_joint_curl_model { @@ -60,208 +57,178 @@ struct u_joint_curl_model * * angles for left hand (right hand is mirrored), angles are clockwise. */ -static struct u_joint_curl_model - hand_joint_default_set_curl_model_defaults[XRT_HAND_JOINT_COUNT] = { - // special cases: wrist and palm without bone lengths, offsets are - // absolute, relative to hand origin (palm) - [XRT_HAND_JOINT_PALM] = {.position_offset = {.x = 0, .y = 0, .z = 0}, +static struct u_joint_curl_model hand_joint_default_set_curl_model_defaults[XRT_HAND_JOINT_COUNT] = { + // special cases: wrist and palm without bone lengths, offsets are + // absolute, relative to hand origin (palm) + [XRT_HAND_JOINT_PALM] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0, + .radius = 0.018, + .joint_id = XRT_HAND_JOINT_PALM}, + + [XRT_HAND_JOINT_WRIST] = {.position_offset = {.x = 0, .y = 0, .z = 0.07}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0, + .radius = 0.03, + .joint_id = XRT_HAND_JOINT_WRIST}, + + + // fingers + // metacarpal bones are angled outwards a little, + // proximal bones copmpensate most of it, making fingers parallel again + // finger position offsets are relative to previous bone + // previous bone of metacarpal: wrist + [XRT_HAND_JOINT_LITTLE_METACARPAL] = {.position_offset = {.x = -0.03, .y = 0, .z = -0.037}, + .axis_angle_offset = {0, DEG_TO_RAD(-25), 0}, + .bone_length = 0.048, + .radius = 0.015, + .joint_id = XRT_HAND_JOINT_LITTLE_METACARPAL}, + + [XRT_HAND_JOINT_LITTLE_PROXIMAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, DEG_TO_RAD(20), 0}, + .bone_length = 0.035, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_LITTLE_PROXIMAL}, + + [XRT_HAND_JOINT_LITTLE_INTERMEDIATE] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.028, + .radius = 0.009, + .joint_id = XRT_HAND_JOINT_LITTLE_INTERMEDIATE}, + + [XRT_HAND_JOINT_LITTLE_DISTAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.022, + .radius = 0.009, + .joint_id = XRT_HAND_JOINT_LITTLE_DISTAL}, + + [XRT_HAND_JOINT_LITTLE_TIP] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0, + .radius = 0.012, + .joint_id = XRT_HAND_JOINT_LITTLE_TIP}, + + + [XRT_HAND_JOINT_RING_METACARPAL] = {.position_offset = {.x = -0.015, .y = 0, .z = -0.038}, + .axis_angle_offset = {0, DEG_TO_RAD(-12), 0}, + .bone_length = 0.052, + .radius = 0.015, + .joint_id = XRT_HAND_JOINT_RING_METACARPAL}, + + [XRT_HAND_JOINT_RING_PROXIMAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, DEG_TO_RAD(10), 0}, + .bone_length = 0.040, + .radius = 0.012, + .joint_id = XRT_HAND_JOINT_RING_PROXIMAL}, + + [XRT_HAND_JOINT_RING_INTERMEDIATE] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.031, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_RING_INTERMEDIATE}, + + [XRT_HAND_JOINT_RING_DISTAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.023, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_RING_DISTAL}, + + [XRT_HAND_JOINT_RING_TIP] = {.position_offset = {.x = 0, .y = 0, .z = 0}, .axis_angle_offset = {0, 0, 0}, .bone_length = 0, - .radius = 0.018, - .joint_id = XRT_HAND_JOINT_PALM}, - - [XRT_HAND_JOINT_WRIST] = {.position_offset = {.x = 0, - .y = 0, - .z = 0.07}, + .radius = 0.013, + .joint_id = XRT_HAND_JOINT_RING_TIP}, + + + [XRT_HAND_JOINT_MIDDLE_METACARPAL] = {.position_offset = {.x = 0.00, .y = 0, .z = -0.039}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.045, + .radius = 0.012, + .joint_id = XRT_HAND_JOINT_MIDDLE_METACARPAL}, + + [XRT_HAND_JOINT_MIDDLE_PROXIMAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.042, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_MIDDLE_PROXIMAL}, + + [XRT_HAND_JOINT_MIDDLE_INTERMEDIATE] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.033, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_MIDDLE_INTERMEDIATE}, + + [XRT_HAND_JOINT_MIDDLE_DISTAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.024, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_MIDDLE_DISTAL}, + + [XRT_HAND_JOINT_MIDDLE_TIP] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_MIDDLE_TIP}, + + + [XRT_HAND_JOINT_INDEX_METACARPAL] = {.position_offset = {.x = 0.015, .y = 0, .z = -0.038}, + .axis_angle_offset = {0, DEG_TO_RAD(12), 0}, + .bone_length = 0.05, + .radius = 0.012, + .joint_id = XRT_HAND_JOINT_INDEX_METACARPAL}, + + [XRT_HAND_JOINT_INDEX_PROXIMAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, DEG_TO_RAD(-10), 0}, + .bone_length = 0.040, + .radius = 0.011, + .joint_id = XRT_HAND_JOINT_INDEX_PROXIMAL}, + + [XRT_HAND_JOINT_INDEX_INTERMEDIATE] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.031, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_INDEX_INTERMEDIATE}, + + [XRT_HAND_JOINT_INDEX_DISTAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.023, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_INDEX_DISTAL}, + + [XRT_HAND_JOINT_INDEX_TIP] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0, + .radius = 0.01, + .joint_id = XRT_HAND_JOINT_INDEX_TIP}, + + + [XRT_HAND_JOINT_THUMB_METACARPAL] = {.position_offset = {.x = 0.03, .y = 0, .z = -0.033}, + .axis_angle_offset = {0, DEG_TO_RAD(40), 0}, + .bone_length = 0.037, + .radius = 0.0175, + .joint_id = XRT_HAND_JOINT_THUMB_METACARPAL}, + + [XRT_HAND_JOINT_THUMB_PROXIMAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, DEG_TO_RAD(-12), 0}, + .bone_length = 0.038, + .radius = 0.017, + .joint_id = XRT_HAND_JOINT_THUMB_PROXIMAL}, + // no intermediate + + [XRT_HAND_JOINT_THUMB_DISTAL] = {.position_offset = {.x = 0, .y = 0, .z = 0}, + .axis_angle_offset = {0, 0, 0}, + .bone_length = 0.028, + .radius = 0.017, + .joint_id = XRT_HAND_JOINT_THUMB_DISTAL}, + + [XRT_HAND_JOINT_THUMB_TIP] = {.position_offset = {.x = 0, .y = 0, .z = 0}, .axis_angle_offset = {0, 0, 0}, .bone_length = 0, - .radius = 0.03, - .joint_id = XRT_HAND_JOINT_WRIST}, - - - // fingers - // metacarpal bones are angled outwards a little, - // proximal bones copmpensate most of it, making fingers parallel again - // finger position offsets are relative to previous bone - // previous bone of metacarpal: wrist - [XRT_HAND_JOINT_LITTLE_METACARPAL] = - {.position_offset = {.x = -0.03, .y = 0, .z = -0.037}, - .axis_angle_offset = {0, DEG_TO_RAD(-25), 0}, - .bone_length = 0.048, - .radius = 0.015, - .joint_id = XRT_HAND_JOINT_LITTLE_METACARPAL}, - - [XRT_HAND_JOINT_LITTLE_PROXIMAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, DEG_TO_RAD(20), 0}, - .bone_length = 0.035, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_LITTLE_PROXIMAL}, - - [XRT_HAND_JOINT_LITTLE_INTERMEDIATE] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.028, - .radius = 0.009, - .joint_id = XRT_HAND_JOINT_LITTLE_INTERMEDIATE}, - - [XRT_HAND_JOINT_LITTLE_DISTAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.022, - .radius = 0.009, - .joint_id = XRT_HAND_JOINT_LITTLE_DISTAL}, - - [XRT_HAND_JOINT_LITTLE_TIP] = {.position_offset = {.x = 0, - .y = 0, - .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0, - .radius = 0.012, - .joint_id = XRT_HAND_JOINT_LITTLE_TIP}, - - - [XRT_HAND_JOINT_RING_METACARPAL] = - {.position_offset = {.x = -0.015, .y = 0, .z = -0.038}, - .axis_angle_offset = {0, DEG_TO_RAD(-12), 0}, - .bone_length = 0.052, - .radius = 0.015, - .joint_id = XRT_HAND_JOINT_RING_METACARPAL}, - - [XRT_HAND_JOINT_RING_PROXIMAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, DEG_TO_RAD(10), 0}, - .bone_length = 0.040, - .radius = 0.012, - .joint_id = XRT_HAND_JOINT_RING_PROXIMAL}, - - [XRT_HAND_JOINT_RING_INTERMEDIATE] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.031, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_RING_INTERMEDIATE}, - - [XRT_HAND_JOINT_RING_DISTAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.023, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_RING_DISTAL}, - - [XRT_HAND_JOINT_RING_TIP] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0, - .radius = 0.013, - .joint_id = XRT_HAND_JOINT_RING_TIP}, - - - [XRT_HAND_JOINT_MIDDLE_METACARPAL] = - {.position_offset = {.x = 0.00, .y = 0, .z = -0.039}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.045, - .radius = 0.012, - .joint_id = XRT_HAND_JOINT_MIDDLE_METACARPAL}, - - [XRT_HAND_JOINT_MIDDLE_PROXIMAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.042, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_MIDDLE_PROXIMAL}, - - [XRT_HAND_JOINT_MIDDLE_INTERMEDIATE] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.033, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_MIDDLE_INTERMEDIATE}, - - [XRT_HAND_JOINT_MIDDLE_DISTAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.024, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_MIDDLE_DISTAL}, - - [XRT_HAND_JOINT_MIDDLE_TIP] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_MIDDLE_TIP}, - - - [XRT_HAND_JOINT_INDEX_METACARPAL] = - {.position_offset = {.x = 0.015, .y = 0, .z = -0.038}, - .axis_angle_offset = {0, DEG_TO_RAD(12), 0}, - .bone_length = 0.05, - .radius = 0.012, - .joint_id = XRT_HAND_JOINT_INDEX_METACARPAL}, - - [XRT_HAND_JOINT_INDEX_PROXIMAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, DEG_TO_RAD(-10), 0}, - .bone_length = 0.040, - .radius = 0.011, - .joint_id = XRT_HAND_JOINT_INDEX_PROXIMAL}, - - [XRT_HAND_JOINT_INDEX_INTERMEDIATE] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.031, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_INDEX_INTERMEDIATE}, - - [XRT_HAND_JOINT_INDEX_DISTAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.023, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_INDEX_DISTAL}, - - [XRT_HAND_JOINT_INDEX_TIP] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0, - .radius = 0.01, - .joint_id = XRT_HAND_JOINT_INDEX_TIP}, - - - [XRT_HAND_JOINT_THUMB_METACARPAL] = - {.position_offset = {.x = 0.03, .y = 0, .z = -0.033}, - .axis_angle_offset = {0, DEG_TO_RAD(40), 0}, - .bone_length = 0.037, - .radius = 0.0175, - .joint_id = XRT_HAND_JOINT_THUMB_METACARPAL}, - - [XRT_HAND_JOINT_THUMB_PROXIMAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, DEG_TO_RAD(-12), 0}, - .bone_length = 0.038, - .radius = 0.017, - .joint_id = XRT_HAND_JOINT_THUMB_PROXIMAL}, - // no intermediate - - [XRT_HAND_JOINT_THUMB_DISTAL] = - {.position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0.028, - .radius = 0.017, - .joint_id = XRT_HAND_JOINT_THUMB_DISTAL}, - - [XRT_HAND_JOINT_THUMB_TIP] = { - .position_offset = {.x = 0, .y = 0, .z = 0}, - .axis_angle_offset = {0, 0, 0}, - .bone_length = 0, - .radius = 0.016, - .joint_id = XRT_HAND_JOINT_THUMB_TIP}}; + .radius = 0.016, + .joint_id = XRT_HAND_JOINT_THUMB_TIP}}; inline static void -quat_from_angle_vector_clockwise(float angle_rads, - const struct xrt_vec3 *vector, - struct xrt_quat *result) +quat_from_angle_vector_clockwise(float angle_rads, const struct xrt_vec3 *vector, struct xrt_quat *result) { math_quat_from_angle_vector(-angle_rads, vector, result); } @@ -269,59 +236,47 @@ quat_from_angle_vector_clockwise(float angle_rads, bool u_hand_joint_is_metacarpal(enum xrt_hand_joint joint) { - return joint == XRT_HAND_JOINT_LITTLE_METACARPAL || - joint == XRT_HAND_JOINT_RING_METACARPAL || - joint == XRT_HAND_JOINT_MIDDLE_METACARPAL || - joint == XRT_HAND_JOINT_INDEX_METACARPAL || + return joint == XRT_HAND_JOINT_LITTLE_METACARPAL || joint == XRT_HAND_JOINT_RING_METACARPAL || + joint == XRT_HAND_JOINT_MIDDLE_METACARPAL || joint == XRT_HAND_JOINT_INDEX_METACARPAL || joint == XRT_HAND_JOINT_THUMB_METACARPAL; } bool u_hand_joint_is_proximal(enum xrt_hand_joint joint) { - return joint == XRT_HAND_JOINT_LITTLE_PROXIMAL || - joint == XRT_HAND_JOINT_RING_PROXIMAL || - joint == XRT_HAND_JOINT_MIDDLE_PROXIMAL || - joint == XRT_HAND_JOINT_INDEX_PROXIMAL || + return joint == XRT_HAND_JOINT_LITTLE_PROXIMAL || joint == XRT_HAND_JOINT_RING_PROXIMAL || + joint == XRT_HAND_JOINT_MIDDLE_PROXIMAL || joint == XRT_HAND_JOINT_INDEX_PROXIMAL || joint == XRT_HAND_JOINT_THUMB_PROXIMAL; } bool u_hand_joint_is_intermediate(enum xrt_hand_joint joint) { - return joint == XRT_HAND_JOINT_LITTLE_INTERMEDIATE || - joint == XRT_HAND_JOINT_RING_INTERMEDIATE || - joint == XRT_HAND_JOINT_MIDDLE_INTERMEDIATE || - joint == XRT_HAND_JOINT_INDEX_INTERMEDIATE; + return joint == XRT_HAND_JOINT_LITTLE_INTERMEDIATE || joint == XRT_HAND_JOINT_RING_INTERMEDIATE || + joint == XRT_HAND_JOINT_MIDDLE_INTERMEDIATE || joint == XRT_HAND_JOINT_INDEX_INTERMEDIATE; } bool u_hand_joint_is_distal(enum xrt_hand_joint joint) { - return joint == XRT_HAND_JOINT_LITTLE_DISTAL || - joint == XRT_HAND_JOINT_RING_DISTAL || - joint == XRT_HAND_JOINT_MIDDLE_DISTAL || - joint == XRT_HAND_JOINT_INDEX_DISTAL || + return joint == XRT_HAND_JOINT_LITTLE_DISTAL || joint == XRT_HAND_JOINT_RING_DISTAL || + joint == XRT_HAND_JOINT_MIDDLE_DISTAL || joint == XRT_HAND_JOINT_INDEX_DISTAL || joint == XRT_HAND_JOINT_THUMB_DISTAL; } bool u_hand_joint_is_tip(enum xrt_hand_joint joint) { - return joint == XRT_HAND_JOINT_LITTLE_TIP || - joint == XRT_HAND_JOINT_RING_TIP || - joint == XRT_HAND_JOINT_MIDDLE_TIP || - joint == XRT_HAND_JOINT_INDEX_TIP || + return joint == XRT_HAND_JOINT_LITTLE_TIP || joint == XRT_HAND_JOINT_RING_TIP || + joint == XRT_HAND_JOINT_MIDDLE_TIP || joint == XRT_HAND_JOINT_INDEX_TIP || joint == XRT_HAND_JOINT_THUMB_TIP; } bool u_hand_joint_is_thumb(enum xrt_hand_joint joint) { - return joint == XRT_HAND_JOINT_THUMB_METACARPAL || - joint == XRT_HAND_JOINT_THUMB_PROXIMAL || - joint == XRT_HAND_JOINT_THUMB_DISTAL || - joint == XRT_HAND_JOINT_THUMB_TIP; + return joint == XRT_HAND_JOINT_THUMB_METACARPAL || joint == XRT_HAND_JOINT_THUMB_PROXIMAL || + joint == XRT_HAND_JOINT_THUMB_DISTAL || joint == XRT_HAND_JOINT_THUMB_TIP; } static void @@ -342,10 +297,8 @@ u_hand_joint_compute_next_by_curl(struct u_hand_tracking *set, { struct xrt_space_relation old_relation = out_joint->relation; - struct u_joint_curl_model prev_defaults = - hand_joint_default_set_curl_model_defaults[prev->joint_id]; - struct u_joint_curl_model defaults = - hand_joint_default_set_curl_model_defaults[out_joint->joint_id]; + struct u_joint_curl_model prev_defaults = hand_joint_default_set_curl_model_defaults[prev->joint_id]; + struct u_joint_curl_model defaults = hand_joint_default_set_curl_model_defaults[out_joint->joint_id]; scale_model_param(&prev_defaults, set->scale); scale_model_param(&defaults, set->scale); @@ -374,20 +327,15 @@ u_hand_joint_compute_next_by_curl(struct u_hand_tracking *set, //! @todo handle velocities struct xrt_pose offset_pose; if (hand == XRT_HAND_LEFT) { - quat_from_angle_vector_clockwise(defaults.axis_angle_offset[1], - &y_axis, - &offset_pose.orientation); + quat_from_angle_vector_clockwise(defaults.axis_angle_offset[1], &y_axis, &offset_pose.orientation); offset_pose.position = defaults.position_offset; } if (hand == XRT_HAND_RIGHT) { - quat_from_angle_vector_clockwise(-defaults.axis_angle_offset[1], - &y_axis, - &offset_pose.orientation); - - offset_pose.position = - (struct xrt_vec3){.x = defaults.position_offset.x * -1, - .y = defaults.position_offset.y, - .z = defaults.position_offset.z}; + quat_from_angle_vector_clockwise(-defaults.axis_angle_offset[1], &y_axis, &offset_pose.orientation); + + offset_pose.position = (struct xrt_vec3){.x = defaults.position_offset.x * -1, + .y = defaults.position_offset.y, + .z = defaults.position_offset.z}; } math_pose_transform(&pose, &offset_pose, &pose); @@ -430,23 +378,17 @@ u_hand_joint_compute_next_by_curl(struct u_hand_tracking *set, // linear velocity = // diff of current and old joint position, divided by timestamp diff out_joint->relation.linear_velocity = out_joint->relation.pose.position; - math_vec3_subtract(&old_relation.pose.position, - &out_joint->relation.linear_velocity); - math_vec3_scalar_mul(1. / time_diff_s, - &out_joint->relation.linear_velocity); + math_vec3_subtract(&old_relation.pose.position, &out_joint->relation.linear_velocity); + math_vec3_scalar_mul(1. / time_diff_s, &out_joint->relation.linear_velocity); if (time_diff_s > 0) { - math_quat_finite_difference( - &old_relation.pose.orientation, - &out_joint->relation.pose.orientation, time_diff_s, - &out_joint->relation.angular_velocity); + math_quat_finite_difference(&old_relation.pose.orientation, &out_joint->relation.pose.orientation, + time_diff_s, &out_joint->relation.angular_velocity); } else { - out_joint->relation.angular_velocity = - (struct xrt_vec3){0, 0, 0}; + out_joint->relation.angular_velocity = (struct xrt_vec3){0, 0, 0}; } - out_joint->relation.relation_flags = - POSE_VALID_FLAGS | VELOCIY_VALID_FLAGS; + out_joint->relation.relation_flags = POSE_VALID_FLAGS | VELOCIY_VALID_FLAGS; } void @@ -467,78 +409,51 @@ u_hand_joints_update_curl(struct u_hand_tracking *set, // wrist and palm mostly fixed poses set->joints.wrist.relation.pose = (struct xrt_pose){ - .position = - hand_joint_default_set_curl_model_defaults[XRT_HAND_JOINT_WRIST] - .position_offset, + .position = hand_joint_default_set_curl_model_defaults[XRT_HAND_JOINT_WRIST].position_offset, .orientation = identity_quat}; set->joints.wrist.relation.linear_velocity = (struct xrt_vec3){0, 0, 0}; - set->joints.wrist.relation.angular_velocity = - (struct xrt_vec3){0, 0, 0}; - set->joints.wrist.relation.relation_flags = - POSE_VALID_FLAGS | VELOCIY_VALID_FLAGS; + set->joints.wrist.relation.angular_velocity = (struct xrt_vec3){0, 0, 0}; + set->joints.wrist.relation.relation_flags = POSE_VALID_FLAGS | VELOCIY_VALID_FLAGS; set->joints.palm.relation.pose = (struct xrt_pose){ - .position = - hand_joint_default_set_curl_model_defaults[XRT_HAND_JOINT_PALM] - .position_offset, + .position = hand_joint_default_set_curl_model_defaults[XRT_HAND_JOINT_PALM].position_offset, .orientation = identity_quat}; set->joints.palm.relation.linear_velocity = (struct xrt_vec3){0, 0, 0}; set->joints.palm.relation.angular_velocity = (struct xrt_vec3){0, 0, 0}; - set->joints.palm.relation.relation_flags = - POSE_VALID_FLAGS | VELOCIY_VALID_FLAGS; + set->joints.palm.relation.relation_flags = POSE_VALID_FLAGS | VELOCIY_VALID_FLAGS; struct u_joint_space_relation *prev = &set->joints.wrist; - for (int joint_num = 0; - joint_num < set->joints.fingers[XRT_FINGER_LITTLE].num_joints; - joint_num++) { - struct u_joint_space_relation *joint = - &set->joints.fingers[XRT_FINGER_LITTLE].joints[joint_num]; - u_hand_joint_compute_next_by_curl( - set, prev, hand, at_timestamp_ns, joint, curl_little); + for (int joint_num = 0; joint_num < set->joints.fingers[XRT_FINGER_LITTLE].num_joints; joint_num++) { + struct u_joint_space_relation *joint = &set->joints.fingers[XRT_FINGER_LITTLE].joints[joint_num]; + u_hand_joint_compute_next_by_curl(set, prev, hand, at_timestamp_ns, joint, curl_little); prev = joint; } prev = &set->joints.wrist; - for (int joint_num = 0; - joint_num < set->joints.fingers[XRT_FINGER_RING].num_joints; - joint_num++) { - struct u_joint_space_relation *joint = - &set->joints.fingers[XRT_FINGER_RING].joints[joint_num]; - u_hand_joint_compute_next_by_curl( - set, prev, hand, at_timestamp_ns, joint, curl_ring); + for (int joint_num = 0; joint_num < set->joints.fingers[XRT_FINGER_RING].num_joints; joint_num++) { + struct u_joint_space_relation *joint = &set->joints.fingers[XRT_FINGER_RING].joints[joint_num]; + u_hand_joint_compute_next_by_curl(set, prev, hand, at_timestamp_ns, joint, curl_ring); prev = joint; } prev = &set->joints.wrist; - for (int joint_num = 0; - joint_num < set->joints.fingers[XRT_FINGER_MIDDLE].num_joints; - joint_num++) { - struct u_joint_space_relation *joint = - &set->joints.fingers[XRT_FINGER_MIDDLE].joints[joint_num]; - u_hand_joint_compute_next_by_curl( - set, prev, hand, at_timestamp_ns, joint, curl_middle); + for (int joint_num = 0; joint_num < set->joints.fingers[XRT_FINGER_MIDDLE].num_joints; joint_num++) { + struct u_joint_space_relation *joint = &set->joints.fingers[XRT_FINGER_MIDDLE].joints[joint_num]; + u_hand_joint_compute_next_by_curl(set, prev, hand, at_timestamp_ns, joint, curl_middle); prev = joint; } prev = &set->joints.wrist; - for (int joint_num = 0; - joint_num < set->joints.fingers[XRT_FINGER_INDEX].num_joints; - joint_num++) { - struct u_joint_space_relation *joint = - &set->joints.fingers[XRT_FINGER_INDEX].joints[joint_num]; - u_hand_joint_compute_next_by_curl( - set, prev, hand, at_timestamp_ns, joint, curl_index); + for (int joint_num = 0; joint_num < set->joints.fingers[XRT_FINGER_INDEX].num_joints; joint_num++) { + struct u_joint_space_relation *joint = &set->joints.fingers[XRT_FINGER_INDEX].joints[joint_num]; + u_hand_joint_compute_next_by_curl(set, prev, hand, at_timestamp_ns, joint, curl_index); prev = joint; } prev = &set->joints.wrist; - for (int joint_num = 0; - joint_num < set->joints.fingers[XRT_FINGER_THUMB].num_joints; - joint_num++) { - struct u_joint_space_relation *joint = - &set->joints.fingers[XRT_FINGER_THUMB].joints[joint_num]; - u_hand_joint_compute_next_by_curl( - set, prev, hand, at_timestamp_ns, joint, curl_thumb); + for (int joint_num = 0; joint_num < set->joints.fingers[XRT_FINGER_THUMB].num_joints; joint_num++) { + struct u_joint_space_relation *joint = &set->joints.fingers[XRT_FINGER_THUMB].joints[joint_num]; + u_hand_joint_compute_next_by_curl(set, prev, hand, at_timestamp_ns, joint, curl_thumb); prev = joint; } @@ -555,145 +470,133 @@ u_hand_joints_init_default_set(struct u_hand_tracking *set, struct xrt_space_relation identity; m_space_relation_ident(&identity); - *set = (struct u_hand_tracking){ - .joints = { - .palm = {.joint_id = XRT_HAND_JOINT_PALM, .relation = identity}, - .wrist = {.joint_id = XRT_HAND_JOINT_WRIST, - .relation = identity}, - - .fingers = { - [XRT_FINGER_LITTLE] = - {.num_joints = 5, - .joints = - { - { - .joint_id = - XRT_HAND_JOINT_LITTLE_METACARPAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_LITTLE_PROXIMAL, - .relation = identity, - }, - { - .joint_id = - XRT_HAND_JOINT_LITTLE_INTERMEDIATE, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_LITTLE_DISTAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_LITTLE_TIP, - .relation = identity, - }, - }}, - - [XRT_FINGER_RING] = - {.num_joints = 5, - .joints = - { - { - .joint_id = XRT_HAND_JOINT_RING_METACARPAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_RING_PROXIMAL, - .relation = identity, - }, - { - .joint_id = - XRT_HAND_JOINT_RING_INTERMEDIATE, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_RING_DISTAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_RING_TIP, - .relation = identity, - }, - }}, - - [XRT_FINGER_MIDDLE] = - {.num_joints = 5, - .joints = - { - { - .joint_id = - XRT_HAND_JOINT_MIDDLE_METACARPAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_MIDDLE_PROXIMAL, - .relation = identity, - }, - { - .joint_id = - XRT_HAND_JOINT_MIDDLE_INTERMEDIATE, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_MIDDLE_DISTAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_MIDDLE_TIP, - .relation = identity, - }, - }}, - - [XRT_FINGER_INDEX] = - {.num_joints = 5, - .joints = - { - { - .joint_id = - XRT_HAND_JOINT_INDEX_METACARPAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_INDEX_PROXIMAL, - .relation = identity, - }, - { - .joint_id = - XRT_HAND_JOINT_INDEX_INTERMEDIATE, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_INDEX_DISTAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_INDEX_TIP, - .relation = identity, - }, - }}, - - [XRT_FINGER_THUMB] = { - .num_joints = 4, - .joints = { - { - .joint_id = XRT_HAND_JOINT_THUMB_METACARPAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_THUMB_PROXIMAL, - .relation = identity, - }, - // has no intermediate - { - .joint_id = XRT_HAND_JOINT_THUMB_DISTAL, - .relation = identity, - }, - { - .joint_id = XRT_HAND_JOINT_THUMB_TIP, - .relation = identity, - }, - }}}}}; + *set = + (struct u_hand_tracking){ + .joints = {.palm = {.joint_id = XRT_HAND_JOINT_PALM, .relation = identity}, + .wrist = {.joint_id = XRT_HAND_JOINT_WRIST, .relation = identity}, + + .fingers = {[XRT_FINGER_LITTLE] = {.num_joints = 5, + .joints = + { + { + .joint_id = XRT_HAND_JOINT_LITTLE_METACARPAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_LITTLE_PROXIMAL, + .relation = identity, + }, + { + .joint_id = + XRT_HAND_JOINT_LITTLE_INTERMEDIATE, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_LITTLE_DISTAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_LITTLE_TIP, + .relation = identity, + }, + }}, + + [XRT_FINGER_RING] = {.num_joints = 5, + .joints = + { + { + .joint_id = XRT_HAND_JOINT_RING_METACARPAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_RING_PROXIMAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_RING_INTERMEDIATE, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_RING_DISTAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_RING_TIP, + .relation = identity, + }, + }}, + + [XRT_FINGER_MIDDLE] = {.num_joints = 5, + .joints = + { + { + .joint_id = XRT_HAND_JOINT_MIDDLE_METACARPAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_MIDDLE_PROXIMAL, + .relation = identity, + }, + { + .joint_id = + XRT_HAND_JOINT_MIDDLE_INTERMEDIATE, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_MIDDLE_DISTAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_MIDDLE_TIP, + .relation = identity, + }, + }}, + + [XRT_FINGER_INDEX] = {.num_joints = 5, + .joints = + { + { + .joint_id = XRT_HAND_JOINT_INDEX_METACARPAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_INDEX_PROXIMAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_INDEX_INTERMEDIATE, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_INDEX_DISTAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_INDEX_TIP, + .relation = identity, + }, + }}, + + [XRT_FINGER_THUMB] = {.num_joints = 4, + .joints = { + { + .joint_id = XRT_HAND_JOINT_THUMB_METACARPAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_THUMB_PROXIMAL, + .relation = identity, + }, + // has no intermediate + { + .joint_id = XRT_HAND_JOINT_THUMB_DISTAL, + .relation = identity, + }, + { + .joint_id = XRT_HAND_JOINT_THUMB_TIP, + .relation = identity, + }, + }}}}}; set->model = XRT_HAND_TRACKING_MODEL_FINGERL_CURL; set->scale = scale; @@ -709,59 +612,35 @@ get_joint_data(struct u_hand_tracking *set, enum xrt_hand_joint joint_id) case XRT_HAND_JOINT_WRIST: return &set->joints.wrist; case XRT_HAND_JOINT_PALM: return &set->joints.palm; - case XRT_HAND_JOINT_LITTLE_METACARPAL: - return &set->joints.fingers[XRT_FINGER_LITTLE].joints[0]; - case XRT_HAND_JOINT_LITTLE_PROXIMAL: - return &set->joints.fingers[XRT_FINGER_LITTLE].joints[1]; - case XRT_HAND_JOINT_LITTLE_INTERMEDIATE: - return &set->joints.fingers[XRT_FINGER_LITTLE].joints[2]; - case XRT_HAND_JOINT_LITTLE_DISTAL: - return &set->joints.fingers[XRT_FINGER_LITTLE].joints[3]; - case XRT_HAND_JOINT_LITTLE_TIP: - return &set->joints.fingers[XRT_FINGER_LITTLE].joints[4]; - - case XRT_HAND_JOINT_RING_METACARPAL: - return &set->joints.fingers[XRT_FINGER_RING].joints[0]; - case XRT_HAND_JOINT_RING_PROXIMAL: - return &set->joints.fingers[XRT_FINGER_RING].joints[1]; - case XRT_HAND_JOINT_RING_INTERMEDIATE: - return &set->joints.fingers[XRT_FINGER_RING].joints[2]; - case XRT_HAND_JOINT_RING_DISTAL: - return &set->joints.fingers[XRT_FINGER_RING].joints[3]; - case XRT_HAND_JOINT_RING_TIP: - return &set->joints.fingers[XRT_FINGER_RING].joints[4]; - - case XRT_HAND_JOINT_MIDDLE_METACARPAL: - return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[0]; - case XRT_HAND_JOINT_MIDDLE_PROXIMAL: - return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[1]; - case XRT_HAND_JOINT_MIDDLE_INTERMEDIATE: - return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[2]; - case XRT_HAND_JOINT_MIDDLE_DISTAL: - return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[3]; - case XRT_HAND_JOINT_MIDDLE_TIP: - return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[4]; - - case XRT_HAND_JOINT_INDEX_METACARPAL: - return &set->joints.fingers[XRT_FINGER_INDEX].joints[0]; - case XRT_HAND_JOINT_INDEX_PROXIMAL: - return &set->joints.fingers[XRT_FINGER_INDEX].joints[1]; - case XRT_HAND_JOINT_INDEX_INTERMEDIATE: - return &set->joints.fingers[XRT_FINGER_INDEX].joints[2]; - case XRT_HAND_JOINT_INDEX_DISTAL: - return &set->joints.fingers[XRT_FINGER_INDEX].joints[3]; - case XRT_HAND_JOINT_INDEX_TIP: - return &set->joints.fingers[XRT_FINGER_INDEX].joints[4]; - - case XRT_HAND_JOINT_THUMB_METACARPAL: - return &set->joints.fingers[XRT_FINGER_THUMB].joints[0]; - case XRT_HAND_JOINT_THUMB_PROXIMAL: - return &set->joints.fingers[XRT_FINGER_THUMB].joints[1]; + case XRT_HAND_JOINT_LITTLE_METACARPAL: return &set->joints.fingers[XRT_FINGER_LITTLE].joints[0]; + case XRT_HAND_JOINT_LITTLE_PROXIMAL: return &set->joints.fingers[XRT_FINGER_LITTLE].joints[1]; + case XRT_HAND_JOINT_LITTLE_INTERMEDIATE: return &set->joints.fingers[XRT_FINGER_LITTLE].joints[2]; + case XRT_HAND_JOINT_LITTLE_DISTAL: return &set->joints.fingers[XRT_FINGER_LITTLE].joints[3]; + case XRT_HAND_JOINT_LITTLE_TIP: return &set->joints.fingers[XRT_FINGER_LITTLE].joints[4]; + + case XRT_HAND_JOINT_RING_METACARPAL: return &set->joints.fingers[XRT_FINGER_RING].joints[0]; + case XRT_HAND_JOINT_RING_PROXIMAL: return &set->joints.fingers[XRT_FINGER_RING].joints[1]; + case XRT_HAND_JOINT_RING_INTERMEDIATE: return &set->joints.fingers[XRT_FINGER_RING].joints[2]; + case XRT_HAND_JOINT_RING_DISTAL: return &set->joints.fingers[XRT_FINGER_RING].joints[3]; + case XRT_HAND_JOINT_RING_TIP: return &set->joints.fingers[XRT_FINGER_RING].joints[4]; + + case XRT_HAND_JOINT_MIDDLE_METACARPAL: return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[0]; + case XRT_HAND_JOINT_MIDDLE_PROXIMAL: return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[1]; + case XRT_HAND_JOINT_MIDDLE_INTERMEDIATE: return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[2]; + case XRT_HAND_JOINT_MIDDLE_DISTAL: return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[3]; + case XRT_HAND_JOINT_MIDDLE_TIP: return &set->joints.fingers[XRT_FINGER_MIDDLE].joints[4]; + + case XRT_HAND_JOINT_INDEX_METACARPAL: return &set->joints.fingers[XRT_FINGER_INDEX].joints[0]; + case XRT_HAND_JOINT_INDEX_PROXIMAL: return &set->joints.fingers[XRT_FINGER_INDEX].joints[1]; + case XRT_HAND_JOINT_INDEX_INTERMEDIATE: return &set->joints.fingers[XRT_FINGER_INDEX].joints[2]; + case XRT_HAND_JOINT_INDEX_DISTAL: return &set->joints.fingers[XRT_FINGER_INDEX].joints[3]; + case XRT_HAND_JOINT_INDEX_TIP: return &set->joints.fingers[XRT_FINGER_INDEX].joints[4]; + + case XRT_HAND_JOINT_THUMB_METACARPAL: return &set->joints.fingers[XRT_FINGER_THUMB].joints[0]; + case XRT_HAND_JOINT_THUMB_PROXIMAL: return &set->joints.fingers[XRT_FINGER_THUMB].joints[1]; // no intermediate for thumb - case XRT_HAND_JOINT_THUMB_DISTAL: - return &set->joints.fingers[XRT_FINGER_THUMB].joints[2]; - case XRT_HAND_JOINT_THUMB_TIP: - return &set->joints.fingers[XRT_FINGER_THUMB].joints[3]; + case XRT_HAND_JOINT_THUMB_DISTAL: return &set->joints.fingers[XRT_FINGER_THUMB].joints[2]; + case XRT_HAND_JOINT_THUMB_TIP: return &set->joints.fingers[XRT_FINGER_THUMB].joints[3]; case XRT_HAND_JOINT_MAX_ENUM: return NULL; } @@ -776,15 +655,13 @@ u_hand_joints_set_out_data(struct u_hand_tracking *set, struct xrt_hand_joint_set *out_value) { - struct xrt_hand_joint_value *l = - out_value->values.hand_joint_set_default; + struct xrt_hand_joint_value *l = out_value->values.hand_joint_set_default; for (int i = 0; i < XRT_HAND_JOINT_COUNT; i++) { struct u_joint_space_relation *data = get_joint_data(set, i); l[i].relation.relation_flags |= data->relation.relation_flags; - l[i].radius = - hand_joint_default_set_curl_model_defaults[i].radius; + l[i].radius = hand_joint_default_set_curl_model_defaults[i].radius; struct xrt_space_graph graph = {0}; m_space_graph_add_relation(&graph, &data->relation); @@ -796,9 +673,7 @@ u_hand_joints_set_out_data(struct u_hand_tracking *set, } void -u_hand_joints_offset_valve_index_controller(enum xrt_hand hand, - struct xrt_vec3 *static_offset, - struct xrt_pose *offset) +u_hand_joints_offset_valve_index_controller(enum xrt_hand hand, struct xrt_vec3 *static_offset, struct xrt_pose *offset) { /* Controller space origin is at the very tip of the controller, * handle pointing forward at -z. @@ -826,22 +701,18 @@ u_hand_joints_offset_valve_index_controller(enum xrt_hand hand, struct xrt_quat hand_rotation_y = {0, 0, 0, 1}; - math_quat_from_angle_vector(hand_on_handle_y_rotation, &y, - &hand_rotation_y); + math_quat_from_angle_vector(hand_on_handle_y_rotation, &y, &hand_rotation_y); struct xrt_quat hand_rotation_z = {0, 0, 0, 1}; - math_quat_from_angle_vector(hand_on_handle_z_rotation, &z, - &hand_rotation_z); + math_quat_from_angle_vector(hand_on_handle_z_rotation, &z, &hand_rotation_z); struct xrt_quat hand_rotation_x = {0, 0, 0, 1}; - math_quat_from_angle_vector(hand_on_handle_x_rotation, &x, - &hand_rotation_x); + math_quat_from_angle_vector(hand_on_handle_x_rotation, &x, &hand_rotation_x); struct xrt_quat hand_rotation; math_quat_rotate(&hand_rotation_x, &hand_rotation_z, &hand_rotation); - struct xrt_pose hand_on_handle_pose = {.orientation = hand_rotation, - .position = *static_offset}; + struct xrt_pose hand_on_handle_pose = {.orientation = hand_rotation, .position = *static_offset}; *offset = hand_on_handle_pose; } diff --git a/src/xrt/auxiliary/util/u_handles.c b/src/xrt/auxiliary/util/u_handles.c index 4890a9a38..c6ddcce5c 100644 --- a/src/xrt/auxiliary/util/u_handles.c +++ b/src/xrt/auxiliary/util/u_handles.c @@ -56,8 +56,7 @@ ref_graphics_handle(xrt_graphics_buffer_handle_t handle) { HANDLE self = GetCurrentProcess(); HANDLE result = NULL; - if (DuplicateHandle(self, handle, self, &result, 0, FALSE, - DUPLICATE_SAME_ACCESS) != 0) { + if (DuplicateHandle(self, handle, self, &result, 0, FALSE, DUPLICATE_SAME_ACCESS) != 0) { return result; } return NULL; diff --git a/src/xrt/auxiliary/util/u_hashmap.cpp b/src/xrt/auxiliary/util/u_hashmap.cpp index 7d65135ca..b572620f5 100644 --- a/src/xrt/auxiliary/util/u_hashmap.cpp +++ b/src/xrt/auxiliary/util/u_hashmap.cpp @@ -80,9 +80,7 @@ u_hashmap_int_empty(const struct u_hashmap_int *hmi) } extern "C" void -u_hashmap_int_clear_and_call_for_each(struct u_hashmap_int *hmi, - u_hashmap_int_callback cb, - void *priv) +u_hashmap_int_clear_and_call_for_each(struct u_hashmap_int *hmi, u_hashmap_int_callback cb, void *priv) { std::vector tmp; tmp.reserve(hmi->map.size()); diff --git a/src/xrt/auxiliary/util/u_hashmap.h b/src/xrt/auxiliary/util/u_hashmap.h index f9afcf0b5..29cb980d8 100644 --- a/src/xrt/auxiliary/util/u_hashmap.h +++ b/src/xrt/auxiliary/util/u_hashmap.h @@ -54,9 +54,7 @@ u_hashmap_int_empty(const struct u_hashmap_int *hmi); * @ingroup aux_util */ void -u_hashmap_int_clear_and_call_for_each(struct u_hashmap_int *hmi, - u_hashmap_int_callback cb, - void *priv); +u_hashmap_int_clear_and_call_for_each(struct u_hashmap_int *hmi, u_hashmap_int_callback cb, void *priv); #ifdef __cplusplus diff --git a/src/xrt/auxiliary/util/u_hashset.cpp b/src/xrt/auxiliary/util/u_hashset.cpp index aff5cdbfd..ea8ea10b0 100644 --- a/src/xrt/auxiliary/util/u_hashset.cpp +++ b/src/xrt/auxiliary/util/u_hashset.cpp @@ -51,10 +51,7 @@ u_hashset_destroy(struct u_hashset **hs) } extern "C" int -u_hashset_find_str(struct u_hashset *hs, - const char *str, - size_t length, - struct u_hashset_item **out_item) +u_hashset_find_str(struct u_hashset *hs, const char *str, size_t length, struct u_hashset_item **out_item) { std::string key = std::string(str, length); auto search = hs->map.find(key); @@ -67,9 +64,7 @@ u_hashset_find_str(struct u_hashset *hs, } extern "C" int -u_hashset_find_c_str(struct u_hashset *hs, - const char *c_str, - struct u_hashset_item **out_item) +u_hashset_find_c_str(struct u_hashset *hs, const char *c_str, struct u_hashset_item **out_item) { size_t length = strlen(c_str); return u_hashset_find_str(hs, c_str, length, out_item); @@ -84,10 +79,7 @@ u_hashset_insert_item(struct u_hashset *hs, struct u_hashset_item *item) } extern "C" int -u_hashset_create_and_insert_str(struct u_hashset *hs, - const char *str, - size_t length, - struct u_hashset_item **out_item) +u_hashset_create_and_insert_str(struct u_hashset *hs, const char *str, size_t length, struct u_hashset_item **out_item) { struct u_hashset_item *dummy = NULL; struct u_hashset_item *item = NULL; @@ -126,9 +118,7 @@ u_hashset_create_and_insert_str(struct u_hashset *hs, } extern "C" int -u_hashset_create_and_insert_str_c(struct u_hashset *hs, - const char *c_str, - struct u_hashset_item **out_item) +u_hashset_create_and_insert_str_c(struct u_hashset *hs, const char *c_str, struct u_hashset_item **out_item) { size_t length = strlen(c_str); return u_hashset_create_and_insert_str(hs, c_str, length, out_item); @@ -158,9 +148,7 @@ u_hashset_erase_c_str(struct u_hashset *hs, const char *c_str) } extern "C" void -u_hashset_clear_and_call_for_each(struct u_hashset *hs, - u_hashset_callback cb, - void *priv) +u_hashset_clear_and_call_for_each(struct u_hashset *hs, u_hashset_callback cb, void *priv) { std::vector tmp; tmp.reserve(hs->map.size()); diff --git a/src/xrt/auxiliary/util/u_hashset.h b/src/xrt/auxiliary/util/u_hashset.h index 554e14875..5c52c2000 100644 --- a/src/xrt/auxiliary/util/u_hashset.h +++ b/src/xrt/auxiliary/util/u_hashset.h @@ -58,26 +58,16 @@ int u_hashset_destroy(struct u_hashset **hs); int -u_hashset_find_str(struct u_hashset *hs, - const char *str, - size_t length, - struct u_hashset_item **out_item); +u_hashset_find_str(struct u_hashset *hs, const char *str, size_t length, struct u_hashset_item **out_item); int -u_hashset_find_c_str(struct u_hashset *hs, - const char *c_str, - struct u_hashset_item **out_item); +u_hashset_find_c_str(struct u_hashset *hs, const char *c_str, struct u_hashset_item **out_item); int -u_hashset_create_and_insert_str(struct u_hashset *hs, - const char *str, - size_t length, - struct u_hashset_item **out_item); +u_hashset_create_and_insert_str(struct u_hashset *hs, const char *str, size_t length, struct u_hashset_item **out_item); int -u_hashset_create_and_insert_str_c(struct u_hashset *hs, - const char *c_str, - struct u_hashset_item **out_item); +u_hashset_create_and_insert_str_c(struct u_hashset *hs, const char *c_str, struct u_hashset_item **out_item); int u_hashset_insert_item(struct u_hashset *hs, struct u_hashset_item *item); @@ -98,9 +88,7 @@ u_hashset_erase_c_str(struct u_hashset *hs, const char *c_str); * @ingroup aux_util */ void -u_hashset_clear_and_call_for_each(struct u_hashset *hs, - u_hashset_callback cb, - void *priv); +u_hashset_clear_and_call_for_each(struct u_hashset *hs, u_hashset_callback cb, void *priv); #ifdef __cplusplus diff --git a/src/xrt/auxiliary/util/u_json.c b/src/xrt/auxiliary/util/u_json.c index 30105d1a9..a8a595cc8 100644 --- a/src/xrt/auxiliary/util/u_json.c +++ b/src/xrt/auxiliary/util/u_json.c @@ -224,9 +224,7 @@ u_json_get_quat(const cJSON *json, struct xrt_quat *out_quat) } size_t -u_json_get_float_array(const cJSON *json_array, - float *out_array, - size_t max_size) +u_json_get_float_array(const cJSON *json_array, float *out_array, size_t max_size) { assert(out_array != NULL); @@ -259,9 +257,7 @@ u_json_get_float_array(const cJSON *json_array, } size_t -u_json_get_double_array(const cJSON *json_array, - double *out_array, - size_t max_size) +u_json_get_double_array(const cJSON *json_array, double *out_array, size_t max_size) { assert(out_array != NULL); diff --git a/src/xrt/auxiliary/util/u_json.h b/src/xrt/auxiliary/util/u_json.h index fc73628a0..55306e83b 100644 --- a/src/xrt/auxiliary/util/u_json.h +++ b/src/xrt/auxiliary/util/u_json.h @@ -99,9 +99,7 @@ u_json_get_quat(const cJSON *json, struct xrt_quat *out_quat); * @return the number of elements set. */ size_t -u_json_get_float_array(const cJSON *json_array, - float *out_array, - size_t max_size); +u_json_get_float_array(const cJSON *json_array, float *out_array, size_t max_size); /*! * @brief Parse up to max_size doubles from a JSON array. @@ -109,9 +107,7 @@ u_json_get_float_array(const cJSON *json_array, * @return the number of elements set. */ size_t -u_json_get_double_array(const cJSON *json_array, - double *out_array, - size_t max_size); +u_json_get_double_array(const cJSON *json_array, double *out_array, size_t max_size); /*! * @brief Parse a matrix_3x3 from a JSON object. diff --git a/src/xrt/auxiliary/util/u_logging.c b/src/xrt/auxiliary/util/u_logging.c index be8806064..fb6f33c1c 100644 --- a/src/xrt/auxiliary/util/u_logging.c +++ b/src/xrt/auxiliary/util/u_logging.c @@ -51,12 +51,7 @@ u_log_convert_priority(enum u_logging_level level) return ANDROID_LOG_INFO; } void -u_log(const char *file, - int line, - const char *func, - enum u_logging_level level, - const char *format, - ...) +u_log(const char *file, int line, const char *func, enum u_logging_level level, const char *format, ...) { _log_level_init(); // print_prefix(func, level); @@ -90,46 +85,27 @@ u_log_xdev(const char *file, #include static int -print_prefix(int remainingBuf, - char *buf, - const char *func, - enum u_logging_level level) +print_prefix(int remainingBuf, char *buf, const char *func, enum u_logging_level level) { int printed = 0; switch (level) { - case U_LOGGING_TRACE: - printed = sprintf_s(buf, remainingBuf, "TRACE "); - break; - case U_LOGGING_DEBUG: - printed = sprintf_s(buf, remainingBuf, "DEBUG "); - break; - case U_LOGGING_INFO: - printed = sprintf_s(buf, remainingBuf, " INFO "); - break; - case U_LOGGING_WARN: - printed = sprintf_s(buf, remainingBuf, " WARN "); - break; - case U_LOGGING_ERROR: - printed = sprintf_s(buf, remainingBuf, "ERROR "); - break; + case U_LOGGING_TRACE: printed = sprintf_s(buf, remainingBuf, "TRACE "); break; + case U_LOGGING_DEBUG: printed = sprintf_s(buf, remainingBuf, "DEBUG "); break; + case U_LOGGING_INFO: printed = sprintf_s(buf, remainingBuf, " INFO "); break; + case U_LOGGING_WARN: printed = sprintf_s(buf, remainingBuf, " WARN "); break; + case U_LOGGING_ERROR: printed = sprintf_s(buf, remainingBuf, "ERROR "); break; case U_LOGGING_RAW: break; default: break; } if (level != U_LOGGING_RAW && func != NULL) { - printed = sprintf_s(buf + printed, remainingBuf - printed, - "[%s] ", func); + printed = sprintf_s(buf + printed, remainingBuf - printed, "[%s] ", func); } return printed; } void -u_log(const char *file, - int line, - const char *func, - enum u_logging_level level, - const char *format, - ...) +u_log(const char *file, int line, const char *func, enum u_logging_level level, const char *format, ...) { _log_level_init(); @@ -140,8 +116,7 @@ u_log(const char *file, va_list args; va_start(args, format); - printed += - vsprintf_s(buf + printed, remainingBuffer - printed, format, args); + printed += vsprintf_s(buf + printed, remainingBuffer - printed, format, args); va_end(args); *(buf + printed) = '\n'; OutputDebugStringA(buf); @@ -194,21 +169,11 @@ static void print_prefix_color(const char *func, enum u_logging_level level) { switch (level) { - case U_LOGGING_TRACE: - fprintf(stderr, COLOR_TRACE "TRACE " COLOR_RESET); - break; - case U_LOGGING_DEBUG: - fprintf(stderr, COLOR_DEBUG "DEBUG " COLOR_RESET); - break; - case U_LOGGING_INFO: - fprintf(stderr, COLOR_INFO " INFO " COLOR_RESET); - break; - case U_LOGGING_WARN: - fprintf(stderr, COLOR_WARN " WARN " COLOR_RESET); - break; - case U_LOGGING_ERROR: - fprintf(stderr, COLOR_ERROR "ERROR " COLOR_RESET); - break; + case U_LOGGING_TRACE: fprintf(stderr, COLOR_TRACE "TRACE " COLOR_RESET); break; + case U_LOGGING_DEBUG: fprintf(stderr, COLOR_DEBUG "DEBUG " COLOR_RESET); break; + case U_LOGGING_INFO: fprintf(stderr, COLOR_INFO " INFO " COLOR_RESET); break; + case U_LOGGING_WARN: fprintf(stderr, COLOR_WARN " WARN " COLOR_RESET); break; + case U_LOGGING_ERROR: fprintf(stderr, COLOR_ERROR "ERROR " COLOR_RESET); break; case U_LOGGING_RAW: break; default: break; } @@ -255,12 +220,7 @@ print_prefix(const char *func, enum u_logging_level level) */ void -u_log(const char *file, - int line, - const char *func, - enum u_logging_level level, - const char *format, - ...) +u_log(const char *file, int line, const char *func, enum u_logging_level level, const char *format, ...) { _log_level_init(); diff --git a/src/xrt/auxiliary/util/u_logging.h b/src/xrt/auxiliary/util/u_logging.h index 14b2770b5..dd9e46fbd 100644 --- a/src/xrt/auxiliary/util/u_logging.h +++ b/src/xrt/auxiliary/util/u_logging.h @@ -34,37 +34,33 @@ struct xrt_device; /*! * For places where you really just want printf, prints a new-line. */ -#define U_LOG_RAW(...) \ - do { \ - u_log(__FILE__, __LINE__, __func__, U_LOGGING_RAW, \ - __VA_ARGS__); \ +#define U_LOG_RAW(...) \ + do { \ + u_log(__FILE__, __LINE__, __func__, U_LOGGING_RAW, __VA_ARGS__); \ } while (false) -#define U_LOG(level, ...) \ - do { \ - u_log(__FILE__, __LINE__, __func__, level, __VA_ARGS__); \ +#define U_LOG(level, ...) \ + do { \ + u_log(__FILE__, __LINE__, __func__, level, __VA_ARGS__); \ } while (false) -#define U_LOG_IFL(level, cond_level, ...) \ - do { \ - if (cond_level <= level) { \ - u_log(__FILE__, __LINE__, __func__, level, \ - __VA_ARGS__); \ - } \ +#define U_LOG_IFL(level, cond_level, ...) \ + do { \ + if (cond_level <= level) { \ + u_log(__FILE__, __LINE__, __func__, level, __VA_ARGS__); \ + } \ } while (false) -#define U_LOG_XDEV(level, xdev, ...) \ - do { \ - u_log_xdev(__FILE__, __LINE__, __func__, level, xdev, \ - __VA_ARGS__); \ +#define U_LOG_XDEV(level, xdev, ...) \ + do { \ + u_log_xdev(__FILE__, __LINE__, __func__, level, xdev, __VA_ARGS__); \ } while (false) -#define U_LOG_XDEV_IFL(level, cond_level, xdev, ...) \ - do { \ - if (cond_level <= level) { \ - u_log_xdev(__FILE__, __LINE__, __func__, level, xdev, \ - __VA_ARGS__); \ - } \ +#define U_LOG_XDEV_IFL(level, cond_level, xdev, ...) \ + do { \ + if (cond_level <= level) { \ + u_log_xdev(__FILE__, __LINE__, __func__, level, xdev, __VA_ARGS__); \ + } \ } while (false) // clang-format off @@ -106,12 +102,8 @@ enum u_logging_level extern enum u_logging_level global_log_level; void -u_log(const char *file, - int line, - const char *func, - enum u_logging_level level, - const char *format, - ...) XRT_PRINTF_FORMAT(5, 6); +u_log(const char *file, int line, const char *func, enum u_logging_level level, const char *format, ...) + XRT_PRINTF_FORMAT(5, 6); void u_log_xdev(const char *file, diff --git a/src/xrt/auxiliary/util/u_misc.h b/src/xrt/auxiliary/util/u_misc.h index e48141500..d4f3187a2 100644 --- a/src/xrt/auxiliary/util/u_misc.h +++ b/src/xrt/auxiliary/util/u_misc.h @@ -55,8 +55,7 @@ extern "C" { * * @ingroup aux_util */ -#define U_TYPED_ARRAY_CALLOC(TYPE, COUNT) \ - ((TYPE *)calloc((COUNT), sizeof(TYPE))) +#define U_TYPED_ARRAY_CALLOC(TYPE, COUNT) ((TYPE *)calloc((COUNT), sizeof(TYPE))) /*! * Zeroes the correct amount of memory based on the type pointed-to by the @@ -111,8 +110,7 @@ u_realloc_or_free(void *ptr, size_t new_size) * * @ingroup aux_util */ -#define U_ARRAY_REALLOC_OR_FREE(VAR, TYPE, COUNT) \ - (VAR) = ((TYPE *)u_realloc_or_free((VAR), sizeof(TYPE) * (COUNT))) +#define U_ARRAY_REALLOC_OR_FREE(VAR, TYPE, COUNT) (VAR) = ((TYPE *)u_realloc_or_free((VAR), sizeof(TYPE) * (COUNT))) #ifdef __cplusplus } diff --git a/src/xrt/auxiliary/util/u_render_timing.c b/src/xrt/auxiliary/util/u_render_timing.c index 5b8f8ac79..762868f95 100644 --- a/src/xrt/auxiliary/util/u_render_timing.c +++ b/src/xrt/auxiliary/util/u_render_timing.c @@ -25,14 +25,13 @@ #if 0 #define DEBUG_PRINT_FRAME_ID() U_LOG_RAW("%" PRIi64 " %s", frame_id, __func__) #else -#define DEBUG_PRINT_FRAME_ID() \ - do { \ +#define DEBUG_PRINT_FRAME_ID() \ + do { \ } while (false) #endif static uint64_t -get_last_input_plus_period_at_least_greater_then(struct u_rt_helper *urth, - uint64_t then_ns) +get_last_input_plus_period_at_least_greater_then(struct u_rt_helper *urth, uint64_t then_ns) { uint64_t val = urth->last_input; @@ -92,8 +91,7 @@ u_rt_helper_predict(struct u_rt_helper *urth, at_least_ns = urth->last_returned; } - uint64_t predict_ns = - get_last_input_plus_period_at_least_greater_then(urth, at_least_ns); + uint64_t predict_ns = get_last_input_plus_period_at_least_greater_then(urth, at_least_ns); urth->last_returned = predict_ns; @@ -144,8 +142,7 @@ u_rt_helper_mark_discarded(struct u_rt_helper *urth, int64_t frame_id) size_t index = (uint64_t)frame_id % ARRAY_SIZE(urth->frames); assert(urth->frames[index].frame_id == frame_id); - assert(urth->frames[index].state == U_RT_WAIT_LEFT || - urth->frames[index].state == U_RT_BEGUN); + assert(urth->frames[index].state == U_RT_WAIT_LEFT || urth->frames[index].state == U_RT_BEGUN); urth->frames[index].end_frame = os_monotonic_get_ns(); urth->frames[index].state = U_RT_READY; @@ -177,10 +174,7 @@ u_rt_helper_mark_delivered(struct u_rt_helper *urth, int64_t frame_id) } void -u_rt_helper_new_sample(struct u_rt_helper *urth, - uint64_t predict, - uint64_t extra, - uint64_t min_period) +u_rt_helper_new_sample(struct u_rt_helper *urth, uint64_t predict, uint64_t extra, uint64_t min_period) { urth->last_input = predict; urth->extra = extra; diff --git a/src/xrt/auxiliary/util/u_render_timing.h b/src/xrt/auxiliary/util/u_render_timing.h index 6b12c1071..aaf3ed12e 100644 --- a/src/xrt/auxiliary/util/u_render_timing.h +++ b/src/xrt/auxiliary/util/u_render_timing.h @@ -80,10 +80,7 @@ void u_rt_helper_mark_delivered(struct u_rt_helper *urth, int64_t frame_id); void -u_rt_helper_new_sample(struct u_rt_helper *urth, - uint64_t predict, - uint64_t extra, - uint64_t min_period); +u_rt_helper_new_sample(struct u_rt_helper *urth, uint64_t predict, uint64_t extra, uint64_t min_period); #ifdef __cplusplus diff --git a/src/xrt/auxiliary/util/u_sink_converter.c b/src/xrt/auxiliary/util/u_sink_converter.c index 34fa7e480..2437fb2ad 100644 --- a/src/xrt/auxiliary/util/u_sink_converter.c +++ b/src/xrt/auxiliary/util/u_sink_converter.c @@ -94,8 +94,7 @@ generate_lookup_YUV_to_RGBX() for (y = 0; y < 256; y++) { for (u = 0; u < 256; u++) { for (v = 0; v < 256; v++) { - lookup_YUV_to_RGBX[y][u][v] = - YUV444_to_RGBX8888(y, u, v); + lookup_YUV_to_RGBX[y][u][v] = YUV444_to_RGBX8888(y, u, v); } } } @@ -191,11 +190,7 @@ YUV444_to_R8G8B8(const uint8_t *input, uint8_t *dst) } static void -from_YUYV422_to_R8G8B8(struct xrt_frame *dst_frame, - uint32_t w, - uint32_t h, - size_t stride, - const uint8_t *data) +from_YUYV422_to_R8G8B8(struct xrt_frame *dst_frame, uint32_t w, uint32_t h, size_t stride, const uint8_t *data) { for (uint32_t y = 0; y < h; y++) { for (uint32_t x = 0; x < w; x += 2) { @@ -210,11 +205,7 @@ from_YUYV422_to_R8G8B8(struct xrt_frame *dst_frame, } static void -from_UYVY422_to_R8G8B8(struct xrt_frame *dst_frame, - uint32_t w, - uint32_t h, - size_t stride, - const uint8_t *data) +from_UYVY422_to_R8G8B8(struct xrt_frame *dst_frame, uint32_t w, uint32_t h, size_t stride, const uint8_t *data) { for (uint32_t y = 0; y < h; y++) { for (uint32_t x = 0; x < w; x += 2) { @@ -230,11 +221,7 @@ from_UYVY422_to_R8G8B8(struct xrt_frame *dst_frame, static void -from_YUV888_to_R8G8B8(struct xrt_frame *dst_frame, - uint32_t w, - uint32_t h, - size_t stride, - const uint8_t *data) +from_YUV888_to_R8G8B8(struct xrt_frame *dst_frame, uint32_t w, uint32_t h, size_t stride, const uint8_t *data) { for (uint32_t y = 0; y < h; y++) { for (uint32_t x = 0; x < w; x++) { @@ -273,9 +260,7 @@ check_header(size_t size, const uint8_t *data) } static bool -from_MJPEG_to_R8G8B8(struct xrt_frame *dst_frame, - size_t size, - const uint8_t *data) +from_MJPEG_to_R8G8B8(struct xrt_frame *dst_frame, size_t size, const uint8_t *data) { if (!check_header(size, data)) { return false; @@ -315,9 +300,7 @@ from_MJPEG_to_R8G8B8(struct xrt_frame *dst_frame, } static bool -from_MJPEG_to_YUV888(struct xrt_frame *dst_frame, - size_t size, - const uint8_t *data) +from_MJPEG_to_YUV888(struct xrt_frame *dst_frame, size_t size, const uint8_t *data) { if (!check_header(size, data)) { return false; @@ -371,9 +354,7 @@ from_MJPEG_to_YUV888(struct xrt_frame *dst_frame, * @todo Allocate from a pool of frames. */ static bool -create_frame_with_format(struct xrt_frame *xf, - enum xrt_format format, - struct xrt_frame **out_frame) +create_frame_with_format(struct xrt_frame *xf, enum xrt_format format, struct xrt_frame **out_frame) { struct xrt_frame *frame = NULL; u_frame_create_one_off(format, xf->width, xf->height, &frame); @@ -403,37 +384,28 @@ receive_frame_r8g8b8_or_l8(struct xrt_frame_sink *xs, struct xrt_frame *xf) switch (xf->format) { case XRT_FORMAT_L8: - case XRT_FORMAT_R8G8B8: - s->downstream->push_frame(s->downstream, xf); - return; + case XRT_FORMAT_R8G8B8: s->downstream->push_frame(s->downstream, xf); return; case XRT_FORMAT_YUYV422: - if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, &converted)) { return; } - from_YUYV422_to_R8G8B8(converted, xf->width, xf->height, - xf->stride, xf->data); + from_YUYV422_to_R8G8B8(converted, xf->width, xf->height, xf->stride, xf->data); break; case XRT_FORMAT_UYVY422: - if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, &converted)) { return; } - from_UYVY422_to_R8G8B8(converted, xf->width, xf->height, - xf->stride, xf->data); + from_UYVY422_to_R8G8B8(converted, xf->width, xf->height, xf->stride, xf->data); break; case XRT_FORMAT_YUV888: - if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, &converted)) { return; } - from_YUV888_to_R8G8B8(converted, xf->width, xf->height, - xf->stride, xf->data); + from_YUV888_to_R8G8B8(converted, xf->width, xf->height, xf->stride, xf->data); break; #ifdef XRT_HAVE_JPEG case XRT_FORMAT_MJPEG: - if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, &converted)) { return; } if (!from_MJPEG_to_R8G8B8(converted, xf->size, xf->data)) { @@ -441,10 +413,7 @@ receive_frame_r8g8b8_or_l8(struct xrt_frame_sink *xs, struct xrt_frame *xf) } break; #endif - default: - U_LOG_E("Can not convert from '%s' to R8G8B8 or L8!", - u_format_str(xf->format)); - return; + default: U_LOG_E("Can not convert from '%s' to R8G8B8 or L8!", u_format_str(xf->format)); return; } s->downstream->push_frame(s->downstream, converted); @@ -461,37 +430,28 @@ receive_frame_r8g8b8(struct xrt_frame_sink *xs, struct xrt_frame *xf) struct xrt_frame *converted = NULL; switch (xf->format) { - case XRT_FORMAT_R8G8B8: - s->downstream->push_frame(s->downstream, xf); - return; + case XRT_FORMAT_R8G8B8: s->downstream->push_frame(s->downstream, xf); return; case XRT_FORMAT_YUYV422: - if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, &converted)) { return; } - from_YUYV422_to_R8G8B8(converted, xf->width, xf->height, - xf->stride, xf->data); + from_YUYV422_to_R8G8B8(converted, xf->width, xf->height, xf->stride, xf->data); break; case XRT_FORMAT_UYVY422: - if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, &converted)) { return; } - from_UYVY422_to_R8G8B8(converted, xf->width, xf->height, - xf->stride, xf->data); + from_UYVY422_to_R8G8B8(converted, xf->width, xf->height, xf->stride, xf->data); break; case XRT_FORMAT_YUV888: - if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, &converted)) { return; } - from_YUV888_to_R8G8B8(converted, xf->width, xf->height, - xf->stride, xf->data); + from_YUV888_to_R8G8B8(converted, xf->width, xf->height, xf->stride, xf->data); break; #ifdef XRT_HAVE_JPEG case XRT_FORMAT_MJPEG: - if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_R8G8B8, &converted)) { return; } if (!from_MJPEG_to_R8G8B8(converted, xf->size, xf->data)) { @@ -499,10 +459,7 @@ receive_frame_r8g8b8(struct xrt_frame_sink *xs, struct xrt_frame *xf) } break; #endif - default: - U_LOG_E("Can not convert from '%s' to R8G8B8!", - u_format_str(xf->format)); - return; + default: U_LOG_E("Can not convert from '%s' to R8G8B8!", u_format_str(xf->format)); return; } s->downstream->push_frame(s->downstream, converted); @@ -512,8 +469,7 @@ receive_frame_r8g8b8(struct xrt_frame_sink *xs, struct xrt_frame *xf) } static void -receive_frame_yuv_yuyv_uyvy_or_l8(struct xrt_frame_sink *xs, - struct xrt_frame *xf) +receive_frame_yuv_yuyv_uyvy_or_l8(struct xrt_frame_sink *xs, struct xrt_frame *xf) { struct u_sink_converter *s = (struct u_sink_converter *)xs; @@ -523,13 +479,10 @@ receive_frame_yuv_yuyv_uyvy_or_l8(struct xrt_frame_sink *xs, case XRT_FORMAT_L8: case XRT_FORMAT_YUYV422: case XRT_FORMAT_UYVY422: - case XRT_FORMAT_YUV888: - s->downstream->push_frame(s->downstream, xf); - return; + case XRT_FORMAT_YUV888: s->downstream->push_frame(s->downstream, xf); return; #ifdef XRT_HAVE_JPEG case XRT_FORMAT_MJPEG: - if (!create_frame_with_format(xf, XRT_FORMAT_YUV888, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_YUV888, &converted)) { return; } if (!from_MJPEG_to_YUV888(converted, xf->size, xf->data)) { @@ -560,13 +513,10 @@ receive_frame_yuv_or_yuyv(struct xrt_frame_sink *xs, struct xrt_frame *xf) switch (xf->format) { case XRT_FORMAT_YUYV422: - case XRT_FORMAT_YUV888: - s->downstream->push_frame(s->downstream, xf); - return; + case XRT_FORMAT_YUV888: s->downstream->push_frame(s->downstream, xf); return; #ifdef XRT_HAVE_JPEG case XRT_FORMAT_MJPEG: - if (!create_frame_with_format(xf, XRT_FORMAT_YUV888, - &converted)) { + if (!create_frame_with_format(xf, XRT_FORMAT_YUV888, &converted)) { return; } if (!from_MJPEG_to_YUV888(converted, xf->size, xf->data)) { @@ -574,10 +524,7 @@ receive_frame_yuv_or_yuyv(struct xrt_frame_sink *xs, struct xrt_frame *xf) } break; #endif - default: - U_LOG_E("Can not convert from '%s' to either YUV or YUYV!", - u_format_str(xf->format)); - return; + default: U_LOG_E("Can not convert from '%s' to either YUV or YUYV!", u_format_str(xf->format)); return; } s->downstream->push_frame(s->downstream, converted); @@ -593,8 +540,7 @@ break_apart(struct xrt_frame_node *node) static void destroy(struct xrt_frame_node *node) { - struct u_sink_converter *s = - container_of(node, struct u_sink_converter, node); + struct u_sink_converter *s = container_of(node, struct u_sink_converter, node); free(s); } diff --git a/src/xrt/auxiliary/util/u_sink_deinterleaver.c b/src/xrt/auxiliary/util/u_sink_deinterleaver.c index fea39507d..f00fc2dd0 100644 --- a/src/xrt/auxiliary/util/u_sink_deinterleaver.c +++ b/src/xrt/auxiliary/util/u_sink_deinterleaver.c @@ -41,11 +41,7 @@ L8_interleaved_to_L8(const uint8_t *input, uint8_t *l8a, uint8_t *l8b) } static void -from_L8_interleaved_to_L8(struct xrt_frame *frame, - uint32_t w, - uint32_t h, - size_t stride, - const uint8_t *data) +from_L8_interleaved_to_L8(struct xrt_frame *frame, uint32_t w, uint32_t h, size_t stride, const uint8_t *data) { uint32_t half_w = w / 2; @@ -117,8 +113,7 @@ break_apart(struct xrt_frame_node *node) static void destroy(struct xrt_frame_node *node) { - struct u_sink_deinterleaver *de = - container_of(node, struct u_sink_deinterleaver, node); + struct u_sink_deinterleaver *de = container_of(node, struct u_sink_deinterleaver, node); free(de); } @@ -135,8 +130,7 @@ u_sink_deinterleaver_create(struct xrt_frame_context *xfctx, struct xrt_frame_sink *downstream, struct xrt_frame_sink **out_xfs) { - struct u_sink_deinterleaver *de = - U_TYPED_CALLOC(struct u_sink_deinterleaver); + struct u_sink_deinterleaver *de = U_TYPED_CALLOC(struct u_sink_deinterleaver); de->base.push_frame = deinterleaves_frame; de->node.break_apart = break_apart; diff --git a/src/xrt/auxiliary/util/u_sink_queue.c b/src/xrt/auxiliary/util/u_sink_queue.c index 8e68c1dd1..54da53336 100644 --- a/src/xrt/auxiliary/util/u_sink_queue.c +++ b/src/xrt/auxiliary/util/u_sink_queue.c @@ -157,9 +157,7 @@ destroy(struct xrt_frame_node *node) */ bool -u_sink_queue_create(struct xrt_frame_context *xfctx, - struct xrt_frame_sink *downstream, - struct xrt_frame_sink **out_xfs) +u_sink_queue_create(struct xrt_frame_context *xfctx, struct xrt_frame_sink *downstream, struct xrt_frame_sink **out_xfs) { struct u_sink_queue *q = U_TYPED_CALLOC(struct u_sink_queue); int ret = 0; diff --git a/src/xrt/auxiliary/util/u_threading.h b/src/xrt/auxiliary/util/u_threading.h index 6a50f2888..892502c9d 100644 --- a/src/xrt/auxiliary/util/u_threading.h +++ b/src/xrt/auxiliary/util/u_threading.h @@ -41,8 +41,7 @@ u_threading_stack_push(struct u_threading_stack *uts, void *ptr) if (uts->num + 1 > uts->length) { uts->length += 8; - uts->arr = - (void **)realloc(uts->arr, uts->length * sizeof(void *)); + uts->arr = (void **)realloc(uts->arr, uts->length * sizeof(void *)); } uts->arr[uts->num++] = ptr; diff --git a/src/xrt/auxiliary/util/u_time.cpp b/src/xrt/auxiliary/util/u_time.cpp index 0cc466c06..acfdd2771 100644 --- a/src/xrt/auxiliary/util/u_time.cpp +++ b/src/xrt/auxiliary/util/u_time.cpp @@ -76,9 +76,7 @@ time_state_get_now_and_update(struct time_state *state) } extern "C" void -time_state_to_timespec(struct time_state const *state, - timepoint_ns timestamp, - struct timespec *out) +time_state_to_timespec(struct time_state const *state, timepoint_ns timestamp, struct timespec *out) { assert(state != NULL); assert(out != NULL); @@ -90,8 +88,7 @@ time_state_to_timespec(struct time_state const *state, } extern "C" timepoint_ns -time_state_from_timespec(struct time_state const *state, - const struct timespec *timespecTime) +time_state_from_timespec(struct time_state const *state, const struct timespec *timespecTime) { assert(state != NULL); assert(timespecTime != NULL); @@ -104,8 +101,7 @@ time_state_from_timespec(struct time_state const *state, } extern "C" timepoint_ns -time_state_monotonic_to_ts_ns(struct time_state const *state, - uint64_t monotonic_ns) +time_state_monotonic_to_ts_ns(struct time_state const *state, uint64_t monotonic_ns) { assert(state != NULL); @@ -113,8 +109,7 @@ time_state_monotonic_to_ts_ns(struct time_state const *state, } extern "C" uint64_t -time_state_ts_to_monotonic_ns(struct time_state const *state, - timepoint_ns timestamp) +time_state_ts_to_monotonic_ns(struct time_state const *state, timepoint_ns timestamp) { assert(state != NULL); diff --git a/src/xrt/auxiliary/util/u_time.h b/src/xrt/auxiliary/util/u_time.h index dcf10c1a9..9a2ccb156 100644 --- a/src/xrt/auxiliary/util/u_time.h +++ b/src/xrt/auxiliary/util/u_time.h @@ -143,9 +143,7 @@ time_state_get_now_and_update(struct time_state *state); * @ingroup aux_util */ void -time_state_to_timespec(struct time_state const *state, - timepoint_ns timestamp, - struct timespec *out); +time_state_to_timespec(struct time_state const *state, timepoint_ns timestamp, struct timespec *out); /*! * Convert a struct timespec (system time) to an integer timestamp. @@ -156,8 +154,7 @@ time_state_to_timespec(struct time_state const *state, * @ingroup aux_util */ timepoint_ns -time_state_from_timespec(struct time_state const *state, - const struct timespec *timespecTime); +time_state_from_timespec(struct time_state const *state, const struct timespec *timespecTime); /*! * Convert a monotonic system time (such as from @ref aux_os_time) to an @@ -172,8 +169,7 @@ time_state_from_timespec(struct time_state const *state, * @ingroup aux_util */ timepoint_ns -time_state_monotonic_to_ts_ns(struct time_state const *state, - uint64_t monotonic_ns); +time_state_monotonic_to_ts_ns(struct time_state const *state, uint64_t monotonic_ns); /*! * Convert a adjusted integer timestamp to an monotonic system time (such as @@ -185,8 +181,7 @@ time_state_monotonic_to_ts_ns(struct time_state const *state, * @ingroup aux_util */ uint64_t -time_state_ts_to_monotonic_ns(struct time_state const *state, - timepoint_ns timestamp); +time_state_ts_to_monotonic_ns(struct time_state const *state, timepoint_ns timestamp); #ifdef __cplusplus diff --git a/src/xrt/auxiliary/util/u_var.cpp b/src/xrt/auxiliary/util/u_var.cpp index 62b7f6bc6..890e8276f 100644 --- a/src/xrt/auxiliary/util/u_var.cpp +++ b/src/xrt/auxiliary/util/u_var.cpp @@ -147,10 +147,7 @@ u_var_remove_root(void *root) } extern "C" void -u_var_visit(u_var_root_cb enter_cb, - u_var_root_cb exit_cb, - u_var_elm_cb elem_cb, - void *priv) +u_var_visit(u_var_root_cb enter_cb, u_var_root_cb exit_cb, u_var_elm_cb elem_cb, void *priv) { if (!get_on()) { return; @@ -174,14 +171,13 @@ u_var_visit(u_var_root_cb enter_cb, } } -#define ADD_FUNC(SUFFIX, TYPE, ENUM) \ - extern "C" void u_var_add_##SUFFIX(void *obj, TYPE *ptr, \ - const char *c_name) \ - { \ - if (!get_on()) { \ - return; \ - } \ - add_var(obj, (void *)ptr, U_VAR_KIND_##ENUM, c_name); \ +#define ADD_FUNC(SUFFIX, TYPE, ENUM) \ + extern "C" void u_var_add_##SUFFIX(void *obj, TYPE *ptr, const char *c_name) \ + { \ + if (!get_on()) { \ + return; \ + } \ + add_var(obj, (void *)ptr, U_VAR_KIND_##ENUM, c_name); \ } U_VAR_ADD_FUNCS() diff --git a/src/xrt/auxiliary/util/u_var.h b/src/xrt/auxiliary/util/u_var.h index 0bce29b4b..1915a8099 100644 --- a/src/xrt/auxiliary/util/u_var.h +++ b/src/xrt/auxiliary/util/u_var.h @@ -153,10 +153,7 @@ u_var_remove_root(void *root); * Visit all root nodes and their variables. */ void -u_var_visit(u_var_root_cb enter_cb, - u_var_root_cb exit_cb, - u_var_elm_cb elem_cb, - void *priv); +u_var_visit(u_var_root_cb enter_cb, u_var_root_cb exit_cb, u_var_elm_cb elem_cb, void *priv); /*! * This forces the variable tracking code to on, it is disabled by default. @@ -164,36 +161,35 @@ u_var_visit(u_var_root_cb enter_cb, void u_var_force_on(void); -#define U_VAR_ADD_FUNCS() \ - ADD_FUNC(bool, bool, BOOL) \ - ADD_FUNC(rgb_u8, struct xrt_colour_rgb_u8, RGB_U8) \ - ADD_FUNC(rgb_f32, struct xrt_colour_rgb_f32, RGB_F32) \ - ADD_FUNC(u8, uint8_t, U8) \ - ADD_FUNC(i32, int32_t, I32) \ - ADD_FUNC(f32, float, F32) \ - ADD_FUNC(f32_arr, struct u_var_f32_arr, F32_ARR) \ - ADD_FUNC(f32_timing, struct u_var_timing, TIMING) \ - ADD_FUNC(vec3_i32, struct xrt_vec3_i32, VEC3_I32) \ - ADD_FUNC(vec3_f32, struct xrt_vec3, VEC3_F32) \ - ADD_FUNC(pose, struct xrt_pose, POSE) \ - ADD_FUNC(sink, struct xrt_frame_sink *, SINK) \ - ADD_FUNC(log_level, enum u_logging_level, LOG_LEVEL) \ - ADD_FUNC(ro_text, const char, RO_TEXT) \ - ADD_FUNC(ro_i32, int32_t, RO_I32) \ - ADD_FUNC(ro_u32, uint32_t, RO_I32) \ - ADD_FUNC(ro_f32, float, RO_F32) \ - ADD_FUNC(ro_i64, int64_t, RO_I64) \ - ADD_FUNC(ro_u64, uint64_t, RO_U64) \ - ADD_FUNC(ro_f64, double, RO_F64) \ - ADD_FUNC(ro_vec3_i32, struct xrt_vec3_i32, RO_VEC3_I32) \ - ADD_FUNC(ro_vec3_f32, struct xrt_vec3, RO_VEC3_F32) \ - ADD_FUNC(ro_quat_f32, struct xrt_quat, RO_QUAT_F32) \ - ADD_FUNC(ro_ff_f64, struct m_ff_f64, RO_FF_F64) \ - ADD_FUNC(ro_ff_vec3_f32, struct m_ff_vec3_f32, RO_FF_VEC3_F32) \ +#define U_VAR_ADD_FUNCS() \ + ADD_FUNC(bool, bool, BOOL) \ + ADD_FUNC(rgb_u8, struct xrt_colour_rgb_u8, RGB_U8) \ + ADD_FUNC(rgb_f32, struct xrt_colour_rgb_f32, RGB_F32) \ + ADD_FUNC(u8, uint8_t, U8) \ + ADD_FUNC(i32, int32_t, I32) \ + ADD_FUNC(f32, float, F32) \ + ADD_FUNC(f32_arr, struct u_var_f32_arr, F32_ARR) \ + ADD_FUNC(f32_timing, struct u_var_timing, TIMING) \ + ADD_FUNC(vec3_i32, struct xrt_vec3_i32, VEC3_I32) \ + ADD_FUNC(vec3_f32, struct xrt_vec3, VEC3_F32) \ + ADD_FUNC(pose, struct xrt_pose, POSE) \ + ADD_FUNC(sink, struct xrt_frame_sink *, SINK) \ + ADD_FUNC(log_level, enum u_logging_level, LOG_LEVEL) \ + ADD_FUNC(ro_text, const char, RO_TEXT) \ + ADD_FUNC(ro_i32, int32_t, RO_I32) \ + ADD_FUNC(ro_u32, uint32_t, RO_I32) \ + ADD_FUNC(ro_f32, float, RO_F32) \ + ADD_FUNC(ro_i64, int64_t, RO_I64) \ + ADD_FUNC(ro_u64, uint64_t, RO_U64) \ + ADD_FUNC(ro_f64, double, RO_F64) \ + ADD_FUNC(ro_vec3_i32, struct xrt_vec3_i32, RO_VEC3_I32) \ + ADD_FUNC(ro_vec3_f32, struct xrt_vec3, RO_VEC3_F32) \ + ADD_FUNC(ro_quat_f32, struct xrt_quat, RO_QUAT_F32) \ + ADD_FUNC(ro_ff_f64, struct m_ff_f64, RO_FF_F64) \ + ADD_FUNC(ro_ff_vec3_f32, struct m_ff_vec3_f32, RO_FF_VEC3_F32) \ ADD_FUNC(gui_header, bool, GUI_HEADER) -#define ADD_FUNC(SUFFIX, TYPE, ENUM) \ - void u_var_add_##SUFFIX(void *, TYPE *, const char *); +#define ADD_FUNC(SUFFIX, TYPE, ENUM) void u_var_add_##SUFFIX(void *, TYPE *, const char *); U_VAR_ADD_FUNCS() diff --git a/src/xrt/auxiliary/vk/vk_helpers.c b/src/xrt/auxiliary/vk/vk_helpers.c index 9ae3bfc39..35820fb98 100644 --- a/src/xrt/auxiliary/vk/vk_helpers.c +++ b/src/xrt/auxiliary/vk/vk_helpers.c @@ -26,7 +26,7 @@ * */ -#define ENUM_TO_STR(r) \ +#define ENUM_TO_STR(r) \ case r: return #r const char * @@ -154,8 +154,7 @@ bool vk_has_error(VkResult res, const char *fun, const char *file, int line) { if (res != VK_SUCCESS) { - U_LOG_E("%s failed with %s in %s:%d", fun, - vk_result_string(res), file, line); + U_LOG_E("%s failed with %s in %s:%d", fun, vk_result_string(res), file, line); return true; } return false; @@ -168,15 +167,11 @@ vk_has_error(VkResult res, const char *fun, const char *file, int line) */ bool -vk_get_memory_type(struct vk_bundle *vk, - uint32_t type_bits, - VkMemoryPropertyFlags memory_props, - uint32_t *out_type_id) +vk_get_memory_type(struct vk_bundle *vk, uint32_t type_bits, VkMemoryPropertyFlags memory_props, uint32_t *out_type_id) { for (uint32_t i = 0; i < vk->device_memory_props.memoryTypeCount; i++) { - uint32_t propertyFlags = - vk->device_memory_props.memoryTypes[i].propertyFlags; + uint32_t propertyFlags = vk->device_memory_props.memoryTypes[i].propertyFlags; if ((type_bits & 1) == 1) { if ((propertyFlags & memory_props) == memory_props) { *out_type_id = i; @@ -200,15 +195,13 @@ vk_alloc_and_bind_image_memory(struct vk_bundle *vk, VkDeviceSize *out_size) { VkMemoryRequirements memory_requirements; - vk->vkGetImageMemoryRequirements(vk->device, image, - &memory_requirements); + vk->vkGetImageMemoryRequirements(vk->device, image, &memory_requirements); if (max_size > 0 && memory_requirements.size > max_size) { VK_ERROR(vk, "client_vk_swapchain - Got too little memory " "%u vs %u\n", - (uint32_t)memory_requirements.size, - (uint32_t)max_size); + (uint32_t)memory_requirements.size, (uint32_t)max_size); return VK_ERROR_OUT_OF_DEVICE_MEMORY; } if (out_size != NULL) { @@ -216,8 +209,7 @@ vk_alloc_and_bind_image_memory(struct vk_bundle *vk, } uint32_t memory_type_index = UINT32_MAX; - if (!vk_get_memory_type(vk, memory_requirements.memoryTypeBits, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + if (!vk_get_memory_type(vk, memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_type_index)) { VK_ERROR(vk, "vk_get_memory_type failed!"); return VK_ERROR_OUT_OF_DEVICE_MEMORY; @@ -231,8 +223,7 @@ vk_alloc_and_bind_image_memory(struct vk_bundle *vk, }; VkDeviceMemory device_memory = VK_NULL_HANDLE; - VkResult ret = - vk->vkAllocateMemory(vk->device, &alloc_info, NULL, &device_memory); + VkResult ret = vk->vkAllocateMemory(vk->device, &alloc_info, NULL, &device_memory); if (ret != VK_SUCCESS) { VK_ERROR(vk, "vkAllocateMemory: %s", vk_result_string(ret)); return ret; @@ -288,8 +279,7 @@ vk_create_image_simple(struct vk_bundle *vk, return ret; } - ret = vk_alloc_and_bind_image_memory(vk, image, SIZE_MAX, NULL, out_mem, - NULL); + ret = vk_alloc_and_bind_image_memory(vk, image, SIZE_MAX, NULL, out_mem, NULL); if (ret != VK_SUCCESS) { // Clean up image vk->vkDestroyImage(vk->device, image, NULL); @@ -307,8 +297,7 @@ vk_create_image_from_native(struct vk_bundle *vk, VkImage *out_image, VkDeviceMemory *out_mem) { - VkImageUsageFlags image_usage = - vk_swapchain_usage_flags(vk, (VkFormat)info->format, info->bits); + VkImageUsageFlags image_usage = vk_swapchain_usage_flags(vk, (VkFormat)info->format, info->bits); if (image_usage == 0) { U_LOG_E( "vk_create_image_from_native: Unsupported swapchain usage " @@ -327,8 +316,7 @@ vk_create_image_from_native(struct vk_bundle *vk, #elif defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_AHARDWAREBUFFER) VkExternalMemoryImageCreateInfoKHR external_memory_image_create_info = { .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR, - .handleTypes = - VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, + .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, }; #elif defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_WIN32_HANDLE) VkExternalMemoryImageCreateInfoKHR external_memory_image_create_info = { @@ -344,9 +332,7 @@ vk_create_image_from_native(struct vk_bundle *vk, .pNext = &external_memory_image_create_info, .imageType = VK_IMAGE_TYPE_2D, .format = (VkFormat)info->format, - .extent = {.width = info->width, - .height = info->height, - .depth = 1}, + .extent = {.width = info->width, .height = info->height, .depth = 1}, .mipLevels = info->mip_count, .arrayLayers = info->array_size, .samples = VK_SAMPLE_COUNT_1_BIT, @@ -370,8 +356,7 @@ vk_create_image_from_native(struct vk_bundle *vk, }; #elif defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_AHARDWAREBUFFER) VkImportAndroidHardwareBufferInfoANDROID import_memory_info = { - .sType = - VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, + .sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .pNext = NULL, .buffer = image_native->handle, }; @@ -391,9 +376,7 @@ vk_create_image_from_native(struct vk_bundle *vk, .image = image, .buffer = VK_NULL_HANDLE, }; - ret = vk_alloc_and_bind_image_memory(vk, image, image_native->size, - &dedicated_memory_info, out_mem, - NULL); + ret = vk_alloc_and_bind_image_memory(vk, image, image_native->size, &dedicated_memory_info, out_mem, NULL); // We have consumed this fd now, make sure it's not freed again. image_native->handle = XRT_GRAPHICS_BUFFER_HANDLE_INVALID; @@ -408,17 +391,14 @@ vk_create_image_from_native(struct vk_bundle *vk, } VkResult -vk_create_semaphore_from_native(struct vk_bundle *vk, - xrt_graphics_sync_handle_t native, - VkSemaphore *out_sem) +vk_create_semaphore_from_native(struct vk_bundle *vk, xrt_graphics_sync_handle_t native, VkSemaphore *out_sem) { VkResult ret; VkSemaphoreCreateInfo semaphore_create_info = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, }; - ret = vk->vkCreateSemaphore(vk->device, &semaphore_create_info, NULL, - out_sem); + ret = vk->vkCreateSemaphore(vk->device, &semaphore_create_info, NULL, out_sem); if (ret != VK_SUCCESS) { VK_ERROR(vk, "vkCreateSemaphore: %s", vk_result_string(ret)); // Nothing to cleanup @@ -433,8 +413,7 @@ vk_create_semaphore_from_native(struct vk_bundle *vk, }; ret = vk->vkImportSemaphoreFdKHR(vk->device, &import_semaphore_fd_info); if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkImportSemaphoreFdKHR: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkImportSemaphoreFdKHR: %s", vk_result_string(ret)); vk->vkDestroySemaphore(vk->device, *out_sem, NULL); return ret; } @@ -445,11 +424,9 @@ vk_create_semaphore_from_native(struct vk_bundle *vk, .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT, .handle = native, }; - ret = vk->vkImportSemaphoreWin32HandleKHR( - vk->device, &import_semaphore_handle_info); + ret = vk->vkImportSemaphoreWin32HandleKHR(vk->device, &import_semaphore_handle_info); if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkImportSemaphoreWin32HandleKHR: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkImportSemaphoreWin32HandleKHR: %s", vk_result_string(ret)); vk->vkDestroySemaphore(vk->device, *out_sem, NULL); return ret; } @@ -460,9 +437,7 @@ vk_create_semaphore_from_native(struct vk_bundle *vk, } VkResult -vk_create_sampler(struct vk_bundle *vk, - VkSamplerAddressMode clamp_mode, - VkSampler *out_sampler) +vk_create_sampler(struct vk_bundle *vk, VkSamplerAddressMode clamp_mode, VkSampler *out_sampler) { VkSampler sampler; VkResult ret; @@ -504,8 +479,7 @@ vk_create_view(struct vk_bundle *vk, .a = VK_COMPONENT_SWIZZLE_A, }; - return vk_create_view_swizzle(vk, image, format, subresource_range, - components, out_view); + return vk_create_view_swizzle(vk, image, format, subresource_range, components, out_view); } VkResult @@ -562,14 +536,12 @@ vk_init_cmd_buffer(struct vk_bundle *vk, VkCommandBuffer *out_cmd_buffer) os_mutex_lock(&vk->cmd_pool_mutex); - ret = vk->vkAllocateCommandBuffers(vk->device, &cmd_buffer_info, - &cmd_buffer); + ret = vk->vkAllocateCommandBuffers(vk->device, &cmd_buffer_info, &cmd_buffer); os_mutex_unlock(&vk->cmd_pool_mutex); if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkAllocateCommandBuffers: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkAllocateCommandBuffers: %s", vk_result_string(ret)); // Nothing to cleanup return ret; } @@ -622,9 +594,8 @@ vk_set_image_layout(struct vk_bundle *vk, }; os_mutex_lock(&vk->cmd_pool_mutex); - vk->vkCmdPipelineBarrier(cmd_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, NULL, - 0, NULL, 1, &barrier); + vk->vkCmdPipelineBarrier(cmd_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, + 0, NULL, 0, NULL, 1, &barrier); os_mutex_unlock(&vk->cmd_pool_mutex); return VK_SUCCESS; @@ -696,8 +667,7 @@ vk_init_cmd_pool(struct vk_bundle *vk) }; VkResult ret; - ret = vk->vkCreateCommandPool(vk->device, &cmd_pool_info, NULL, - &vk->cmd_pool); + ret = vk->vkCreateCommandPool(vk->device, &cmd_pool_info, NULL, &vk->cmd_pool); if (ret != VK_SUCCESS) { VK_ERROR(vk, "vkCreateCommandPool: %s", vk_result_string(ret)); } @@ -713,11 +683,9 @@ vk_init_cmd_pool(struct vk_bundle *vk) #define GET_PROC(vk, name) (PFN_##name) vk->vkGetInstanceProcAddr(NULL, #name); -#define GET_INS_PROC(vk, name) \ - (PFN_##name) vk->vkGetInstanceProcAddr(vk->instance, #name); +#define GET_INS_PROC(vk, name) (PFN_##name) vk->vkGetInstanceProcAddr(vk->instance, #name); -#define GET_DEV_PROC(vk, name) \ - (PFN_##name) vk->vkGetDeviceProcAddr(vk->device, #name); +#define GET_DEV_PROC(vk, name) (PFN_##name) vk->vkGetDeviceProcAddr(vk->device, #name); VkResult vk_get_loader_functions(struct vk_bundle *vk, PFN_vkGetInstanceProcAddr g) @@ -883,10 +851,7 @@ vk_get_device_functions(struct vk_bundle *vk) static void -vk_print_device_info_debug(struct vk_bundle *vk, - VkPhysicalDeviceProperties *pdp, - uint32_t gpu_index, - const char *title) +vk_print_device_info_debug(struct vk_bundle *vk, VkPhysicalDeviceProperties *pdp, uint32_t gpu_index, const char *title) { VK_DEBUG(vk, "%s" @@ -895,12 +860,9 @@ vk_print_device_info_debug(struct vk_bundle *vk, "\tproduct: 0x%04x\n" "\tapiVersion: %u.%u.%u\n" "\tdriverVersion: %u.%u.%u", - title, pdp->deviceName, pdp->vendorID, pdp->deviceID, - VK_VERSION_MAJOR(pdp->apiVersion), - VK_VERSION_MINOR(pdp->apiVersion), - VK_VERSION_PATCH(pdp->apiVersion), - VK_VERSION_MAJOR(pdp->driverVersion), - VK_VERSION_MINOR(pdp->driverVersion), + title, pdp->deviceName, pdp->vendorID, pdp->deviceID, VK_VERSION_MAJOR(pdp->apiVersion), + VK_VERSION_MINOR(pdp->apiVersion), VK_VERSION_PATCH(pdp->apiVersion), + VK_VERSION_MAJOR(pdp->driverVersion), VK_VERSION_MINOR(pdp->driverVersion), VK_VERSION_PATCH(pdp->driverVersion)); } @@ -917,11 +879,9 @@ vk_select_physical_device(struct vk_bundle *vk, int forced_index) uint32_t gpu_count = ARRAY_SIZE(physical_devices); VkResult ret; - ret = vk->vkEnumeratePhysicalDevices(vk->instance, &gpu_count, - physical_devices); + ret = vk->vkEnumeratePhysicalDevices(vk->instance, &gpu_count, physical_devices); if (ret != VK_SUCCESS) { - VK_DEBUG(vk, "vkEnumeratePhysicalDevices: %s", - vk_result_string(ret)); + VK_DEBUG(vk, "vkEnumeratePhysicalDevices: %s", vk_result_string(ret)); return ret; } @@ -945,23 +905,20 @@ vk_select_physical_device(struct vk_bundle *vk, int forced_index) return VK_ERROR_DEVICE_LOST; } gpu_index = forced_index; - VK_DEBUG(vk, "Forced use of Vulkan device index %d.", - gpu_index); + VK_DEBUG(vk, "Forced use of Vulkan device index %d.", gpu_index); } else { VK_DEBUG(vk, "Available GPUs"); // as a first-step to 'intelligent' selection, prefer a // 'discrete' gpu if it is present for (uint32_t i = 0; i < gpu_count; i++) { VkPhysicalDeviceProperties pdp; - vk->vkGetPhysicalDeviceProperties(physical_devices[i], - &pdp); + vk->vkGetPhysicalDeviceProperties(physical_devices[i], &pdp); char title[20]; snprintf(title, 20, "GPU index %d\n", i); vk_print_device_info_debug(vk, &pdp, i, title); - if (pdp.deviceType == - VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { + if (pdp.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { gpu_index = i; } } @@ -978,8 +935,7 @@ vk_select_physical_device(struct vk_bundle *vk, int forced_index) vk_print_device_info_debug(vk, &pdp, gpu_index, title); // Fill out the device memory props as well. - vk->vkGetPhysicalDeviceMemoryProperties(vk->physical_device, - &vk->device_memory_props); + vk->vkGetPhysicalDeviceMemoryProperties(vk->physical_device, &vk->device_memory_props); return VK_SUCCESS; } @@ -990,14 +946,11 @@ vk_find_graphics_queue(struct vk_bundle *vk, uint32_t *out_graphics_queue) /* Find the first graphics queue */ uint32_t num_queues = 0; uint32_t i = 0; - vk->vkGetPhysicalDeviceQueueFamilyProperties(vk->physical_device, - &num_queues, NULL); + vk->vkGetPhysicalDeviceQueueFamilyProperties(vk->physical_device, &num_queues, NULL); - VkQueueFamilyProperties *queue_family_props = - U_TYPED_ARRAY_CALLOC(VkQueueFamilyProperties, num_queues); + VkQueueFamilyProperties *queue_family_props = U_TYPED_ARRAY_CALLOC(VkQueueFamilyProperties, num_queues); - vk->vkGetPhysicalDeviceQueueFamilyProperties( - vk->physical_device, &num_queues, queue_family_props); + vk->vkGetPhysicalDeviceQueueFamilyProperties(vk->physical_device, &num_queues, queue_family_props); if (num_queues == 0) { VK_DEBUG(vk, "Failed to get queue properties"); @@ -1027,17 +980,12 @@ err_free: } static bool -vk_check_extension(struct vk_bundle *vk, - VkExtensionProperties *props, - uint32_t num_props, - const char *ext) +vk_check_extension(struct vk_bundle *vk, VkExtensionProperties *props, uint32_t num_props, const char *ext) { for (uint32_t i = 0; i < num_props; i++) { if (strcmp(props[i].extensionName, ext) == 0) { - if (strcmp(ext, - VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME) == - 0) { + if (strcmp(ext, VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME) == 0) { vk->has_GOOGLE_display_timing = true; } @@ -1054,16 +1002,13 @@ vk_get_device_ext_props(struct vk_bundle *vk, VkExtensionProperties **props, uint32_t *num_props) { - VkResult res = vk->vkEnumerateDeviceExtensionProperties( - physical_device, NULL, num_props, NULL); + VkResult res = vk->vkEnumerateDeviceExtensionProperties(physical_device, NULL, num_props, NULL); vk_check_error("vkEnumerateDeviceExtensionProperties", res, false); *props = U_TYPED_ARRAY_CALLOC(VkExtensionProperties, *num_props); - res = vk->vkEnumerateDeviceExtensionProperties(physical_device, NULL, - num_props, *props); - vk_check_error_with_free("vkEnumerateDeviceExtensionProperties", res, - false, props); + res = vk->vkEnumerateDeviceExtensionProperties(physical_device, NULL, num_props, *props); + vk_check_error_with_free("vkEnumerateDeviceExtensionProperties", res, false, props); return true; } @@ -1084,11 +1029,9 @@ vk_build_device_extensions(struct vk_bundle *vk, return false; } - int max_exts = - num_required_device_extensions + num_optional_device_extensions; + int max_exts = num_required_device_extensions + num_optional_device_extensions; - const char **device_extensions = - U_TYPED_ARRAY_CALLOC(const char *, max_exts); + const char **device_extensions = U_TYPED_ARRAY_CALLOC(const char *, max_exts); for (uint32_t i = 0; i < num_required_device_extensions; i++) { const char *ext = required_device_extensions[i]; @@ -1139,11 +1082,9 @@ vk_create_device(struct vk_bundle *vk, const char **device_extensions; size_t num_device_extensions; - if (!vk_build_device_extensions( - vk, vk->physical_device, required_device_extensions, - num_required_device_extensions, optional_device_extensions, - num_optional_device_extensions, &device_extensions, - &num_device_extensions)) { + if (!vk_build_device_extensions(vk, vk->physical_device, required_device_extensions, + num_required_device_extensions, optional_device_extensions, + num_optional_device_extensions, &device_extensions, &num_device_extensions)) { return VK_ERROR_EXTENSION_NOT_PRESENT; } @@ -1170,8 +1111,7 @@ vk_create_device(struct vk_bundle *vk, .pEnabledFeatures = enabled_features, }; - ret = vk->vkCreateDevice(vk->physical_device, &device_create_info, NULL, - &vk->device); + ret = vk->vkCreateDevice(vk->physical_device, &device_create_info, NULL, &vk->device); free(device_extensions); @@ -1227,8 +1167,7 @@ vk_init_from_given(struct vk_bundle *vk, // Fill out the device memory props here, as we are // passed a vulkan context and do not call selectPhysicalDevice() - vk->vkGetPhysicalDeviceMemoryProperties(vk->physical_device, - &vk->device_memory_props); + vk->vkGetPhysicalDeviceMemoryProperties(vk->physical_device, &vk->device_memory_props); // Fill in all device functions. ret = vk_get_device_functions(vk); @@ -1256,20 +1195,13 @@ vk_get_access_flags(VkImageLayout layout) { switch (layout) { case VK_IMAGE_LAYOUT_UNDEFINED: return 0; - case VK_IMAGE_LAYOUT_GENERAL: - return VK_ACCESS_TRANSFER_WRITE_BIT | - VK_ACCESS_TRANSFER_READ_BIT; + case VK_IMAGE_LAYOUT_GENERAL: return VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT; case VK_IMAGE_LAYOUT_PREINITIALIZED: return VK_ACCESS_HOST_WRITE_BIT; - case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: - return VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: - return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: - return VK_ACCESS_TRANSFER_READ_BIT; - case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: - return VK_ACCESS_TRANSFER_WRITE_BIT; - case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: - return VK_ACCESS_SHADER_READ_BIT; + case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: return VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: return VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: return VK_ACCESS_TRANSFER_READ_BIT; + case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: return VK_ACCESS_TRANSFER_WRITE_BIT; + case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: return VK_ACCESS_SHADER_READ_BIT; default: U_LOG_E("Unhandled access mask case for layout %d.", layout); } return 0; @@ -1316,69 +1248,56 @@ check_feature(VkFormat format, U_LOG_E( "vk_swapchain_usage_flags: %s requested but %s not " "supported for format %s (%08x) (%08x)", - xrt_swapchain_usage_string(usage), - vk_format_feature_string(flag), - vk_color_format_string(format), format_features, flag); + xrt_swapchain_usage_string(usage), vk_format_feature_string(flag), vk_color_format_string(format), + format_features, flag); return false; } return true; } VkImageUsageFlags -vk_swapchain_usage_flags(struct vk_bundle *vk, - VkFormat format, - enum xrt_swapchain_usage_bits bits) +vk_swapchain_usage_flags(struct vk_bundle *vk, VkFormat format, enum xrt_swapchain_usage_bits bits) { VkFormatProperties prop; - vk->vkGetPhysicalDeviceFormatProperties(vk->physical_device, format, - &prop); + vk->vkGetPhysicalDeviceFormatProperties(vk->physical_device, format, &prop); VkImageUsageFlags image_usage = 0; if ((bits & XRT_SWAPCHAIN_USAGE_DEPTH_STENCIL) != 0) { - if (!check_feature( - format, XRT_SWAPCHAIN_USAGE_DEPTH_STENCIL, - prop.optimalTilingFeatures, - VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) { + if (!check_feature(format, XRT_SWAPCHAIN_USAGE_DEPTH_STENCIL, prop.optimalTilingFeatures, + VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) { return 0; } - image_usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | - VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; + image_usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; } - if ((prop.optimalTilingFeatures & - VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0) { - image_usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | - VK_IMAGE_USAGE_SAMPLED_BIT; + if ((prop.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0) { + image_usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; } if ((bits & XRT_SWAPCHAIN_USAGE_COLOR) != 0) { - if (!check_feature(format, XRT_SWAPCHAIN_USAGE_COLOR, - prop.optimalTilingFeatures, + if (!check_feature(format, XRT_SWAPCHAIN_USAGE_COLOR, prop.optimalTilingFeatures, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) { return 0; } image_usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; } if ((bits & XRT_SWAPCHAIN_USAGE_TRANSFER_SRC) != 0) { - if (!check_feature(format, XRT_SWAPCHAIN_USAGE_TRANSFER_SRC, - prop.optimalTilingFeatures, + if (!check_feature(format, XRT_SWAPCHAIN_USAGE_TRANSFER_SRC, prop.optimalTilingFeatures, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT)) { return 0; } image_usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; } if ((bits & XRT_SWAPCHAIN_USAGE_TRANSFER_DST) != 0) { - if (!check_feature(format, XRT_SWAPCHAIN_USAGE_TRANSFER_DST, - prop.optimalTilingFeatures, + if (!check_feature(format, XRT_SWAPCHAIN_USAGE_TRANSFER_DST, prop.optimalTilingFeatures, VK_FORMAT_FEATURE_TRANSFER_DST_BIT)) { return 0; } image_usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; } if ((bits & XRT_SWAPCHAIN_USAGE_SAMPLED) != 0) { - if (!check_feature(format, XRT_SWAPCHAIN_USAGE_SAMPLED, - prop.optimalTilingFeatures, + if (!check_feature(format, XRT_SWAPCHAIN_USAGE_SAMPLED, prop.optimalTilingFeatures, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { return 0; } @@ -1405,8 +1324,7 @@ vk_init_descriptor_pool(struct vk_bundle *vk, .pPoolSizes = pool_sizes, }; - VkResult res = vk->vkCreateDescriptorPool(vk->device, &info, NULL, - out_descriptor_pool); + VkResult res = vk->vkCreateDescriptorPool(vk->device, &info, NULL, out_descriptor_pool); vk_check_error("vkCreateDescriptorPool", res, false); return true; @@ -1426,8 +1344,7 @@ vk_allocate_descriptor_sets(struct vk_bundle *vk, .pSetLayouts = set_layout, }; - VkResult res = - vk->vkAllocateDescriptorSets(vk->device, &alloc_info, sets); + VkResult res = vk->vkAllocateDescriptorSets(vk->device, &alloc_info, sets); vk_check_error("vkAllocateDescriptorSets", res, false); return true; @@ -1447,22 +1364,17 @@ vk_buffer_init(struct vk_bundle *vk, .usage = usage, }; - VkResult res = - vk->vkCreateBuffer(vk->device, &buffer_info, NULL, out_buffer); + VkResult res = vk->vkCreateBuffer(vk->device, &buffer_info, NULL, out_buffer); vk_check_error("vkCreateBuffer", res, false); VkMemoryRequirements requirements; - vk->vkGetBufferMemoryRequirements(vk->device, *out_buffer, - &requirements); + vk->vkGetBufferMemoryRequirements(vk->device, *out_buffer, &requirements); - VkMemoryAllocateInfo alloc_info = { - .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - .allocationSize = requirements.size}; + VkMemoryAllocateInfo alloc_info = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = requirements.size}; - if (!vk_get_memory_type(vk, requirements.memoryTypeBits, properties, - &alloc_info.memoryTypeIndex)) { - VK_ERROR(vk, - "Failed to find matching memoryTypeIndex for buffer"); + if (!vk_get_memory_type(vk, requirements.memoryTypeBits, properties, &alloc_info.memoryTypeIndex)) { + VK_ERROR(vk, "Failed to find matching memoryTypeIndex for buffer"); return false; } @@ -1483,14 +1395,10 @@ vk_buffer_destroy(struct vk_buffer *self, struct vk_bundle *vk) } bool -vk_update_buffer(struct vk_bundle *vk, - float *buffer, - size_t buffer_size, - VkDeviceMemory memory) +vk_update_buffer(struct vk_bundle *vk, float *buffer, size_t buffer_size, VkDeviceMemory memory) { void *tmp; - VkResult res = - vk->vkMapMemory(vk->device, memory, 0, VK_WHOLE_SIZE, 0, &tmp); + VkResult res = vk->vkMapMemory(vk->device, memory, 0, VK_WHOLE_SIZE, 0, &tmp); vk_check_error("vkMapMemory", res, false); memcpy(tmp, buffer, buffer_size); @@ -1510,11 +1418,7 @@ vk_update_buffer(struct vk_bundle *vk, } VkResult -vk_locked_submit(struct vk_bundle *vk, - VkQueue queue, - uint32_t count, - const VkSubmitInfo *infos, - VkFence fence) +vk_locked_submit(struct vk_bundle *vk, VkQueue queue, uint32_t count, const VkSubmitInfo *infos, VkFence fence) { VkResult ret; os_mutex_lock(&vk->queue_mutex); diff --git a/src/xrt/auxiliary/vk/vk_helpers.h b/src/xrt/auxiliary/vk/vk_helpers.h index 94c00856a..e3e930bf2 100644 --- a/src/xrt/auxiliary/vk/vk_helpers.h +++ b/src/xrt/auxiliary/vk/vk_helpers.h @@ -265,14 +265,14 @@ vk_color_space_string(VkColorSpaceKHR code); bool vk_has_error(VkResult res, const char *fun, const char *file, int line); -#define vk_check_error(fun, res, ret) \ - if (vk_has_error(res, fun, __FILE__, __LINE__)) \ +#define vk_check_error(fun, res, ret) \ + if (vk_has_error(res, fun, __FILE__, __LINE__)) \ return ret -#define vk_check_error_with_free(fun, res, ret, to_free) \ - if (vk_has_error(res, fun, __FILE__, __LINE__)) { \ - free(to_free); \ - return ret; \ +#define vk_check_error_with_free(fun, res, ret, to_free) \ + if (vk_has_error(res, fun, __FILE__, __LINE__)) { \ + free(to_free); \ + return ret; \ } /*! @@ -323,10 +323,7 @@ vk_init_from_given(struct vk_bundle *vk, * @ingroup aux_vk */ bool -vk_get_memory_type(struct vk_bundle *vk, - uint32_t type_bits, - VkMemoryPropertyFlags memory_props, - uint32_t *out_type_id); +vk_get_memory_type(struct vk_bundle *vk, uint32_t type_bits, VkMemoryPropertyFlags memory_props, uint32_t *out_type_id); /*! * Allocate memory for an image and bind it to that image. @@ -382,9 +379,7 @@ vk_create_image_from_native(struct vk_bundle *vk, * @ingroup aux_vk */ VkResult -vk_create_semaphore_from_native(struct vk_bundle *vk, - xrt_graphics_sync_handle_t native, - VkSemaphore *out_sem); +vk_create_semaphore_from_native(struct vk_bundle *vk, xrt_graphics_sync_handle_t native, VkSemaphore *out_sem); /*! * @ingroup aux_vk @@ -401,9 +396,7 @@ vk_create_image_simple(struct vk_bundle *vk, * @ingroup aux_vk */ VkResult -vk_create_sampler(struct vk_bundle *vk, - VkSamplerAddressMode clamp_mode, - VkSampler *out_sampler); +vk_create_sampler(struct vk_bundle *vk, VkSamplerAddressMode clamp_mode, VkSampler *out_sampler); /*! * @ingroup aux_vk @@ -464,9 +457,7 @@ vk_swapchain_access_flags(enum xrt_swapchain_usage_bits bits); * compositor and client. */ VkImageUsageFlags -vk_swapchain_usage_flags(struct vk_bundle *vk, - VkFormat format, - enum xrt_swapchain_usage_bits bits); +vk_swapchain_usage_flags(struct vk_bundle *vk, VkFormat format, enum xrt_swapchain_usage_bits bits); bool vk_init_descriptor_pool(struct vk_bundle *vk, @@ -494,17 +485,10 @@ void vk_buffer_destroy(struct vk_buffer *self, struct vk_bundle *vk); bool -vk_update_buffer(struct vk_bundle *vk, - float *buffer, - size_t buffer_size, - VkDeviceMemory memory); +vk_update_buffer(struct vk_bundle *vk, float *buffer, size_t buffer_size, VkDeviceMemory memory); VkResult -vk_locked_submit(struct vk_bundle *vk, - VkQueue queue, - uint32_t count, - const VkSubmitInfo *infos, - VkFence fence); +vk_locked_submit(struct vk_bundle *vk, VkQueue queue, uint32_t count, const VkSubmitInfo *infos, VkFence fence); #ifdef __cplusplus } diff --git a/src/xrt/auxiliary/vk/vk_image_allocator.c b/src/xrt/auxiliary/vk/vk_image_allocator.c index 754d88025..d0e8c2a26 100644 --- a/src/xrt/auxiliary/vk/vk_image_allocator.c +++ b/src/xrt/auxiliary/vk/vk_image_allocator.c @@ -31,9 +31,7 @@ #if defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_FD) static VkResult -get_device_memory_handle(struct vk_bundle *vk, - VkDeviceMemory device_memory, - xrt_graphics_buffer_handle_t *out_handle) +get_device_memory_handle(struct vk_bundle *vk, VkDeviceMemory device_memory, xrt_graphics_buffer_handle_t *out_handle) { // vkGetMemoryFdKHR parameter VkMemoryGetFdInfoKHR fd_info = { @@ -58,21 +56,17 @@ get_device_memory_handle(struct vk_bundle *vk, #elif defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_AHARDWAREBUFFER) static VkResult -get_device_memory_handle(struct vk_bundle *vk, - VkDeviceMemory device_memory, - xrt_graphics_buffer_handle_t *out_handle) +get_device_memory_handle(struct vk_bundle *vk, VkDeviceMemory device_memory, xrt_graphics_buffer_handle_t *out_handle) { // vkGetMemoryAndroidHardwareBufferANDROID parameter VkMemoryGetAndroidHardwareBufferInfoANDROID ahb_info = { - .sType = - VK_STRUCTURE_TYPE_MEMORY_GET_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, + .sType = VK_STRUCTURE_TYPE_MEMORY_GET_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .pNext = NULL, .memory = device_memory, }; AHardwareBuffer *buf = NULL; - VkResult ret = vk->vkGetMemoryAndroidHardwareBufferANDROID( - vk->device, &ahb_info, &buf); + VkResult ret = vk->vkGetMemoryAndroidHardwareBufferANDROID(vk->device, &ahb_info, &buf); if (ret != VK_SUCCESS) { return ret; } @@ -85,9 +79,7 @@ get_device_memory_handle(struct vk_bundle *vk, #elif defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_WIN32_HANDLE) static VkResult -get_device_memory_handle(struct vk_bundle *vk, - VkDeviceMemory device_memory, - xrt_graphics_buffer_handle_t *out_handle) +get_device_memory_handle(struct vk_bundle *vk, VkDeviceMemory device_memory, xrt_graphics_buffer_handle_t *out_handle) { // vkGetMemoryWin32HandleKHR parameter VkMemoryGetWin32HandleInfoKHR win32_info = { @@ -98,8 +90,7 @@ get_device_memory_handle(struct vk_bundle *vk, }; HANDLE handle = NULL; - VkResult ret = - vk->vkGetMemoryWin32HandleKHR(vk->device, &win32_info, &handle); + VkResult ret = vk->vkGetMemoryWin32HandleKHR(vk->device, &win32_info, &handle); if (ret != VK_SUCCESS) { return ret; } @@ -113,12 +104,9 @@ get_device_memory_handle(struct vk_bundle *vk, #endif static VkResult -create_image(struct vk_bundle *vk, - const struct xrt_swapchain_create_info *info, - struct vk_image *out_image) +create_image(struct vk_bundle *vk, const struct xrt_swapchain_create_info *info, struct vk_image *out_image) { - VkImageUsageFlags image_usage = - vk_swapchain_usage_flags(vk, (VkFormat)info->format, info->bits); + VkImageUsageFlags image_usage = vk_swapchain_usage_flags(vk, (VkFormat)info->format, info->bits); if (image_usage == 0) { U_LOG_E("create_image: Unsupported swapchain usage flags"); return VK_ERROR_FEATURE_NOT_PRESENT; @@ -143,22 +131,18 @@ create_image(struct vk_bundle *vk, } VkAndroidHardwareBufferFormatPropertiesANDROID a_buffer_format_props = { - .sType = - VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID, + .sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID, .format = (VkFormat)info->format, }; VkAndroidHardwareBufferPropertiesANDROID a_buffer_props = { - .sType = - VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, + .sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &a_buffer_format_props, }; - ret = vk->vkGetAndroidHardwareBufferPropertiesANDROID( - vk->device, a_buffer, &a_buffer_props); + ret = vk->vkGetAndroidHardwareBufferPropertiesANDROID(vk->device, a_buffer, &a_buffer_props); if (ret != VK_SUCCESS) { - U_LOG_E("vkGetAndroidHardwareBufferPropertiesANDROID: %s", - vk_result_string(ret)); + U_LOG_E("vkGetAndroidHardwareBufferPropertiesANDROID: %s", vk_result_string(ret)); return ret; } #endif @@ -167,13 +151,12 @@ create_image(struct vk_bundle *vk, * Create the image. */ - VkExternalMemoryImageCreateInfoKHR external_memory_image_create_info = - {.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR, + VkExternalMemoryImageCreateInfoKHR external_memory_image_create_info = { + .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR, #if defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_AHARDWAREBUFFER) - .handleTypes = - VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, + .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, #else - .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR, + .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR, #endif }; @@ -192,23 +175,23 @@ create_image(struct vk_bundle *vk, } #endif - VkImageCreateInfo create_info = - {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + VkImageCreateInfo create_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, #if defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_AHARDWAREBUFFER) - .pNext = &format_android, + .pNext = &format_android, #else - .pNext = &external_memory_image_create_info, + .pNext = &external_memory_image_create_info, #endif - .imageType = VK_IMAGE_TYPE_2D, - .format = format, - .extent = {.width = info->width, .height = info->height, .depth = 1}, - .mipLevels = info->mip_count, - .arrayLayers = info->array_size, - .samples = VK_SAMPLE_COUNT_1_BIT, - .tiling = VK_IMAGE_TILING_OPTIMAL, - .usage = image_usage, - .sharingMode = VK_SHARING_MODE_EXCLUSIVE, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .imageType = VK_IMAGE_TYPE_2D, + .format = format, + .extent = {.width = info->width, .height = info->height, .depth = 1}, + .mipLevels = info->mip_count, + .arrayLayers = info->array_size, + .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = image_usage, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, }; ret = vk->vkCreateImage(vk->device, &create_info, NULL, &image); @@ -240,8 +223,7 @@ create_image(struct vk_bundle *vk, VkExportMemoryAllocateInfo export_alloc_info = { .sType = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR, .pNext = &dedicated_memory_info, - .handleTypes = - VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, + .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, }; #elif defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_WIN32_HANDLE) @@ -256,8 +238,7 @@ create_image(struct vk_bundle *vk, #error "need port" #endif - ret = vk_alloc_and_bind_image_memory( - vk, image, SIZE_MAX, &export_alloc_info, &device_memory, &size); + ret = vk_alloc_and_bind_image_memory(vk, image, SIZE_MAX, &export_alloc_info, &device_memory, &size); if (ret != VK_SUCCESS) { U_LOG_E("vkAllocateMemory: %s", vk_result_string(ret)); vk->vkDestroyImage(vk->device, image, NULL); @@ -352,11 +333,9 @@ vk_ic_from_natives(struct vk_bundle *vk, size_t i = 0; for (; i < num_images; i++) { // Ensure that all handles are consumed or none are. - xrt_graphics_buffer_handle_t buf = - u_graphics_buffer_ref(native_images[i].handle); + xrt_graphics_buffer_handle_t buf = u_graphics_buffer_ref(native_images[i].handle); - ret = vk_create_image_from_native(vk, xscci, &native_images[i], - &out_vkic->images[i].handle, + ret = vk_create_image_from_native(vk, xscci, &native_images[i], &out_vkic->images[i].handle, &out_vkic->images[i].memory); if (ret != VK_SUCCESS) { u_graphics_buffer_unref(&buf); @@ -410,8 +389,7 @@ vk_ic_get_handles(struct vk_bundle *vk, size_t i = 0; for (; i < vkic->num_images && i < max_handles; i++) { - ret = get_device_memory_handle(vk, vkic->images[i].memory, - &out_handles[i]); + ret = get_device_memory_handle(vk, vkic->images[i].memory, &out_handles[i]); if (ret != VK_SUCCESS) { break; } diff --git a/src/xrt/compositor/client/comp_egl_glue.c b/src/xrt/compositor/client/comp_egl_glue.c index 8fabeb946..7635d0b7c 100644 --- a/src/xrt/compositor/client/comp_egl_glue.c +++ b/src/xrt/compositor/client/comp_egl_glue.c @@ -44,16 +44,12 @@ DEBUG_GET_ONCE_LOG_OPTION(egl_log, "EGL_LOG", U_LOGGING_INFO) #ifdef XRT_OS_ANDROID -typedef const char * - EGLAPIENTRY (*PFNEGLQUERYSTRINGIMPLEMENTATIONANDROIDPROC)(EGLDisplay dpy, - EGLint name); +typedef const char *EGLAPIENTRY (*PFNEGLQUERYSTRINGIMPLEMENTATIONANDROIDPROC)(EGLDisplay dpy, EGLint name); #endif // Not forward declared by mesa -typedef EGLBoolean EGLAPIENTRY (*PFNEGLMAKECURRENTPROC)(EGLDisplay dpy, - EGLSurface draw, - EGLSurface read, - EGLContext ctx); +typedef EGLBoolean + EGLAPIENTRY (*PFNEGLMAKECURRENTPROC)(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); /*! * EGL based compositor. @@ -99,8 +95,7 @@ has_extension(const char *extensions, const char *ext) } terminator = loc + strlen(ext); - if ((loc == extensions || *(loc - 1) == ' ') && - (*terminator == ' ' || *terminator == '\0')) { + if ((loc == extensions || *(loc - 1) == ' ') && (*terminator == ' ' || *terminator == '\0')) { return true; } extensions = terminator; @@ -108,8 +103,7 @@ has_extension(const char *extensions, const char *ext) } static void -ensure_native_fence_is_loaded(EGLDisplay dpy, - PFNEGLGETPROCADDRESSPROC get_gl_procaddr) +ensure_native_fence_is_loaded(EGLDisplay dpy, PFNEGLGETPROCADDRESSPROC get_gl_procaddr) { #ifdef XRT_OS_ANDROID // clang-format off @@ -117,21 +111,18 @@ ensure_native_fence_is_loaded(EGLDisplay dpy, // clang-format on eglQueryStringImplementationANDROID = - (PFNEGLQUERYSTRINGIMPLEMENTATIONANDROIDPROC)get_gl_procaddr( - "eglQueryStringImplementationANDROID"); + (PFNEGLQUERYSTRINGIMPLEMENTATIONANDROIDPROC)get_gl_procaddr("eglQueryStringImplementationANDROID"); // On Android, EGL_ANDROID_native_fence_sync only shows up in this // extension list, not the normal one. - const char *ext = - eglQueryStringImplementationANDROID(dpy, EGL_EXTENSIONS); + const char *ext = eglQueryStringImplementationANDROID(dpy, EGL_EXTENSIONS); if (!has_extension(ext, "EGL_ANDROID_native_fence_sync")) { return; } GLAD_EGL_ANDROID_native_fence_sync = true; glad_eglDupNativeFenceFDANDROID = - (PFNEGLDUPNATIVEFENCEFDANDROIDPROC)get_gl_procaddr( - "eglDupNativeFenceFDANDROID"); + (PFNEGLDUPNATIVEFENCEFDANDROIDPROC)get_gl_procaddr("eglDupNativeFenceFDANDROID"); #endif } @@ -169,8 +160,7 @@ old_restore(struct old_helper *old) return; } - EGL_ERROR("Failed to make old EGL context current! (%p, %p, %p, %p)", - old->dpy, old->draw, old->read, old->ctx); + EGL_ERROR("Failed to make old EGL context current! (%p, %p, %p, %p)", old->dpy, old->draw, old->read, old->ctx); } @@ -194,8 +184,7 @@ insert_fence(struct xrt_compositor *xc, xrt_graphics_sync_handle_t *out_handle) #ifdef XRT_GRAPHICS_SYNC_HANDLE_IS_FD - EGLSyncKHR sync = - eglCreateSyncKHR(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL); + EGLSyncKHR sync = eglCreateSyncKHR(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL); if (sync == EGL_NO_SYNC_KHR) { EGL_ERROR("Failed to insert fence!"); return XRT_ERROR_FENCE_CREATE_FAILED; @@ -251,8 +240,7 @@ xrt_gfx_provider_create_gl_egl(struct xrt_compositor_native *xcn, } EGLint egl_client_type; - if (!eglQueryContext(display, context, EGL_CONTEXT_CLIENT_TYPE, - &egl_client_type)) { + if (!eglQueryContext(display, context, EGL_CONTEXT_CLIENT_TYPE, &egl_client_type)) { old_restore(&old); return NULL; } @@ -273,23 +261,20 @@ xrt_gfx_provider_create_gl_egl(struct xrt_compositor_native *xcn, gladLoadGLES2(get_gl_procaddr); break; #else - EGL_ERROR( - "OpenGL|ES support not including in this runtime build"); + EGL_ERROR("OpenGL|ES support not including in this runtime build"); old_restore(&old); return NULL; #endif default: EGL_ERROR("Unsupported EGL client type"); return NULL; } - struct client_egl_compositor *ceglc = - U_TYPED_CALLOC(struct client_egl_compositor); + struct client_egl_compositor *ceglc = U_TYPED_CALLOC(struct client_egl_compositor); ceglc->dpy = display; client_gl_swapchain_create_func sc_create = NULL; EGL_INFO("Extension availability:"); -#define DUMP_EXTENSION_STATUS(EXT) \ - EGL_INFO(" - " #EXT ": %s", GLAD_##EXT ? "true" : "false") +#define DUMP_EXTENSION_STATUS(EXT) EGL_INFO(" - " #EXT ": %s", GLAD_##EXT ? "true" : "false") DUMP_EXTENSION_STATUS(GL_EXT_memory_object); DUMP_EXTENSION_STATUS(GL_EXT_memory_object_fd); @@ -325,13 +310,11 @@ xrt_gfx_provider_create_gl_egl(struct xrt_compositor_native *xcn, return NULL; } #elif defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_AHARDWAREBUFFER) - EGL_INFO( - "Using EGL_Image swapchain implementation with AHardwareBuffer"); + EGL_INFO("Using EGL_Image swapchain implementation with AHardwareBuffer"); sc_create = client_gl_eglimage_swapchain_create; #endif - if (!client_gl_compositor_init(&ceglc->base, xcn, sc_create, - insert_fence)) { + if (!client_gl_compositor_init(&ceglc->base, xcn, sc_create, insert_fence)) { free(ceglc); U_LOG_E("Failed to initialize compositor"); old_restore(&old); diff --git a/src/xrt/compositor/client/comp_gl_client.c b/src/xrt/compositor/client/comp_gl_client.c index 16e429f98..babfbacb4 100644 --- a/src/xrt/compositor/client/comp_gl_client.c +++ b/src/xrt/compositor/client/comp_gl_client.c @@ -48,8 +48,7 @@ client_gl_swapchain(struct xrt_swapchain *xsc) */ static xrt_result_t -client_gl_swapchain_acquire_image(struct xrt_swapchain *xsc, - uint32_t *out_index) +client_gl_swapchain_acquire_image(struct xrt_swapchain *xsc, uint32_t *out_index) { struct client_gl_swapchain *sc = client_gl_swapchain(xsc); @@ -58,9 +57,7 @@ client_gl_swapchain_acquire_image(struct xrt_swapchain *xsc, } static xrt_result_t -client_gl_swapchain_wait_image(struct xrt_swapchain *xsc, - uint64_t timeout, - uint32_t index) +client_gl_swapchain_wait_image(struct xrt_swapchain *xsc, uint64_t timeout, uint32_t index) { struct client_gl_swapchain *sc = client_gl_swapchain(xsc); @@ -85,8 +82,7 @@ client_gl_swapchain_release_image(struct xrt_swapchain *xsc, uint32_t index) */ static xrt_result_t -client_gl_compositor_prepare_session( - struct xrt_compositor *xc, const struct xrt_session_prepare_info *xspi) +client_gl_compositor_prepare_session(struct xrt_compositor *xc, const struct xrt_session_prepare_info *xspi) { struct client_gl_compositor *c = client_gl_compositor(xc); @@ -96,8 +92,7 @@ client_gl_compositor_prepare_session( static xrt_result_t -client_gl_compositor_begin_session(struct xrt_compositor *xc, - enum xrt_view_type type) +client_gl_compositor_begin_session(struct xrt_compositor *xc, enum xrt_view_type type) { struct client_gl_compositor *c = client_gl_compositor(xc); @@ -123,9 +118,7 @@ client_gl_compositor_wait_frame(struct xrt_compositor *xc, struct client_gl_compositor *c = client_gl_compositor(xc); // Pipe down call into native compositor. - return xrt_comp_wait_frame(&c->xcn->base, out_frame_id, - predicted_display_time, - predicted_display_period); + return xrt_comp_wait_frame(&c->xcn->base, out_frame_id, predicted_display_time, predicted_display_period); } static xrt_result_t @@ -147,9 +140,7 @@ client_gl_compositor_discard_frame(struct xrt_compositor *xc, int64_t frame_id) } static xrt_result_t -client_gl_compositor_layer_begin(struct xrt_compositor *xc, - int64_t frame_id, - enum xrt_blend_mode env_blend_mode) +client_gl_compositor_layer_begin(struct xrt_compositor *xc, int64_t frame_id, enum xrt_blend_mode env_blend_mode) { struct client_gl_compositor *c = client_gl_compositor(xc); @@ -174,19 +165,17 @@ client_gl_compositor_layer_stereo_projection(struct xrt_compositor *xc, struct xrt_layer_data d = *data; d.flip_y = !d.flip_y; - return xrt_comp_layer_stereo_projection(&c->xcn->base, xdev, l_xscn, - r_xscn, &d); + return xrt_comp_layer_stereo_projection(&c->xcn->base, xdev, l_xscn, r_xscn, &d); } static xrt_result_t -client_gl_compositor_layer_stereo_projection_depth( - struct xrt_compositor *xc, - struct xrt_device *xdev, - struct xrt_swapchain *l_xsc, - struct xrt_swapchain *r_xsc, - struct xrt_swapchain *l_d_xsc, - struct xrt_swapchain *r_d_xsc, - const struct xrt_layer_data *data) +client_gl_compositor_layer_stereo_projection_depth(struct xrt_compositor *xc, + struct xrt_device *xdev, + struct xrt_swapchain *l_xsc, + struct xrt_swapchain *r_xsc, + struct xrt_swapchain *l_d_xsc, + struct xrt_swapchain *r_d_xsc, + const struct xrt_layer_data *data) { struct client_gl_compositor *c = client_gl_compositor(xc); struct xrt_swapchain *l_xscn, *r_xscn, *l_d_xscn, *r_d_xscn; @@ -201,8 +190,7 @@ client_gl_compositor_layer_stereo_projection_depth( struct xrt_layer_data d = *data; d.flip_y = !d.flip_y; - return xrt_comp_layer_stereo_projection_depth( - &c->xcn->base, xdev, l_xscn, r_xscn, l_d_xscn, r_d_xscn, &d); + return xrt_comp_layer_stereo_projection_depth(&c->xcn->base, xdev, l_xscn, r_xscn, l_d_xscn, r_d_xscn, &d); } static xrt_result_t @@ -301,9 +289,7 @@ client_gl_compositor_layer_equirect2(struct xrt_compositor *xc, } static xrt_result_t -client_gl_compositor_layer_commit(struct xrt_compositor *xc, - int64_t frame_id, - xrt_graphics_sync_handle_t sync_handle) +client_gl_compositor_layer_commit(struct xrt_compositor *xc, int64_t frame_id, xrt_graphics_sync_handle_t sync_handle) { struct client_gl_compositor *c = client_gl_compositor(xc); @@ -360,11 +346,7 @@ vk_format_to_gl(int64_t format) case 126 /*VK_FORMAT_D32_SFLOAT*/: return GL_DEPTH_COMPONENT32F; case 129 /*VK_FORMAT_D24_UNORM_S8_UINT*/: return GL_DEPTH24_STENCIL8; case 130 /*VK_FORMAT_D32_SFLOAT_S8_UINT*/: return GL_DEPTH32F_STENCIL8; - default: - U_LOG_W("Cannot convert VK format 0x%016" PRIx64 - " to GL format!\n", - format); - return 0; + default: U_LOG_W("Cannot convert VK format 0x%016" PRIx64 " to GL format!\n", format); return 0; } } @@ -407,8 +389,7 @@ client_gl_swapchain_create(struct xrt_compositor *xc, GLint prev_texture = 0; GLuint binding_enum = 0; GLuint tex_target = 0; - ogl_texture_target_for_swapchain_info(&xinfo, &tex_target, - &binding_enum); + ogl_texture_target_for_swapchain_info(&xinfo, &tex_target, &binding_enum); glGetIntegerv(binding_enum, &prev_texture); @@ -445,8 +426,7 @@ client_gl_swapchain_create(struct xrt_compositor *xc, } static xrt_result_t -client_gl_compositor_poll_events(struct xrt_compositor *xc, - union xrt_compositor_event *out_xce) +client_gl_compositor_poll_events(struct xrt_compositor *xc, union xrt_compositor_event *out_xce) { struct client_gl_compositor *c = client_gl_compositor(xc); @@ -474,10 +454,8 @@ client_gl_compositor_init(struct client_gl_compositor *c, c->base.base.begin_frame = client_gl_compositor_begin_frame; c->base.base.discard_frame = client_gl_compositor_discard_frame; c->base.base.layer_begin = client_gl_compositor_layer_begin; - c->base.base.layer_stereo_projection = - client_gl_compositor_layer_stereo_projection; - c->base.base.layer_stereo_projection_depth = - client_gl_compositor_layer_stereo_projection_depth; + c->base.base.layer_stereo_projection = client_gl_compositor_layer_stereo_projection; + c->base.base.layer_stereo_projection_depth = client_gl_compositor_layer_stereo_projection_depth; c->base.base.layer_quad = client_gl_compositor_layer_quad; c->base.base.layer_cube = client_gl_compositor_layer_cube; c->base.base.layer_cylinder = client_gl_compositor_layer_cylinder; diff --git a/src/xrt/compositor/client/comp_gl_client.h b/src/xrt/compositor/client/comp_gl_client.h index a7e1ef9c8..84742c6e0 100644 --- a/src/xrt/compositor/client/comp_gl_client.h +++ b/src/xrt/compositor/client/comp_gl_client.h @@ -56,11 +56,10 @@ struct client_gl_swapchain * - Must populate `destroy` * - Does not need to save/restore texture binding */ -typedef struct xrt_swapchain *(*client_gl_swapchain_create_func)( - struct xrt_compositor *xc, - const struct xrt_swapchain_create_info *info, - struct xrt_swapchain_native *xscn, - struct client_gl_swapchain **out_sc); +typedef struct xrt_swapchain *(*client_gl_swapchain_create_func)(struct xrt_compositor *xc, + const struct xrt_swapchain_create_info *info, + struct xrt_swapchain_native *xscn, + struct client_gl_swapchain **out_sc); /*! * The type of a fence insertion function. @@ -69,8 +68,7 @@ typedef struct xrt_swapchain *(*client_gl_swapchain_create_func)( * * The returned graphics sync handle is given to xrt_compositor::layer_commit. */ -typedef xrt_result_t (*client_gl_insert_fence_func)( - struct xrt_compositor *xc, xrt_graphics_sync_handle_t *out_handle); +typedef xrt_result_t (*client_gl_insert_fence_func)(struct xrt_compositor *xc, xrt_graphics_sync_handle_t *out_handle); /*! * @class client_gl_compositor diff --git a/src/xrt/compositor/client/comp_gl_eglimage_swapchain.c b/src/xrt/compositor/client/comp_gl_eglimage_swapchain.c index 080984ecb..977373c3c 100644 --- a/src/xrt/compositor/client/comp_gl_eglimage_swapchain.c +++ b/src/xrt/compositor/client/comp_gl_eglimage_swapchain.c @@ -40,9 +40,7 @@ static enum u_logging_level ll; #define EGL_SC_WARN(...) U_LOG_IFL_W(ll, __VA_ARGS__) #define EGL_SC_ERROR(...) U_LOG_IFL_E(ll, __VA_ARGS__) -DEBUG_GET_ONCE_LOG_OPTION(egl_swapchain_log, - "EGL_SWAPCHAIN_LOG", - U_LOGGING_WARN) +DEBUG_GET_ONCE_LOG_OPTION(egl_swapchain_log, "EGL_SWAPCHAIN_LOG", U_LOGGING_WARN) /*! @@ -63,8 +61,7 @@ client_gl_eglimage_swapchain(struct xrt_swapchain *xsc) // This is shared between "destroy" and an error cleanup static void -client_gl_eglimage_swapchain_teardown_storage( - struct client_gl_eglimage_swapchain *sc) +client_gl_eglimage_swapchain_teardown_storage(struct client_gl_eglimage_swapchain *sc) { uint32_t num_images = sc->base.base.base.num_images; if (num_images > 0) { @@ -72,8 +69,7 @@ client_gl_eglimage_swapchain_teardown_storage( U_ZERO_ARRAY(sc->base.base.images); for (uint32_t i = 0; i < num_images; ++i) { if (sc->egl_images[i] != NULL) { - eglDestroyImageKHR(sc->display, - &(sc->egl_images[i])); + eglDestroyImageKHR(sc->display, &(sc->egl_images[i])); } } U_ZERO_ARRAY(sc->egl_images); @@ -83,8 +79,7 @@ client_gl_eglimage_swapchain_teardown_storage( static void client_gl_eglimage_swapchain_destroy(struct xrt_swapchain *xsc) { - struct client_gl_eglimage_swapchain *sc = - client_gl_eglimage_swapchain(xsc); + struct client_gl_eglimage_swapchain *sc = client_gl_eglimage_swapchain(xsc); client_gl_eglimage_swapchain_teardown_storage(sc); sc->base.base.base.num_images = 0; @@ -103,31 +98,21 @@ client_gl_eglimage_swapchain_destroy(struct xrt_swapchain *xsc) * for the "source of truth" for this data. */ -#define XRT_FOURCC(A, B, C, D) \ - ((uint32_t)(A) | ((uint32_t)(B) << 8) | ((uint32_t)(C) << 16) | \ - ((uint32_t)(D) << 24)) +#define XRT_FOURCC(A, B, C, D) ((uint32_t)(A) | ((uint32_t)(B) << 8) | ((uint32_t)(C) << 16) | ((uint32_t)(D) << 24)) static inline uint32_t gl_format_to_drm_fourcc(uint64_t format) { switch (format) { - case GL_RGBA8: - return XRT_FOURCC('R', 'A', '2', '4'); /*DRM_FORMAT_RGBA8888*/ - case GL_SRGB8_ALPHA8: - return XRT_FOURCC('R', 'A', '2', '4'); /*DRM_FORMAT_RGBA8888*/ - case GL_RGB10_A2: - return XRT_FOURCC('A', 'B', '3', - '0'); /*DRM_FORMAT_ABGR2101010*/ + case GL_RGBA8: return XRT_FOURCC('R', 'A', '2', '4'); /*DRM_FORMAT_RGBA8888*/ + case GL_SRGB8_ALPHA8: return XRT_FOURCC('R', 'A', '2', '4'); /*DRM_FORMAT_RGBA8888*/ + case GL_RGB10_A2: return XRT_FOURCC('A', 'B', '3', '0'); /*DRM_FORMAT_ABGR2101010*/ #if 0 /* couldn't find a matching code? */ case GL_RGBA16F: #endif - default: - EGL_SC_ERROR("Cannot convert GL format 0x%08" PRIx64 - " to DRM FOURCC format!", - format); - return 0; + default: EGL_SC_ERROR("Cannot convert GL format 0x%08" PRIx64 " to DRM FOURCC format!", format); return 0; } } static inline uint32_t @@ -142,11 +127,7 @@ gl_format_to_bpp(uint64_t format) /* couldn't find a matching code? */ case GL_RGBA16F: #endif - default: - EGL_SC_ERROR("Cannot convert GL format 0x%08" PRIx64 - " to DRM FOURCC format!", - format); - return 0; + default: EGL_SC_ERROR("Cannot convert GL format 0x%08" PRIx64 " to DRM FOURCC format!", format); return 0; } } #endif // defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_FD) @@ -178,11 +159,10 @@ vk_format_to_srgb(uint64_t format) struct xrt_swapchain * -client_gl_eglimage_swapchain_create( - struct xrt_compositor *xc, - const struct xrt_swapchain_create_info *info, - struct xrt_swapchain_native *xscn, - struct client_gl_swapchain **out_sc) +client_gl_eglimage_swapchain_create(struct xrt_compositor *xc, + const struct xrt_swapchain_create_info *info, + struct xrt_swapchain_native *xscn, + struct client_gl_swapchain **out_sc) { ll = debug_get_log_option_egl_swapchain_log(); @@ -205,16 +185,14 @@ client_gl_eglimage_swapchain_create( // round up row_pitch += 1; } - EGL_SC_INFO("Computed row pitch is %" PRIu32 " bytes: %" PRIu32 - " bpp, %" PRIu32 " pixels wide", + EGL_SC_INFO("Computed row pitch is %" PRIu32 " bytes: %" PRIu32 " bpp, %" PRIu32 " pixels wide", row_pitch, bpp, info->width); } #endif // defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_FD) struct xrt_swapchain *native_xsc = &xscn->base; - struct client_gl_eglimage_swapchain *sc = - U_TYPED_CALLOC(struct client_gl_eglimage_swapchain); + struct client_gl_eglimage_swapchain *sc = U_TYPED_CALLOC(struct client_gl_eglimage_swapchain); struct xrt_swapchain_gl *xscgl = &sc->base.base; struct xrt_swapchain *client_xsc = &xscgl->base; client_xsc->destroy = client_gl_eglimage_swapchain_destroy; @@ -241,8 +219,7 @@ client_gl_eglimage_swapchain_create( #if defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_AHARDWAREBUFFER) // see // https://android.googlesource.com/platform/cts/+/master/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp - native_buffer = - eglGetNativeClientBufferANDROID(xscn->images[i].handle); + native_buffer = eglGetNativeClientBufferANDROID(xscn->images[i].handle); if (NULL == native_buffer) { EGL_SC_ERROR("eglGetNativeClientBufferANDROID failed"); @@ -251,11 +228,7 @@ client_gl_eglimage_swapchain_create( return NULL; } EGLint attrs[] = { - EGL_IMAGE_PRESERVED_KHR, - EGL_TRUE, - EGL_NONE, - EGL_NONE, - EGL_NONE, + EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE, EGL_NONE, EGL_NONE, }; if (vk_format_to_srgb(info->format)) { attrs[2] = EGL_GL_COLORSPACE_KHR; @@ -282,8 +255,7 @@ client_gl_eglimage_swapchain_create( #else #error "need port" #endif - sc->egl_images[i] = eglCreateImageKHR( - sc->display, EGL_NO_CONTEXT, source, native_buffer, attrs); + sc->egl_images[i] = eglCreateImageKHR(sc->display, EGL_NO_CONTEXT, source, native_buffer, attrs); if (EGL_NO_IMAGE_KHR == sc->egl_images[i]) { EGL_SC_ERROR("eglCreateImageKHR failed"); client_gl_eglimage_swapchain_teardown_storage(sc); @@ -297,14 +269,10 @@ client_gl_eglimage_swapchain_create( * Also, glEGLImageTargetTexStorageEXT was added in Android * platform 28, so fairly recently. */ - if (GLAD_GL_EXT_EGL_image_storage && - glEGLImageTargetTexStorageEXT) { - glEGLImageTargetTexStorageEXT(tex_target, - sc->egl_images[i], NULL); - } else if (GLAD_GL_OES_EGL_image_external || - GLAD_GL_OES_EGL_image_external_essl3) { - glEGLImageTargetTexture2DOES(tex_target, - sc->egl_images[i]); + if (GLAD_GL_EXT_EGL_image_storage && glEGLImageTargetTexStorageEXT) { + glEGLImageTargetTexStorageEXT(tex_target, sc->egl_images[i], NULL); + } else if (GLAD_GL_OES_EGL_image_external || GLAD_GL_OES_EGL_image_external_essl3) { + glEGLImageTargetTexture2DOES(tex_target, sc->egl_images[i]); } } diff --git a/src/xrt/compositor/client/comp_gl_eglimage_swapchain.h b/src/xrt/compositor/client/comp_gl_eglimage_swapchain.h index bceff8f50..a20b68be1 100644 --- a/src/xrt/compositor/client/comp_gl_eglimage_swapchain.h +++ b/src/xrt/compositor/client/comp_gl_eglimage_swapchain.h @@ -45,11 +45,10 @@ struct client_gl_eglimage_swapchain * This is used on Android and on desktop when the EGL extension is used. */ struct xrt_swapchain * -client_gl_eglimage_swapchain_create( - struct xrt_compositor *xc, - const struct xrt_swapchain_create_info *info, - struct xrt_swapchain_native *xscn, - struct client_gl_swapchain **out_sc); +client_gl_eglimage_swapchain_create(struct xrt_compositor *xc, + const struct xrt_swapchain_create_info *info, + struct xrt_swapchain_native *xscn, + struct client_gl_swapchain **out_sc); #ifdef __cplusplus } diff --git a/src/xrt/compositor/client/comp_gl_memobj_swapchain.c b/src/xrt/compositor/client/comp_gl_memobj_swapchain.c index b9159904c..8e4a060b6 100644 --- a/src/xrt/compositor/client/comp_gl_memobj_swapchain.c +++ b/src/xrt/compositor/client/comp_gl_memobj_swapchain.c @@ -79,8 +79,7 @@ client_gl_memobj_swapchain_create(struct xrt_compositor *xc, ogl_texture_target_for_swapchain_info(info, &tex_target, &binding_enum); struct xrt_swapchain *native_xsc = &xscn->base; - struct client_gl_memobj_swapchain *sc = - U_TYPED_CALLOC(struct client_gl_memobj_swapchain); + struct client_gl_memobj_swapchain *sc = U_TYPED_CALLOC(struct client_gl_memobj_swapchain); struct xrt_swapchain_gl *xscgl = &sc->base.base; struct xrt_swapchain *client_xsc = &xscgl->base; client_xsc->destroy = client_gl_memobj_swapchain_destroy; @@ -97,25 +96,19 @@ client_gl_memobj_swapchain_create(struct xrt_compositor *xc, glCreateMemoryObjectsEXT(native_xsc->num_images, &sc->memory[0]); for (uint32_t i = 0; i < native_xsc->num_images; i++) { GLint dedicated = GL_TRUE; - glMemoryObjectParameterivEXT( - sc->memory[i], GL_DEDICATED_MEMORY_OBJECT_EXT, &dedicated); - glImportMemoryFdEXT(sc->memory[i], xscn->images[i].size, - GL_HANDLE_TYPE_OPAQUE_FD_EXT, + glMemoryObjectParameterivEXT(sc->memory[i], GL_DEDICATED_MEMORY_OBJECT_EXT, &dedicated); + glImportMemoryFdEXT(sc->memory[i], xscn->images[i].size, GL_HANDLE_TYPE_OPAQUE_FD_EXT, xscn->images[i].handle); // We have consumed this now, make sure it's not freed again. xscn->images[i].handle = XRT_GRAPHICS_BUFFER_HANDLE_INVALID; if (info->array_size == 1) { - glTextureStorageMem2DEXT( - xscgl->images[i], info->mip_count, - (GLuint)info->format, info->width, info->height, - sc->memory[i], 0); + glTextureStorageMem2DEXT(xscgl->images[i], info->mip_count, (GLuint)info->format, info->width, + info->height, sc->memory[i], 0); } else { - glTextureStorageMem3DEXT( - xscgl->images[i], info->mip_count, - (GLuint)info->format, info->width, info->height, - info->array_size, sc->memory[i], 0); + glTextureStorageMem3DEXT(xscgl->images[i], info->mip_count, (GLuint)info->format, info->width, + info->height, info->array_size, sc->memory[i], 0); } } diff --git a/src/xrt/compositor/client/comp_gl_xlib_client.c b/src/xrt/compositor/client/comp_gl_xlib_client.c index 43db27f9b..cb7359043 100644 --- a/src/xrt/compositor/client/comp_gl_xlib_client.c +++ b/src/xrt/compositor/client/comp_gl_xlib_client.c @@ -58,14 +58,12 @@ client_gl_xlib_compositor_create(struct xrt_compositor_native *xcn, { gladLoadGL(glXGetProcAddress); -#define CHECK_REQUIRED_EXTENSION(EXT) \ - do { \ - if (!GLAD_##EXT) { \ - U_LOG_E("%s - Required OpenGL extension " #EXT \ - " not available", \ - __func__); \ - return NULL; \ - } \ +#define CHECK_REQUIRED_EXTENSION(EXT) \ + do { \ + if (!GLAD_##EXT) { \ + U_LOG_E("%s - Required OpenGL extension " #EXT " not available", __func__); \ + return NULL; \ + } \ } while (0) CHECK_REQUIRED_EXTENSION(GL_EXT_memory_object); @@ -75,11 +73,9 @@ client_gl_xlib_compositor_create(struct xrt_compositor_native *xcn, #undef CHECK_REQUIRED_EXTENSION - struct client_gl_xlib_compositor *c = - U_TYPED_CALLOC(struct client_gl_xlib_compositor); + struct client_gl_xlib_compositor *c = U_TYPED_CALLOC(struct client_gl_xlib_compositor); - if (!client_gl_compositor_init( - &c->base, xcn, client_gl_memobj_swapchain_create, NULL)) { + if (!client_gl_compositor_init(&c->base, xcn, client_gl_memobj_swapchain_create, NULL)) { free(c); return NULL; } diff --git a/src/xrt/compositor/client/comp_gl_xlib_glue.c b/src/xrt/compositor/client/comp_gl_xlib_glue.c index 385d9c7d9..2fc50c5e4 100644 --- a/src/xrt/compositor/client/comp_gl_xlib_glue.c +++ b/src/xrt/compositor/client/comp_gl_xlib_glue.c @@ -24,8 +24,7 @@ xrt_gfx_provider_create_gl_xlib(struct xrt_compositor_native *xcn, GLXContext glxContext) { struct client_gl_xlib_compositor *xcc = - client_gl_xlib_compositor_create( - xcn, xDisplay, visualid, glxFBConfig, glxDrawable, glxContext); + client_gl_xlib_compositor_create(xcn, xDisplay, visualid, glxFBConfig, glxDrawable, glxContext); return &xcc->base.base; } diff --git a/src/xrt/compositor/client/comp_vk_client.c b/src/xrt/compositor/client/comp_vk_client.c index 638362456..1597e1094 100644 --- a/src/xrt/compositor/client/comp_vk_client.c +++ b/src/xrt/compositor/client/comp_vk_client.c @@ -52,8 +52,7 @@ client_vk_swapchain_destroy(struct xrt_swapchain *xsc) for (uint32_t i = 0; i < sc->base.base.num_images; i++) { if (sc->base.images[i] != VK_NULL_HANDLE) { - c->vk.vkDestroyImage(c->vk.device, sc->base.images[i], - NULL); + c->vk.vkDestroyImage(c->vk.device, sc->base.images[i], NULL); sc->base.images[i] = VK_NULL_HANDLE; } @@ -70,15 +69,13 @@ client_vk_swapchain_destroy(struct xrt_swapchain *xsc) } static xrt_result_t -client_vk_swapchain_acquire_image(struct xrt_swapchain *xsc, - uint32_t *out_index) +client_vk_swapchain_acquire_image(struct xrt_swapchain *xsc, uint32_t *out_index) { struct client_vk_swapchain *sc = client_vk_swapchain(xsc); struct vk_bundle *vk = &sc->c->vk; // Pipe down call into native swapchain. - xrt_result_t xret = - xrt_swapchain_acquire_image(&sc->xscn->base, out_index); + xrt_result_t xret = xrt_swapchain_acquire_image(&sc->xscn->base, out_index); if (xret != XRT_SUCCESS) { return xret; } @@ -90,8 +87,7 @@ client_vk_swapchain_acquire_image(struct xrt_swapchain *xsc, .pCommandBuffers = &sc->acquire[*out_index], }; - VkResult ret = - vk_locked_submit(vk, vk->queue, 1, &submitInfo, VK_NULL_HANDLE); + VkResult ret = vk_locked_submit(vk, vk->queue, 1, &submitInfo, VK_NULL_HANDLE); if (ret != VK_SUCCESS) { VK_ERROR(vk, "Could not submit to queue: %d", ret); return XRT_ERROR_FAILED_TO_SUBMIT_VULKAN_COMMANDS; @@ -100,9 +96,7 @@ client_vk_swapchain_acquire_image(struct xrt_swapchain *xsc, } static xrt_result_t -client_vk_swapchain_wait_image(struct xrt_swapchain *xsc, - uint64_t timeout, - uint32_t index) +client_vk_swapchain_wait_image(struct xrt_swapchain *xsc, uint64_t timeout, uint32_t index) { struct client_vk_swapchain *sc = client_vk_swapchain(xsc); @@ -123,8 +117,7 @@ client_vk_swapchain_release_image(struct xrt_swapchain *xsc, uint32_t index) .pCommandBuffers = &sc->release[index], }; - VkResult ret = - vk_locked_submit(vk, vk->queue, 1, &submitInfo, VK_NULL_HANDLE); + VkResult ret = vk_locked_submit(vk, vk->queue, 1, &submitInfo, VK_NULL_HANDLE); if (ret != VK_SUCCESS) { VK_ERROR(vk, "Could not submit to queue: %d", ret); return XRT_ERROR_FAILED_TO_SUBMIT_VULKAN_COMMANDS; @@ -142,8 +135,7 @@ client_vk_swapchain_release_image(struct xrt_swapchain *xsc, uint32_t index) */ static xrt_result_t -client_vk_compositor_poll_events(struct xrt_compositor *xc, - union xrt_compositor_event *out_xce) +client_vk_compositor_poll_events(struct xrt_compositor *xc, union xrt_compositor_event *out_xce) { struct client_vk_compositor *c = client_vk_compositor(xc); @@ -171,8 +163,7 @@ client_vk_compositor_destroy(struct xrt_compositor *xc) } static xrt_result_t -client_vk_compositor_prepare_session( - struct xrt_compositor *xc, const struct xrt_session_prepare_info *xspi) +client_vk_compositor_prepare_session(struct xrt_compositor *xc, const struct xrt_session_prepare_info *xspi) { struct client_vk_compositor *c = client_vk_compositor(xc); @@ -181,8 +172,7 @@ client_vk_compositor_prepare_session( } static xrt_result_t -client_vk_compositor_begin_session(struct xrt_compositor *xc, - enum xrt_view_type type) +client_vk_compositor_begin_session(struct xrt_compositor *xc, enum xrt_view_type type) { struct client_vk_compositor *c = client_vk_compositor(xc); @@ -208,9 +198,7 @@ client_vk_compositor_wait_frame(struct xrt_compositor *xc, struct client_vk_compositor *c = client_vk_compositor(xc); // Pipe down call into native compositor. - return xrt_comp_wait_frame(&c->xcn->base, out_frame_id, - predicted_display_time, - predicted_display_period); + return xrt_comp_wait_frame(&c->xcn->base, out_frame_id, predicted_display_time, predicted_display_period); } static xrt_result_t @@ -232,9 +220,7 @@ client_vk_compositor_discard_frame(struct xrt_compositor *xc, int64_t frame_id) } static xrt_result_t -client_vk_compositor_layer_begin(struct xrt_compositor *xc, - int64_t frame_id, - enum xrt_blend_mode env_blend_mode) +client_vk_compositor_layer_begin(struct xrt_compositor *xc, int64_t frame_id, enum xrt_blend_mode env_blend_mode) { struct client_vk_compositor *c = client_vk_compositor(xc); @@ -256,20 +242,18 @@ client_vk_compositor_layer_stereo_projection(struct xrt_compositor *xc, l_xscn = &client_vk_swapchain(l_xsc)->xscn->base; r_xscn = &client_vk_swapchain(r_xsc)->xscn->base; - return xrt_comp_layer_stereo_projection(&c->xcn->base, xdev, l_xscn, - r_xscn, data); + return xrt_comp_layer_stereo_projection(&c->xcn->base, xdev, l_xscn, r_xscn, data); } static xrt_result_t -client_vk_compositor_layer_stereo_projection_depth( - struct xrt_compositor *xc, - struct xrt_device *xdev, - struct xrt_swapchain *l_xsc, - struct xrt_swapchain *r_xsc, - struct xrt_swapchain *l_d_xsc, - struct xrt_swapchain *r_d_xsc, - const struct xrt_layer_data *data) +client_vk_compositor_layer_stereo_projection_depth(struct xrt_compositor *xc, + struct xrt_device *xdev, + struct xrt_swapchain *l_xsc, + struct xrt_swapchain *r_xsc, + struct xrt_swapchain *l_d_xsc, + struct xrt_swapchain *r_d_xsc, + const struct xrt_layer_data *data) { struct client_vk_compositor *c = client_vk_compositor(xc); struct xrt_swapchain *l_xscn, *r_xscn, *l_d_xscn, *r_d_xscn; @@ -281,8 +265,7 @@ client_vk_compositor_layer_stereo_projection_depth( l_d_xscn = &client_vk_swapchain(l_d_xsc)->xscn->base; r_d_xscn = &client_vk_swapchain(r_d_xsc)->xscn->base; - return xrt_comp_layer_stereo_projection_depth( - &c->xcn->base, xdev, l_xscn, r_xscn, l_d_xscn, r_d_xscn, data); + return xrt_comp_layer_stereo_projection_depth(&c->xcn->base, xdev, l_xscn, r_xscn, l_d_xscn, r_d_xscn, data); } static xrt_result_t @@ -366,17 +349,14 @@ client_vk_compositor_layer_equirect2(struct xrt_compositor *xc, } static xrt_result_t -client_vk_compositor_layer_commit(struct xrt_compositor *xc, - int64_t frame_id, - xrt_graphics_sync_handle_t sync_handle) +client_vk_compositor_layer_commit(struct xrt_compositor *xc, int64_t frame_id, xrt_graphics_sync_handle_t sync_handle) { struct client_vk_compositor *c = client_vk_compositor(xc); //! @todo We should be creating the handle ourselves in the future. assert(!xrt_graphics_sync_handle_is_valid(sync_handle)); - return xrt_comp_layer_commit(&c->xcn->base, frame_id, - XRT_GRAPHICS_SYNC_HANDLE_INVALID); + return xrt_comp_layer_commit(&c->xcn->base, frame_id, XRT_GRAPHICS_SYNC_HANDLE_INVALID); } static xrt_result_t @@ -412,8 +392,7 @@ client_vk_swapchain_create(struct xrt_compositor *xc, .layerCount = VK_REMAINING_ARRAY_LAYERS, }; - struct client_vk_swapchain *sc = - U_TYPED_CALLOC(struct client_vk_swapchain); + struct client_vk_swapchain *sc = U_TYPED_CALLOC(struct client_vk_swapchain); sc->base.base.destroy = client_vk_swapchain_destroy; sc->base.base.acquire_image = client_vk_swapchain_acquire_image; sc->base.base.wait_image = client_vk_swapchain_wait_image; @@ -424,9 +403,7 @@ client_vk_swapchain_create(struct xrt_compositor *xc, sc->xscn = xscn; for (uint32_t i = 0; i < xsc->num_images; i++) { - ret = vk_create_image_from_native( - &c->vk, info, &xscn->images[i], &sc->base.images[i], - &sc->mems[i]); + ret = vk_create_image_from_native(&c->vk, info, &xscn->images[i], &sc->base.images[i], &sc->mems[i]); if (ret != VK_SUCCESS) { @@ -438,11 +415,8 @@ client_vk_swapchain_create(struct xrt_compositor *xc, * not be a bug in the validation layer. That may or may not be * fixed in the future version of the validation layer. */ - vk_set_image_layout(&c->vk, cmd_buffer, sc->base.images[i], 0, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - subresource_range); + vk_set_image_layout(&c->vk, cmd_buffer, sc->base.images[i], 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, subresource_range); } ret = vk_submit_cmd_buffer(&c->vk, cmd_buffer); @@ -511,25 +485,19 @@ client_vk_swapchain_create(struct xrt_compositor *xc, }; //! @todo less conservative pipeline stage masks based on usage - c->vk.vkCmdPipelineBarrier(sc->acquire[i], - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - 0, 0, NULL, 0, NULL, 1, &acquire); - c->vk.vkCmdPipelineBarrier(sc->release[i], - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 1, &release); + c->vk.vkCmdPipelineBarrier(sc->acquire[i], VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, NULL, 0, NULL, 1, &acquire); + c->vk.vkCmdPipelineBarrier(sc->release[i], VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &release); ret = c->vk.vkEndCommandBuffer(sc->acquire[i]); if (ret != VK_SUCCESS) { - VK_ERROR((&c->vk), "vkEndCommandBuffer: %s", - vk_result_string(ret)); + VK_ERROR((&c->vk), "vkEndCommandBuffer: %s", vk_result_string(ret)); return XRT_ERROR_VULKAN; } ret = c->vk.vkEndCommandBuffer(sc->release[i]); if (ret != VK_SUCCESS) { - VK_ERROR((&c->vk), "vkEndCommandBuffer: %s", - vk_result_string(ret)); + VK_ERROR((&c->vk), "vkEndCommandBuffer: %s", vk_result_string(ret)); return XRT_ERROR_VULKAN; } } @@ -549,8 +517,7 @@ client_vk_compositor_create(struct xrt_compositor_native *xcn, uint32_t queueIndex) { VkResult ret; - struct client_vk_compositor *c = - U_TYPED_CALLOC(struct client_vk_compositor); + struct client_vk_compositor *c = U_TYPED_CALLOC(struct client_vk_compositor); c->base.base.create_swapchain = client_vk_swapchain_create; c->base.base.prepare_session = client_vk_compositor_prepare_session; @@ -560,10 +527,8 @@ client_vk_compositor_create(struct xrt_compositor_native *xcn, c->base.base.begin_frame = client_vk_compositor_begin_frame; c->base.base.discard_frame = client_vk_compositor_discard_frame; c->base.base.layer_begin = client_vk_compositor_layer_begin; - c->base.base.layer_stereo_projection = - client_vk_compositor_layer_stereo_projection; - c->base.base.layer_stereo_projection_depth = - client_vk_compositor_layer_stereo_projection_depth; + c->base.base.layer_stereo_projection = client_vk_compositor_layer_stereo_projection; + c->base.base.layer_stereo_projection_depth = client_vk_compositor_layer_stereo_projection_depth; c->base.base.layer_quad = client_vk_compositor_layer_quad; c->base.base.layer_cube = client_vk_compositor_layer_cube; c->base.base.layer_cylinder = client_vk_compositor_layer_cylinder; @@ -580,13 +545,10 @@ client_vk_compositor_create(struct xrt_compositor_native *xcn, } c->base.base.info.num_formats = xcn->base.info.num_formats; - memcpy(c->base.base.info.compositor_vk_deviceUUID, - xcn->base.info.compositor_vk_deviceUUID, XRT_GPU_UUID_SIZE); - memcpy(c->base.base.info.client_vk_deviceUUID, - xcn->base.info.client_vk_deviceUUID, XRT_GPU_UUID_SIZE); + memcpy(c->base.base.info.compositor_vk_deviceUUID, xcn->base.info.compositor_vk_deviceUUID, XRT_GPU_UUID_SIZE); + memcpy(c->base.base.info.client_vk_deviceUUID, xcn->base.info.client_vk_deviceUUID, XRT_GPU_UUID_SIZE); - ret = vk_init_from_given(&c->vk, getProc, instance, physicalDevice, - device, queueFamilyIndex, queueIndex); + ret = vk_init_from_given(&c->vk, getProc, instance, physicalDevice, device, queueFamilyIndex, queueIndex); if (ret != VK_SUCCESS) { goto err_free; } diff --git a/src/xrt/compositor/client/comp_vk_glue.c b/src/xrt/compositor/client/comp_vk_glue.c index 21ffc0d8e..9dac59eaa 100644 --- a/src/xrt/compositor/client/comp_vk_glue.c +++ b/src/xrt/compositor/client/comp_vk_glue.c @@ -16,21 +16,16 @@ // Note: Most of the time, the instance extensions required do **not** vary by // platform! -const char *xrt_gfx_vk_instance_extensions = - VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME - " " VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME - " " VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME +const char *xrt_gfx_vk_instance_extensions = VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME + " " VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME " " VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME " " VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME; // The device extensions do vary by platform, but in a very regular way. // This should match the list in comp_compositor, except it shouldn't include // VK_KHR_SWAPCHAIN_EXTENSION_NAME -const char *xrt_gfx_vk_device_extensions = - VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME - " " VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME - " " VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME - " " VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME - " " VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME +const char *xrt_gfx_vk_device_extensions = VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME + " " VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME " " VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME + " " VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME " " VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME // Platform version of "external_memory" #if defined(XRT_GRAPHICS_BUFFER_HANDLE_IS_FD) @@ -47,12 +42,10 @@ const char *xrt_gfx_vk_device_extensions = // Platform version of "external_fence" and "external_semaphore" #if defined(XRT_GRAPHICS_SYNC_HANDLE_IS_FD) - " " VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME - " " VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME; + " " VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME " " VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME; #elif defined(XRT_GRAPHICS_SYNC_HANDLE_IS_WIN32_HANDLE) - " " VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME - " " VK_KHR_EXTERNAL_FENCE_WIN32_EXTENSION_NAME; + " " VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME " " VK_KHR_EXTERNAL_FENCE_WIN32_EXTENSION_NAME; #else #error "Need port!" @@ -80,8 +73,7 @@ xrt_gfx_vk_provider_create(struct xrt_compositor_native *xcn, uint32_t queue_index) { struct client_vk_compositor *vcc = client_vk_compositor_create( - xcn, instance, get_instance_proc_addr, physical_device, device, - queue_family_index, queue_index); + xcn, instance, get_instance_proc_addr, physical_device, device, queue_family_index, queue_index); return &vcc->base; } diff --git a/src/xrt/compositor/main/comp_compositor.c b/src/xrt/compositor/main/comp_compositor.c index f561973e3..fb96c46ce 100644 --- a/src/xrt/compositor/main/comp_compositor.c +++ b/src/xrt/compositor/main/comp_compositor.c @@ -135,8 +135,7 @@ compositor_destroy(struct xrt_compositor *xc) } static xrt_result_t -compositor_prepare_session(struct xrt_compositor *xc, - const struct xrt_session_prepare_info *xspi) +compositor_prepare_session(struct xrt_compositor *xc, const struct xrt_session_prepare_info *xspi) { struct comp_compositor *c = comp_compositor(xc); COMP_DEBUG(c, "PREPARE_SESSION"); @@ -233,8 +232,7 @@ compositor_wait_frame(struct xrt_compositor *xc, COMP_SPEW(c, "WAIT_FRAME Finished at %8.3fms, predicted display " "time %8.3fms, period %8.3fms", - ns_to_ms(now_ns), ns_to_ms(*predicted_display_time), - ns_to_ms(*predicted_display_period)); + ns_to_ms(now_ns), ns_to_ms(*predicted_display_time), ns_to_ms(*predicted_display_period)); return XRT_SUCCESS; } @@ -242,13 +240,10 @@ compositor_wait_frame(struct xrt_compositor *xc, // First estimate of next display time. while (1) { - int64_t render_time_ns = - c->expected_app_duration_ns + c->frame_overhead_ns; - int64_t swap_interval = - ceilf((float)render_time_ns / interval_ns); + int64_t render_time_ns = c->expected_app_duration_ns + c->frame_overhead_ns; + int64_t swap_interval = ceilf((float)render_time_ns / interval_ns); int64_t render_interval_ns = swap_interval * interval_ns; - int64_t next_display_time = - c->last_next_display_time + render_interval_ns; + int64_t next_display_time = c->last_next_display_time + render_interval_ns; /*! * @todo adjust next_display_time to be a multiple of * interval_ns from c->last_frame_time_ns @@ -258,12 +253,10 @@ compositor_wait_frame(struct xrt_compositor *xc, // we can't unblock in the past next_display_time += render_interval_ns; } - if (compositor_wait_vsync_or_time( - c, (next_display_time - render_time_ns))) { + if (compositor_wait_vsync_or_time(c, (next_display_time - render_time_ns))) { // True return val means we actually waited for the // deadline. - *predicted_display_period = - next_display_time - c->last_next_display_time; + *predicted_display_period = next_display_time - c->last_next_display_time; *predicted_display_time = next_display_time; *out_frame_id = c->last_next_display_time; @@ -272,8 +265,7 @@ compositor_wait_frame(struct xrt_compositor *xc, COMP_SPEW(c, "WAIT_FRAME Finished at %8.3fms, predicted " "display time %8.3fms, period %8.3fms", - ns_to_ms(now_ns), - ns_to_ms(*predicted_display_time), + ns_to_ms(now_ns), ns_to_ms(*predicted_display_time), ns_to_ms(*predicted_display_period)); return XRT_SUCCESS; @@ -315,30 +307,23 @@ compositor_add_frame_timing(struct comp_compositor *c) for (int i = 0; i < NUM_FRAME_TIMINGS; i++) { uint64_t frametime_ns = - c->compositor_frame_times.times_ns[i + 1] - - c->compositor_frame_times.times_ns[i]; - float frametime_s = - frametime_ns * 1. / 1000. * 1. / 1000. * 1. / 1000.; + c->compositor_frame_times.times_ns[i + 1] - c->compositor_frame_times.times_ns[i]; + float frametime_s = frametime_ns * 1. / 1000. * 1. / 1000. * 1. / 1000.; total_s += frametime_s; } float avg_frametime_s = total_s / ((float)NUM_FRAME_TIMINGS); c->compositor_frame_times.fps = 1. / avg_frametime_s; } - c->compositor_frame_times.times_ns[c->compositor_frame_times.index] = - os_monotonic_get_ns(); + c->compositor_frame_times.times_ns[c->compositor_frame_times.index] = os_monotonic_get_ns(); - uint64_t diff = c->compositor_frame_times - .times_ns[c->compositor_frame_times.index] - + uint64_t diff = c->compositor_frame_times.times_ns[c->compositor_frame_times.index] - c->compositor_frame_times.times_ns[last_index]; - c->compositor_frame_times.timings_ms[c->compositor_frame_times.index] = - (float)diff * 1. / 1000. * 1. / 1000.; + c->compositor_frame_times.timings_ms[c->compositor_frame_times.index] = (float)diff * 1. / 1000. * 1. / 1000.; } static xrt_result_t -compositor_layer_begin(struct xrt_compositor *xc, - int64_t frame_id, - enum xrt_blend_mode env_blend_mode) +compositor_layer_begin(struct xrt_compositor *xc, int64_t frame_id, enum xrt_blend_mode env_blend_mode) { struct comp_compositor *c = comp_compositor(xc); @@ -467,9 +452,7 @@ compositor_layer_equirect2(struct xrt_compositor *xc, } static xrt_result_t -compositor_layer_commit(struct xrt_compositor *xc, - int64_t frame_id, - xrt_graphics_sync_handle_t sync_handle) +compositor_layer_commit(struct xrt_compositor *xc, int64_t frame_id, xrt_graphics_sync_handle_t sync_handle) { struct comp_compositor *c = comp_compositor(xc); @@ -497,9 +480,7 @@ compositor_layer_commit(struct xrt_compositor *xc, struct comp_layer *layer = &c->slots[slot_id].layers[i]; struct xrt_layer_data *data = &layer->data; - COMP_SPEW(c, - "LAYER_COMMIT (%d) predicted display time: %8.3fms", - i, ns_to_ms(data->timestamp)); + COMP_SPEW(c, "LAYER_COMMIT (%d) predicted display time: %8.3fms", i, ns_to_ms(data->timestamp)); switch (data->type) { case XRT_LAYER_QUAD: { @@ -509,44 +490,34 @@ compositor_layer_commit(struct xrt_compositor *xc, comp_renderer_set_quad_layer(c->r, i, image, data); } break; case XRT_LAYER_STEREO_PROJECTION: { - struct xrt_layer_stereo_projection_data *stereo = - &data->stereo; + struct xrt_layer_stereo_projection_data *stereo = &data->stereo; struct comp_swapchain_image *right; struct comp_swapchain_image *left; - left = - &layer->scs[0]->images[stereo->l.sub.image_index]; - right = - &layer->scs[1]->images[stereo->r.sub.image_index]; + left = &layer->scs[0]->images[stereo->l.sub.image_index]; + right = &layer->scs[1]->images[stereo->r.sub.image_index]; - comp_renderer_set_projection_layer(c->r, i, left, right, - data); + comp_renderer_set_projection_layer(c->r, i, left, right, data); } break; case XRT_LAYER_STEREO_PROJECTION_DEPTH: { - struct xrt_layer_stereo_projection_depth_data *stereo = - &data->stereo_depth; + struct xrt_layer_stereo_projection_depth_data *stereo = &data->stereo_depth; struct comp_swapchain_image *right; struct comp_swapchain_image *left; - left = - &layer->scs[0]->images[stereo->l.sub.image_index]; - right = - &layer->scs[1]->images[stereo->r.sub.image_index]; + left = &layer->scs[0]->images[stereo->l.sub.image_index]; + right = &layer->scs[1]->images[stereo->r.sub.image_index]; //! @todo: Make use of stereo->l_d and stereo->r_d - comp_renderer_set_projection_layer(c->r, i, left, right, - data); + comp_renderer_set_projection_layer(c->r, i, left, right, data); } break; case XRT_LAYER_CYLINDER: { - struct xrt_layer_cylinder_data *cyl = - &layer->data.cylinder; + struct xrt_layer_cylinder_data *cyl = &layer->data.cylinder; struct comp_swapchain_image *image; image = &layer->scs[0]->images[cyl->sub.image_index]; comp_renderer_set_cylinder_layer(c->r, i, image, data); } break; #ifdef XRT_FEATURE_OPENXR_LAYER_EQUIRECT1 case XRT_LAYER_EQUIRECT1: { - struct xrt_layer_equirect1_data *eq = - &layer->data.equirect1; + struct xrt_layer_equirect1_data *eq = &layer->data.equirect1; struct comp_swapchain_image *image; image = &layer->scs[0]->images[eq->sub.image_index]; comp_renderer_set_equirect1_layer(c->r, i, image, data); @@ -554,8 +525,7 @@ compositor_layer_commit(struct xrt_compositor *xc, #endif #ifdef XRT_FEATURE_OPENXR_LAYER_EQUIRECT2 case XRT_LAYER_EQUIRECT2: { - struct xrt_layer_equirect2_data *eq = - &layer->data.equirect2; + struct xrt_layer_equirect2_data *eq = &layer->data.equirect2; struct comp_swapchain_image *image; image = &layer->scs[0]->images[eq->sub.image_index]; comp_renderer_set_equirect2_layer(c->r, i, image, data); @@ -582,11 +552,9 @@ compositor_layer_commit(struct xrt_compositor *xc, c->app_profiling.last_end = c->last_frame_time_ns; //! @todo do a time-weighted average or something. - c->expected_app_duration_ns = - c->app_profiling.last_end - c->app_profiling.last_begin; + c->expected_app_duration_ns = c->app_profiling.last_end - c->app_profiling.last_begin; - COMP_SPEW(c, "LAYER_COMMIT finished drawing at %8.3fms", - ns_to_ms(c->last_frame_time_ns)); + COMP_SPEW(c, "LAYER_COMMIT finished drawing at %8.3fms", ns_to_ms(c->last_frame_time_ns)); // Now is a good point to garbage collect. comp_compositor_garbage_collect(c); @@ -594,8 +562,7 @@ compositor_layer_commit(struct xrt_compositor *xc, } static xrt_result_t -compositor_poll_events(struct xrt_compositor *xc, - union xrt_compositor_event *out_xce) +compositor_poll_events(struct xrt_compositor *xc, union xrt_compositor_event *out_xce) { struct comp_compositor *c = comp_compositor(xc); COMP_SPEW(c, "POLL_EVENTS"); @@ -607,9 +574,7 @@ compositor_poll_events(struct xrt_compositor *xc, COMP_ERROR(c, "Polled uninitialized compositor"); out_xce->state.type = XRT_COMPOSITOR_EVENT_NONE; break; - case COMP_STATE_READY: - out_xce->state.type = XRT_COMPOSITOR_EVENT_NONE; - break; + case COMP_STATE_READY: out_xce->state.type = XRT_COMPOSITOR_EVENT_NONE; break; case COMP_STATE_PREPARED: COMP_DEBUG(c, "PREPARED -> VISIBLE"); out_xce->state.type = XRT_COMPOSITOR_EVENT_STATE_CHANGE; @@ -640,8 +605,7 @@ compositor_poll_events(struct xrt_compositor *xc, */ static bool -compositor_check_and_prepare_xdev(struct comp_compositor *c, - struct xrt_device *xdev) +compositor_check_and_prepare_xdev(struct comp_compositor *c, struct xrt_device *xdev) { // clang-format off bool has_none = (xdev->hmd->distortion.models & XRT_DISTORTION_MODEL_NONE) != 0; @@ -655,9 +619,7 @@ compositor_check_and_prepare_xdev(struct comp_compositor *c, } if (!has_none && !has_compute) { - COMP_ERROR( - c, "The xdev '%s' didn't have none nor compute distortion.", - xdev->str); + COMP_ERROR(c, "The xdev '%s' didn't have none nor compute distortion.", xdev->str); return false; } @@ -688,12 +650,9 @@ compositor_check_and_prepare_xdev(struct comp_compositor *c, * */ -#define GET_DEV_PROC(c, name) \ - (PFN_##name) c->vk.vkGetDeviceProcAddr(c->vk.device, #name); -#define GET_INS_PROC(c, name) \ - (PFN_##name) c->vk.vkGetInstanceProcAddr(c->vk.instance, #name); -#define GET_DEV_PROC(c, name) \ - (PFN_##name) c->vk.vkGetDeviceProcAddr(c->vk.device, #name); +#define GET_DEV_PROC(c, name) (PFN_##name) c->vk.vkGetDeviceProcAddr(c->vk.device, #name); +#define GET_INS_PROC(c, name) (PFN_##name) c->vk.vkGetInstanceProcAddr(c->vk.instance, #name); +#define GET_DEV_PROC(c, name) (PFN_##name) c->vk.vkGetDeviceProcAddr(c->vk.device, #name); // NOLINTNEXTLINE // don't remove the forward decl. VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL @@ -710,24 +669,20 @@ find_get_instance_proc_addr(struct comp_compositor *c) // If any of these lists are updated, please also update the appropriate column // in `vulkan-extensions.md` -#define COMP_INSTANCE_EXTENSIONS_COMMON \ - VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME, \ - VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME, \ - VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME, \ - VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, \ - VK_KHR_SURFACE_EXTENSION_NAME +#define COMP_INSTANCE_EXTENSIONS_COMMON \ + VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME, VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME, \ + VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME, \ + VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, VK_KHR_SURFACE_EXTENSION_NAME -static const char *instance_extensions_none[] = { - COMP_INSTANCE_EXTENSIONS_COMMON}; +static const char *instance_extensions_none[] = {COMP_INSTANCE_EXTENSIONS_COMMON}; #ifdef VK_USE_PLATFORM_XCB_KHR -static const char *instance_extensions_xcb[] = { - COMP_INSTANCE_EXTENSIONS_COMMON, VK_KHR_XCB_SURFACE_EXTENSION_NAME}; +static const char *instance_extensions_xcb[] = {COMP_INSTANCE_EXTENSIONS_COMMON, VK_KHR_XCB_SURFACE_EXTENSION_NAME}; #endif #ifdef VK_USE_PLATFORM_WAYLAND_KHR -static const char *instance_extensions_wayland[] = { - COMP_INSTANCE_EXTENSIONS_COMMON, VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME}; +static const char *instance_extensions_wayland[] = {COMP_INSTANCE_EXTENSIONS_COMMON, + VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME}; #endif #ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT @@ -740,13 +695,13 @@ static const char *instance_extensions_direct_mode[] = { #endif #ifdef VK_USE_PLATFORM_ANDROID_KHR -static const char *instance_extensions_android[] = { - COMP_INSTANCE_EXTENSIONS_COMMON, VK_KHR_ANDROID_SURFACE_EXTENSION_NAME}; +static const char *instance_extensions_android[] = {COMP_INSTANCE_EXTENSIONS_COMMON, + VK_KHR_ANDROID_SURFACE_EXTENSION_NAME}; #endif #ifdef VK_USE_PLATFORM_WIN32_KHR -static const char *instance_extensions_windows[] = { - COMP_INSTANCE_EXTENSIONS_COMMON, VK_KHR_WIN32_SURFACE_EXTENSION_NAME}; +static const char *instance_extensions_windows[] = {COMP_INSTANCE_EXTENSIONS_COMMON, + VK_KHR_WIN32_SURFACE_EXTENSION_NAME}; #endif // Note: Keep synchronized with comp_vk_glue - we should have everything they @@ -793,9 +748,7 @@ static const char *optional_device_extensions[] = { static VkResult -select_instances_extensions(struct comp_compositor *c, - const char ***out_exts, - uint32_t *out_num) +select_instances_extensions(struct comp_compositor *c, const char ***out_exts, uint32_t *out_num) { switch (c->settings.window_type) { case WINDOW_NONE: @@ -853,11 +806,9 @@ create_instance(struct comp_compositor *c) .apiVersion = VK_MAKE_VERSION(1, 0, 2), }; - ret = select_instances_extensions(c, &instance_extensions, - &num_extensions); + ret = select_instances_extensions(c, &instance_extensions, &num_extensions); if (ret != VK_SUCCESS) { - COMP_ERROR(c, "Failed to select instance extensions: %s", - vk_result_string(ret)); + COMP_ERROR(c, "Failed to select instance extensions: %s", vk_result_string(ret)); return ret; } @@ -877,8 +828,7 @@ create_instance(struct comp_compositor *c) ret = vk_get_instance_functions(&c->vk); if (ret != VK_SUCCESS) { - COMP_ERROR(c, "Failed to get Vulkan instance functions: %s", - vk_result_string(ret)); + COMP_ERROR(c, "Failed to get Vulkan instance functions: %s", vk_result_string(ret)); return ret; } @@ -886,17 +836,11 @@ create_instance(struct comp_compositor *c) } static bool -get_device_uuid(struct vk_bundle *vk, - struct comp_compositor *c, - int gpu_index, - uint8_t *uuid) +get_device_uuid(struct vk_bundle *vk, struct comp_compositor *c, int gpu_index, uint8_t *uuid) { - VkPhysicalDeviceIDProperties pdidp = { - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; + VkPhysicalDeviceIDProperties pdidp = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; - VkPhysicalDeviceProperties2 pdp2 = { - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, - .pNext = &pdidp}; + VkPhysicalDeviceProperties2 pdp2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &pdidp}; VkPhysicalDevice phys[16]; uint32_t gpu_count = ARRAY_SIZE(phys); @@ -931,10 +875,9 @@ compositor_init_vulkan(struct comp_compositor *c) return false; } - ret = vk_create_device( - &c->vk, c->settings.selected_gpu_index, required_device_extensions, - ARRAY_SIZE(required_device_extensions), optional_device_extensions, - ARRAY_SIZE(optional_device_extensions)); + ret = vk_create_device(&c->vk, c->settings.selected_gpu_index, required_device_extensions, + ARRAY_SIZE(required_device_extensions), optional_device_extensions, + ARRAY_SIZE(optional_device_extensions)); if (os_mutex_init(&c->vk.queue_mutex) != 0) { return false; @@ -951,18 +894,14 @@ compositor_init_vulkan(struct comp_compositor *c) // store physical device UUID for compositor in settings if (c->settings.selected_gpu_index >= 0) { - if (get_device_uuid(&c->vk, c, c->settings.selected_gpu_index, - c->settings.selected_gpu_deviceUUID)) { + if (get_device_uuid(&c->vk, c, c->settings.selected_gpu_index, c->settings.selected_gpu_deviceUUID)) { char uuid_str[XRT_GPU_UUID_SIZE * 3 + 1] = {0}; for (int i = 0; i < XRT_GPU_UUID_SIZE; i++) { - sprintf(uuid_str + i * 3, "%02x ", - c->settings.selected_gpu_deviceUUID[i]); + sprintf(uuid_str + i * 3, "%02x ", c->settings.selected_gpu_deviceUUID[i]); } - COMP_DEBUG(c, "Selected %d with uuid: %s", - c->settings.selected_gpu_index, uuid_str); + COMP_DEBUG(c, "Selected %d with uuid: %s", c->settings.selected_gpu_index, uuid_str); } else { - COMP_ERROR(c, "Failed to get device %d uuid", - c->settings.selected_gpu_index); + COMP_ERROR(c, "Failed to get device %d uuid", c->settings.selected_gpu_index); } } @@ -973,18 +912,14 @@ compositor_init_vulkan(struct comp_compositor *c) // store physical device UUID suggested to clients in settings if (c->settings.client_gpu_index >= 0) { - if (get_device_uuid(&c->vk, c, c->settings.client_gpu_index, - c->settings.client_gpu_deviceUUID)) { + if (get_device_uuid(&c->vk, c, c->settings.client_gpu_index, c->settings.client_gpu_deviceUUID)) { char uuid_str[XRT_GPU_UUID_SIZE * 3 + 1] = {0}; for (int i = 0; i < XRT_GPU_UUID_SIZE; i++) { - sprintf(uuid_str + i * 3, "%02x ", - c->settings.client_gpu_deviceUUID[i]); + sprintf(uuid_str + i * 3, "%02x ", c->settings.client_gpu_deviceUUID[i]); } - COMP_DEBUG(c, "Suggest %d with uuid: %s to clients", - c->settings.client_gpu_index, uuid_str); + COMP_DEBUG(c, "Suggest %d with uuid: %s to clients", c->settings.client_gpu_index, uuid_str); } else { - COMP_ERROR(c, "Failed to get device %d uuid", - c->settings.client_gpu_index); + COMP_ERROR(c, "Failed to get device %d uuid", c->settings.client_gpu_index); } } @@ -1028,8 +963,7 @@ static bool _test_for_nvidia(struct comp_compositor *c, struct vk_bundle *vk) { VkPhysicalDeviceProperties physical_device_properties; - vk->vkGetPhysicalDeviceProperties(vk->physical_device, - &physical_device_properties); + vk->vkGetPhysicalDeviceProperties(vk->physical_device, &physical_device_properties); if (physical_device_properties.vendorID != 0x10DE) return false; @@ -1037,18 +971,15 @@ _test_for_nvidia(struct comp_compositor *c, struct vk_bundle *vk) // get a list of attached displays uint32_t display_count; - if (vk->vkGetPhysicalDeviceDisplayPropertiesKHR( - vk->physical_device, &display_count, NULL) != VK_SUCCESS) { + if (vk->vkGetPhysicalDeviceDisplayPropertiesKHR(vk->physical_device, &display_count, NULL) != VK_SUCCESS) { COMP_ERROR(c, "Failed to get vulkan display count"); return false; } - VkDisplayPropertiesKHR *display_props = - U_TYPED_ARRAY_CALLOC(VkDisplayPropertiesKHR, display_count); + VkDisplayPropertiesKHR *display_props = U_TYPED_ARRAY_CALLOC(VkDisplayPropertiesKHR, display_count); - if (display_props && vk->vkGetPhysicalDeviceDisplayPropertiesKHR( - vk->physical_device, &display_count, - display_props) != VK_SUCCESS) { + if (display_props && vk->vkGetPhysicalDeviceDisplayPropertiesKHR(vk->physical_device, &display_count, + display_props) != VK_SUCCESS) { COMP_ERROR(c, "Failed to get display properties"); free(display_props); return false; @@ -1064,8 +995,7 @@ _test_for_nvidia(struct comp_compositor *c, struct vk_bundle *vk) } } - if (c->settings.nvidia_display && - _match_wl_entry(c->settings.nvidia_display, disp)) { + if (c->settings.nvidia_display && _match_wl_entry(c->settings.nvidia_display, disp)) { free(display_props); return true; } @@ -1111,8 +1041,7 @@ compositor_check_vulkan_caps(struct comp_compositor *c) return false; } - const char *extension_names[] = {COMP_INSTANCE_EXTENSIONS_COMMON, - VK_KHR_DISPLAY_EXTENSION_NAME}; + const char *extension_names[] = {COMP_INSTANCE_EXTENSIONS_COMMON, VK_KHR_DISPLAY_EXTENSION_NAME}; VkInstanceCreateInfo instance_create_info = { @@ -1121,30 +1050,25 @@ compositor_check_vulkan_caps(struct comp_compositor *c) .ppEnabledExtensionNames = extension_names, }; - ret = temp_vk.vkCreateInstance(&instance_create_info, NULL, - &(temp_vk.instance)); + ret = temp_vk.vkCreateInstance(&instance_create_info, NULL, &(temp_vk.instance)); if (ret != VK_SUCCESS) { - COMP_ERROR(c, "Failed to create VkInstance: %s", - vk_result_string(ret)); + COMP_ERROR(c, "Failed to create VkInstance: %s", vk_result_string(ret)); return false; } ret = vk_get_instance_functions(&temp_vk); if (ret != VK_SUCCESS) { - COMP_ERROR(c, "Failed to get Vulkan instance functions: %s", - vk_result_string(ret)); + COMP_ERROR(c, "Failed to get Vulkan instance functions: %s", vk_result_string(ret)); return false; } // follow same device selection logic as subsequent calls - ret = vk_create_device( - &temp_vk, c->settings.selected_gpu_index, - required_device_extensions, ARRAY_SIZE(required_device_extensions), - optional_device_extensions, ARRAY_SIZE(optional_device_extensions)); + ret = vk_create_device(&temp_vk, c->settings.selected_gpu_index, required_device_extensions, + ARRAY_SIZE(required_device_extensions), optional_device_extensions, + ARRAY_SIZE(optional_device_extensions)); if (ret != VK_SUCCESS) { - COMP_ERROR(c, "Failed to create VkDevice: %s", - vk_result_string(ret)); + COMP_ERROR(c, "Failed to create VkDevice: %s", vk_result_string(ret)); return false; } @@ -1196,8 +1120,7 @@ compositor_init_window_pre_vulkan(struct comp_compositor *c) } #endif #ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT - if (compositor_try_window(c, - comp_window_direct_randr_create(c))) { + if (compositor_try_window(c, comp_window_direct_randr_create(c))) { c->settings.window_type = WINDOW_DIRECT_RANDR; return true; } @@ -1208,8 +1131,7 @@ compositor_init_window_pre_vulkan(struct comp_compositor *c) COMP_DEBUG(c, "Using VK_PRESENT_MODE_IMMEDIATE_KHR for " "xcb window") - c->settings.present_mode = - VK_PRESENT_MODE_IMMEDIATE_KHR; + c->settings.present_mode = VK_PRESENT_MODE_IMMEDIATE_KHR; return true; } #endif @@ -1230,8 +1152,7 @@ compositor_init_window_pre_vulkan(struct comp_compositor *c) case WINDOW_XCB: #ifdef VK_USE_PLATFORM_XCB_KHR compositor_try_window(c, comp_window_xcb_create(c)); - COMP_DEBUG(c, - "Using VK_PRESENT_MODE_IMMEDIATE_KHR for xcb window") + COMP_DEBUG(c, "Using VK_PRESENT_MODE_IMMEDIATE_KHR for xcb window") c->settings.present_mode = VK_PRESENT_MODE_IMMEDIATE_KHR; #else COMP_ERROR(c, "XCB support not compiled in!"); @@ -1283,8 +1204,7 @@ compositor_init_window_post_vulkan(struct comp_compositor *c) #ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT return compositor_try_window(c, comp_window_direct_nvidia_create(c)); #else - assert(false && - "NVIDIA direct mode depends on the xlib/xrandr direct mode."); + assert(false && "NVIDIA direct mode depends on the xlib/xrandr direct mode."); return false; #endif } @@ -1337,19 +1257,18 @@ static bool is_format_supported(struct comp_compositor *c, VkFormat format) { VkFormatProperties prop; - c->vk.vkGetPhysicalDeviceFormatProperties(c->vk.physical_device, format, - &prop); + c->vk.vkGetPhysicalDeviceFormatProperties(c->vk.physical_device, format, &prop); // This is a fairly crude way of checking support, // but works well enough. return prop.optimalTilingFeatures != 0; } -#define ADD_IF_SUPPORTED(format) \ - do { \ - if (is_format_supported(c, format)) { \ - info->formats[formats++] = format; \ - } \ +#define ADD_IF_SUPPORTED(format) \ + do { \ + if (is_format_supported(c, format)) { \ + info->formats[formats++] = format; \ + } \ } while (false) struct xrt_compositor_native * @@ -1366,10 +1285,8 @@ xrt_gfx_provider_create_native(struct xrt_device *xdev) c->base.base.begin_frame = compositor_begin_frame; c->base.base.discard_frame = compositor_discard_frame; c->base.base.layer_begin = compositor_layer_begin; - c->base.base.layer_stereo_projection = - compositor_layer_stereo_projection; - c->base.base.layer_stereo_projection_depth = - compositor_layer_stereo_projection_depth; + c->base.base.layer_stereo_projection = compositor_layer_stereo_projection; + c->base.base.layer_stereo_projection_depth = compositor_layer_stereo_projection_depth; c->base.base.layer_quad = compositor_layer_quad; c->base.base.layer_cube = compositor_layer_cube; c->base.base.layer_cylinder = compositor_layer_cylinder; @@ -1422,11 +1339,9 @@ xrt_gfx_provider_create_native(struct xrt_device *xdev) // Required by OpenXR spec. info->max_layers = 16; - memcpy(info->compositor_vk_deviceUUID, - c->settings.selected_gpu_deviceUUID, XRT_GPU_UUID_SIZE); + memcpy(info->compositor_vk_deviceUUID, c->settings.selected_gpu_deviceUUID, XRT_GPU_UUID_SIZE); - memcpy(info->client_vk_deviceUUID, c->settings.client_gpu_deviceUUID, - XRT_GPU_UUID_SIZE); + memcpy(info->client_vk_deviceUUID, c->settings.client_gpu_deviceUUID, XRT_GPU_UUID_SIZE); /*! * @todo Support more like, depth/float formats etc, @@ -1500,8 +1415,7 @@ xrt_gfx_provider_create_native(struct xrt_device *xdev) struct u_var_timing *ft = U_TYPED_CALLOC(struct u_var_timing); - float target_frame_time_ms = - c->settings.nominal_frame_interval_ns * 1. / 1000. * 1. / 1000.; + float target_frame_time_ms = c->settings.nominal_frame_interval_ns * 1. / 1000. * 1. / 1000.; uint64_t now = os_monotonic_get_ns(); for (int i = 0; i < NUM_FRAME_TIMES; i++) { diff --git a/src/xrt/compositor/main/comp_compositor.h b/src/xrt/compositor/main/comp_compositor.h index 83391f6fe..f91c7b1e6 100644 --- a/src/xrt/compositor/main/comp_compositor.h +++ b/src/xrt/compositor/main/comp_compositor.h @@ -362,9 +362,9 @@ comp_shaders_close(struct vk_bundle *vk, struct comp_shaders *s); * * @relates comp_compositor */ -#define COMP_PRINT_MODE(c, ...) \ - if (c->settings.print_modes) { \ - U_LOG_I(__VA_ARGS__); \ +#define COMP_PRINT_MODE(c, ...) \ + if (c->settings.print_modes) { \ + U_LOG_I(__VA_ARGS__); \ } diff --git a/src/xrt/compositor/main/comp_layer.c b/src/xrt/compositor/main/comp_layer.c index 068ba4131..83e82fe84 100644 --- a/src/xrt/compositor/main/comp_layer.c +++ b/src/xrt/compositor/main/comp_layer.c @@ -36,48 +36,37 @@ comp_layer_set_flip_y(struct comp_render_layer *self, bool flip_y) } void -comp_layer_set_model_matrix(struct comp_render_layer *self, - const struct xrt_matrix_4x4 *m) +comp_layer_set_model_matrix(struct comp_render_layer *self, const struct xrt_matrix_4x4 *m) { memcpy(&self->model_matrix, m, sizeof(struct xrt_matrix_4x4)); } static void -_update_mvp_matrix(struct comp_render_layer *self, - uint32_t eye, - const struct xrt_matrix_4x4 *vp) +_update_mvp_matrix(struct comp_render_layer *self, uint32_t eye, const struct xrt_matrix_4x4 *vp) { - math_matrix_4x4_multiply(vp, &self->model_matrix, - &self->transformation[eye].mvp); - memcpy(self->transformation_ubos[eye].data, &self->transformation[eye], - sizeof(struct layer_transformation)); + math_matrix_4x4_multiply(vp, &self->model_matrix, &self->transformation[eye].mvp); + memcpy(self->transformation_ubos[eye].data, &self->transformation[eye], sizeof(struct layer_transformation)); } static bool _init_ubos(struct comp_render_layer *self) { VkBufferUsageFlags usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; - VkMemoryPropertyFlags properties = - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | - VK_MEMORY_PROPERTY_HOST_CACHED_BIT; + VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + VK_MEMORY_PROPERTY_HOST_CACHED_BIT; for (uint32_t i = 0; i < 2; i++) { math_matrix_4x4_identity(&self->transformation[i].mvp); - if (!vk_buffer_init( - self->vk, sizeof(struct layer_transformation), usage, - properties, &self->transformation_ubos[i].handle, - &self->transformation_ubos[i].memory)) + if (!vk_buffer_init(self->vk, sizeof(struct layer_transformation), usage, properties, + &self->transformation_ubos[i].handle, &self->transformation_ubos[i].memory)) return false; - VkResult res = self->vk->vkMapMemory( - self->vk->device, self->transformation_ubos[i].memory, 0, - VK_WHOLE_SIZE, 0, &self->transformation_ubos[i].data); + VkResult res = self->vk->vkMapMemory(self->vk->device, self->transformation_ubos[i].memory, 0, + VK_WHOLE_SIZE, 0, &self->transformation_ubos[i].data); vk_check_error("vkMapMemory", res, false); - memcpy(self->transformation_ubos[i].data, - &self->transformation[i], + memcpy(self->transformation_ubos[i].data, &self->transformation[i], sizeof(struct layer_transformation)); } return true; @@ -88,23 +77,18 @@ static bool _init_equirect1_ubo(struct comp_render_layer *self) { VkBufferUsageFlags usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; - VkMemoryPropertyFlags properties = - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | - VK_MEMORY_PROPERTY_HOST_CACHED_BIT; - - if (!vk_buffer_init(self->vk, sizeof(struct layer_transformation), - usage, properties, &self->equirect1_ubo.handle, - &self->equirect1_ubo.memory)) + VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + VK_MEMORY_PROPERTY_HOST_CACHED_BIT; + + if (!vk_buffer_init(self->vk, sizeof(struct layer_transformation), usage, properties, + &self->equirect1_ubo.handle, &self->equirect1_ubo.memory)) return false; - VkResult res = self->vk->vkMapMemory( - self->vk->device, self->equirect1_ubo.memory, 0, VK_WHOLE_SIZE, 0, - &self->equirect1_ubo.data); + VkResult res = self->vk->vkMapMemory(self->vk->device, self->equirect1_ubo.memory, 0, VK_WHOLE_SIZE, 0, + &self->equirect1_ubo.data); vk_check_error("vkMapMemory", res, false); - memcpy(self->equirect1_ubo.data, &self->equirect1_data, - sizeof(struct layer_equirect1_data)); + memcpy(self->equirect1_ubo.data, &self->equirect1_data, sizeof(struct layer_equirect1_data)); return true; } @@ -114,23 +98,18 @@ static bool _init_equirect2_ubo(struct comp_render_layer *self) { VkBufferUsageFlags usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; - VkMemoryPropertyFlags properties = - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | - VK_MEMORY_PROPERTY_HOST_CACHED_BIT; - - if (!vk_buffer_init(self->vk, sizeof(struct layer_transformation), - usage, properties, &self->equirect2_ubo.handle, - &self->equirect2_ubo.memory)) + VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | + VK_MEMORY_PROPERTY_HOST_CACHED_BIT; + + if (!vk_buffer_init(self->vk, sizeof(struct layer_transformation), usage, properties, + &self->equirect2_ubo.handle, &self->equirect2_ubo.memory)) return false; - VkResult res = self->vk->vkMapMemory( - self->vk->device, self->equirect2_ubo.memory, 0, VK_WHOLE_SIZE, 0, - &self->equirect2_ubo.data); + VkResult res = self->vk->vkMapMemory(self->vk->device, self->equirect2_ubo.memory, 0, VK_WHOLE_SIZE, 0, + &self->equirect2_ubo.data); vk_check_error("vkMapMemory", res, false); - memcpy(self->equirect2_ubo.data, &self->equirect2_data, - sizeof(struct layer_equirect2_data)); + memcpy(self->equirect2_ubo.data, &self->equirect2_data, sizeof(struct layer_equirect2_data)); return true; } @@ -179,12 +158,9 @@ _update_descriptor(struct comp_render_layer *self, vk->vkUpdateDescriptorSets(vk->device, 2, sets, 0, NULL); } -#if defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT1) || \ - defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT2) +#if defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT1) || defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT2) static void -_update_descriptor_equirect(struct comp_render_layer *self, - VkDescriptorSet set, - VkBuffer buffer) +_update_descriptor_equirect(struct comp_render_layer *self, VkDescriptorSet set, VkBuffer buffer) { VkWriteDescriptorSet *sets = (VkWriteDescriptorSet[]){ { @@ -208,40 +184,32 @@ _update_descriptor_equirect(struct comp_render_layer *self, #endif void -comp_layer_update_descriptors(struct comp_render_layer *self, - VkSampler sampler, - VkImageView image_view) +comp_layer_update_descriptors(struct comp_render_layer *self, VkSampler sampler, VkImageView image_view) { for (uint32_t eye = 0; eye < 2; eye++) - _update_descriptor(self, self->vk, self->descriptor_sets[eye], - self->transformation_ubos[eye].handle, + _update_descriptor(self, self->vk, self->descriptor_sets[eye], self->transformation_ubos[eye].handle, sampler, image_view); } #ifdef XRT_FEATURE_OPENXR_LAYER_EQUIRECT1 void -comp_layer_update_equirect1_descriptor(struct comp_render_layer *self, - struct xrt_layer_equirect1_data *data) +comp_layer_update_equirect1_descriptor(struct comp_render_layer *self, struct xrt_layer_equirect1_data *data) { - _update_descriptor_equirect(self, self->descriptor_equirect, - self->equirect1_ubo.handle); + _update_descriptor_equirect(self, self->descriptor_equirect, self->equirect1_ubo.handle); self->equirect1_data = (struct layer_equirect1_data){ .radius = data->radius, .scale = data->scale, .bias = data->bias, }; - memcpy(self->equirect1_ubo.data, &self->equirect1_data, - sizeof(struct layer_equirect1_data)); + memcpy(self->equirect1_ubo.data, &self->equirect1_data, sizeof(struct layer_equirect1_data)); } #endif #ifdef XRT_FEATURE_OPENXR_LAYER_EQUIRECT2 void -comp_layer_update_equirect2_descriptor(struct comp_render_layer *self, - struct xrt_layer_equirect2_data *data) +comp_layer_update_equirect2_descriptor(struct comp_render_layer *self, struct xrt_layer_equirect2_data *data) { - _update_descriptor_equirect(self, self->descriptor_equirect, - self->equirect2_ubo.handle); + _update_descriptor_equirect(self, self->descriptor_equirect, self->equirect2_ubo.handle); self->equirect2_data = (struct layer_equirect2_data){ .radius = data->radius, @@ -249,8 +217,7 @@ comp_layer_update_equirect2_descriptor(struct comp_render_layer *self, .upper_vertical_angle = data->upper_vertical_angle, .lower_vertical_angle = data->lower_vertical_angle, }; - memcpy(self->equirect2_ubo.data, &self->equirect2_data, - sizeof(struct layer_equirect2_data)); + memcpy(self->equirect2_ubo.data, &self->equirect2_data, sizeof(struct layer_equirect2_data)); } #endif @@ -261,12 +228,10 @@ comp_layer_update_stereo_descriptors(struct comp_render_layer *self, VkImageView left_image_view, VkImageView right_image_view) { - _update_descriptor(self, self->vk, self->descriptor_sets[0], - self->transformation_ubos[0].handle, left_sampler, + _update_descriptor(self, self->vk, self->descriptor_sets[0], self->transformation_ubos[0].handle, left_sampler, left_image_view); - _update_descriptor(self, self->vk, self->descriptor_sets[1], - self->transformation_ubos[1].handle, right_sampler, + _update_descriptor(self, self->vk, self->descriptor_sets[1], self->transformation_ubos[1].handle, right_sampler, right_image_view); } @@ -306,21 +271,16 @@ _init(struct comp_render_layer *self, }, }; - if (!vk_init_descriptor_pool(self->vk, pool_sizes, - ARRAY_SIZE(pool_sizes), 3, - &self->descriptor_pool)) + if (!vk_init_descriptor_pool(self->vk, pool_sizes, ARRAY_SIZE(pool_sizes), 3, &self->descriptor_pool)) return false; for (uint32_t eye = 0; eye < 2; eye++) - if (!vk_allocate_descriptor_sets( - self->vk, self->descriptor_pool, 1, layout, - &self->descriptor_sets[eye])) + if (!vk_allocate_descriptor_sets(self->vk, self->descriptor_pool, 1, layout, + &self->descriptor_sets[eye])) return false; -#if defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT1) || \ - defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT2) - if (!vk_allocate_descriptor_sets(self->vk, self->descriptor_pool, 1, - layout_equirect, +#if defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT1) || defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT2) + if (!vk_allocate_descriptor_sets(self->vk, self->descriptor_pool, 1, layout_equirect, &self->descriptor_equirect)) return false; #endif @@ -337,26 +297,21 @@ comp_layer_draw(struct comp_render_layer *self, const struct xrt_matrix_4x4 *vp_world, const struct xrt_matrix_4x4 *vp_eye) { - if (eye == 0 && - (self->visibility & XRT_LAYER_EYE_VISIBILITY_LEFT_BIT) == 0) { + if (eye == 0 && (self->visibility & XRT_LAYER_EYE_VISIBILITY_LEFT_BIT) == 0) { return; } - if (eye == 1 && - (self->visibility & XRT_LAYER_EYE_VISIBILITY_RIGHT_BIT) == 0) { + if (eye == 1 && (self->visibility & XRT_LAYER_EYE_VISIBILITY_RIGHT_BIT) == 0) { return; } - self->vk->vkCmdBindPipeline(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline); + self->vk->vkCmdBindPipeline(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); // Is this layer viewspace or not. const struct xrt_matrix_4x4 *vp = self->view_space ? vp_eye : vp_world; switch (self->type) { - case XRT_LAYER_STEREO_PROJECTION: - _update_mvp_matrix(self, eye, &proj_scale); - break; + case XRT_LAYER_STEREO_PROJECTION: _update_mvp_matrix(self, eye, &proj_scale); break; case XRT_LAYER_QUAD: case XRT_LAYER_CYLINDER: case XRT_LAYER_EQUIRECT1: @@ -368,27 +323,22 @@ comp_layer_draw(struct comp_render_layer *self, } - if (self->type == XRT_LAYER_EQUIRECT1 || - self->type == XRT_LAYER_EQUIRECT2) { + if (self->type == XRT_LAYER_EQUIRECT1 || self->type == XRT_LAYER_EQUIRECT2) { const VkDescriptorSet sets[2] = { self->descriptor_sets[eye], self->descriptor_equirect, }; - self->vk->vkCmdBindDescriptorSets( - cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layout, 0, 2, sets, 0, NULL); + self->vk->vkCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 2, + sets, 0, NULL); } else { - self->vk->vkCmdBindDescriptorSets( - cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layout, 0, 1, &self->descriptor_sets[eye], 0, - NULL); + self->vk->vkCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, + &self->descriptor_sets[eye], 0, NULL); } VkDeviceSize offsets[1] = {0}; - self->vk->vkCmdBindVertexBuffers(cmd_buffer, 0, 1, - &vertex_buffer->handle, &offsets[0]); + self->vk->vkCmdBindVertexBuffers(cmd_buffer, 0, 1, &vertex_buffer->handle, &offsets[0]); self->vk->vkCmdDraw(cmd_buffer, vertex_buffer->size, 1, 0, 0); } @@ -478,14 +428,12 @@ _calculate_unit_cylinder_segment_vertices(float central_angle) } bool -comp_layer_update_cylinder_vertex_buffer(struct comp_render_layer *self, - float central_angle) +comp_layer_update_cylinder_vertex_buffer(struct comp_render_layer *self, float central_angle) { _calculate_unit_cylinder_segment_vertices(central_angle); struct vk_bundle *vk = self->vk; - return vk_update_buffer(vk, cylinder_vertices, - sizeof(float) * ARRAY_SIZE(cylinder_vertices), + return vk_update_buffer(vk, cylinder_vertices, sizeof(float) * ARRAY_SIZE(cylinder_vertices), self->cylinder.vertex_buffer.memory); return true; @@ -497,13 +445,10 @@ _init_cylinder_vertex_buffer(struct comp_render_layer *self) struct vk_bundle *vk = self->vk; VkBufferUsageFlags usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; - VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - if (!vk_buffer_init(vk, sizeof(float) * ARRAY_SIZE(cylinder_vertices), - usage, properties, - &self->cylinder.vertex_buffer.handle, - &self->cylinder.vertex_buffer.memory)) + if (!vk_buffer_init(vk, sizeof(float) * ARRAY_SIZE(cylinder_vertices), usage, properties, + &self->cylinder.vertex_buffer.handle, &self->cylinder.vertex_buffer.memory)) return false; self->cylinder.vertex_buffer.size = CYLINDER_VERTICES; @@ -517,9 +462,7 @@ comp_layer_get_cylinder_vertex_buffer(struct comp_render_layer *self) } struct comp_render_layer * -comp_layer_create(struct vk_bundle *vk, - VkDescriptorSetLayout *layout, - VkDescriptorSetLayout *layout_equirect) +comp_layer_create(struct vk_bundle *vk, VkDescriptorSetLayout *layout, VkDescriptorSetLayout *layout_equirect) { struct comp_render_layer *q = U_TYPED_CALLOC(struct comp_render_layer); @@ -543,8 +486,7 @@ comp_layer_destroy(struct comp_render_layer *self) #ifdef XRT_FEATURE_OPENXR_LAYER_EQUIRECT2 vk_buffer_destroy(&self->equirect2_ubo, self->vk); #endif - self->vk->vkDestroyDescriptorPool(self->vk->device, - self->descriptor_pool, NULL); + self->vk->vkDestroyDescriptorPool(self->vk->device, self->descriptor_pool, NULL); vk_buffer_destroy(&self->cylinder.vertex_buffer, self->vk); diff --git a/src/xrt/compositor/main/comp_layer.h b/src/xrt/compositor/main/comp_layer.h index cd3975f9d..5e9830e06 100644 --- a/src/xrt/compositor/main/comp_layer.h +++ b/src/xrt/compositor/main/comp_layer.h @@ -77,9 +77,7 @@ struct comp_render_layer }; struct comp_render_layer * -comp_layer_create(struct vk_bundle *vk, - VkDescriptorSetLayout *layout, - VkDescriptorSetLayout *layout_equirect); +comp_layer_create(struct vk_bundle *vk, VkDescriptorSetLayout *layout, VkDescriptorSetLayout *layout_equirect); void comp_layer_draw(struct comp_render_layer *self, @@ -92,16 +90,13 @@ comp_layer_draw(struct comp_render_layer *self, const struct xrt_matrix_4x4 *vp_eye); void -comp_layer_set_model_matrix(struct comp_render_layer *self, - const struct xrt_matrix_4x4 *m); +comp_layer_set_model_matrix(struct comp_render_layer *self, const struct xrt_matrix_4x4 *m); void comp_layer_destroy(struct comp_render_layer *self); void -comp_layer_update_descriptors(struct comp_render_layer *self, - VkSampler sampler, - VkImageView image_view); +comp_layer_update_descriptors(struct comp_render_layer *self, VkSampler sampler, VkImageView image_view); void comp_layer_update_stereo_descriptors(struct comp_render_layer *self, @@ -117,16 +112,13 @@ struct vk_buffer * comp_layer_get_cylinder_vertex_buffer(struct comp_render_layer *self); bool -comp_layer_update_cylinder_vertex_buffer(struct comp_render_layer *self, - float central_angle); +comp_layer_update_cylinder_vertex_buffer(struct comp_render_layer *self, float central_angle); #ifdef XRT_FEATURE_OPENXR_LAYER_EQUIRECT1 void -comp_layer_update_equirect1_descriptor(struct comp_render_layer *self, - struct xrt_layer_equirect1_data *data); +comp_layer_update_equirect1_descriptor(struct comp_render_layer *self, struct xrt_layer_equirect1_data *data); #endif #ifdef XRT_FEATURE_OPENXR_LAYER_EQUIRECT2 void -comp_layer_update_equirect2_descriptor(struct comp_render_layer *self, - struct xrt_layer_equirect2_data *data); +comp_layer_update_equirect2_descriptor(struct comp_render_layer *self, struct xrt_layer_equirect2_data *data); #endif diff --git a/src/xrt/compositor/main/comp_layer_renderer.c b/src/xrt/compositor/main/comp_layer_renderer.c index 37df99257..b3202f743 100644 --- a/src/xrt/compositor/main/comp_layer_renderer.c +++ b/src/xrt/compositor/main/comp_layer_renderer.c @@ -69,8 +69,7 @@ _init_render_pass(struct vk_bundle *vk, .pDependencies = NULL, }; - VkResult res = vk->vkCreateRenderPass(vk->device, &renderpass_info, - NULL, out_render_pass); + VkResult res = vk->vkCreateRenderPass(vk->device, &renderpass_info, NULL, out_render_pass); vk_check_error("vkCreateRenderPass", res, false); return true; @@ -90,21 +89,18 @@ _init_descriptor_layout(struct comp_layer_renderer *self) .binding = self->transformation_ubo_binding, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - .stageFlags = VK_SHADER_STAGE_VERTEX_BIT | - VK_SHADER_STAGE_FRAGMENT_BIT, + .stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, }, { .binding = self->texture_binding, .descriptorCount = 1, - .descriptorType = - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, }, }, }; - VkResult res = vk->vkCreateDescriptorSetLayout( - vk->device, &info, NULL, &self->descriptor_set_layout); + VkResult res = vk->vkCreateDescriptorSetLayout(vk->device, &info, NULL, &self->descriptor_set_layout); vk_check_error("vkCreateDescriptorSetLayout", res, false); @@ -130,8 +126,7 @@ _init_descriptor_layout_equirect(struct comp_layer_renderer *self) }, }; - VkResult res = vk->vkCreateDescriptorSetLayout( - vk->device, &info, NULL, &self->descriptor_set_layout_equirect); + VkResult res = vk->vkCreateDescriptorSetLayout(vk->device, &info, NULL, &self->descriptor_set_layout_equirect); vk_check_error("vkCreateDescriptorSetLayout", res, false); @@ -143,8 +138,8 @@ _init_pipeline_layout(struct comp_layer_renderer *self) { struct vk_bundle *vk = self->vk; - const VkDescriptorSetLayout set_layouts[2] = { - self->descriptor_set_layout, self->descriptor_set_layout_equirect}; + const VkDescriptorSetLayout set_layouts[2] = {self->descriptor_set_layout, + self->descriptor_set_layout_equirect}; VkPipelineLayoutCreateInfo info = { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, @@ -152,8 +147,7 @@ _init_pipeline_layout(struct comp_layer_renderer *self) .pSetLayouts = set_layouts, }; - VkResult res = vk->vkCreatePipelineLayout(vk->device, &info, NULL, - &self->pipeline_layout); + VkResult res = vk->vkCreatePipelineLayout(vk->device, &info, NULL, &self->pipeline_layout); vk_check_error("vkCreatePipelineLayout", res, false); @@ -169,8 +163,7 @@ _init_pipeline_cache(struct comp_layer_renderer *self) .sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, }; - VkResult res = vk->vkCreatePipelineCache(vk->device, &info, NULL, - &self->pipeline_cache); + VkResult res = vk->vkCreatePipelineCache(vk->device, &info, NULL, &self->pipeline_cache); vk_check_error("vkCreatePipelineCache", res, false); @@ -201,9 +194,7 @@ _init_graphics_pipeline(struct comp_layer_renderer *self, { struct vk_bundle *vk = self->vk; - VkBlendFactor blend_factor = premultiplied_alpha - ? VK_BLEND_FACTOR_ONE - : VK_BLEND_FACTOR_SRC_ALPHA; + VkBlendFactor blend_factor = premultiplied_alpha ? VK_BLEND_FACTOR_ONE : VK_BLEND_FACTOR_SRC_ALPHA; struct comp_pipeline_config config = { .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, @@ -211,14 +202,12 @@ _init_graphics_pipeline(struct comp_layer_renderer *self, .attribs = (VkVertexInputAttributeDescription[]){ {0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, - {1, 0, VK_FORMAT_R32G32_SFLOAT, - offsetof(struct comp_layer_vertex, uv)}, + {1, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(struct comp_layer_vertex, uv)}, }, .attrib_count = 2, .depth_stencil_state = &(VkPipelineDepthStencilStateCreateInfo){ - .sType = - VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, .depthTestEnable = VK_FALSE, .depthWriteEnable = VK_FALSE, .depthCompareOp = VK_COMPARE_OP_NEVER, @@ -226,9 +215,8 @@ _init_graphics_pipeline(struct comp_layer_renderer *self, .blend_attachments = &(VkPipelineColorBlendAttachmentState){ .blendEnable = VK_TRUE, - .colorWriteMask = - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | - VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, + .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | + VK_COLOR_COMPONENT_A_BIT, .srcColorBlendFactor = blend_factor, .dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, .colorBlendOp = VK_BLEND_OP_ADD, @@ -238,8 +226,7 @@ _init_graphics_pipeline(struct comp_layer_renderer *self, }, .rasterization_state = &(VkPipelineRasterizationStateCreateInfo){ - .sType = - VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, .polygonMode = VK_POLYGON_MODE_FILL, .cullMode = VK_CULL_MODE_BACK_BIT, .frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, @@ -267,8 +254,7 @@ _init_graphics_pipeline(struct comp_layer_renderer *self, .layout = self->pipeline_layout, .pVertexInputState = &(VkPipelineVertexInputStateCreateInfo){ - .sType = - VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, .pVertexAttributeDescriptions = config.attribs, .vertexBindingDescriptionCount = 1, .pVertexBindingDescriptions = @@ -281,23 +267,20 @@ _init_graphics_pipeline(struct comp_layer_renderer *self, }, .pInputAssemblyState = &(VkPipelineInputAssemblyStateCreateInfo){ - .sType = - VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, .topology = config.topology, .primitiveRestartEnable = VK_FALSE, }, .pViewportState = &(VkPipelineViewportStateCreateInfo){ - .sType = - VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, .viewportCount = 1, .scissorCount = 1, }, .pRasterizationState = config.rasterization_state, .pMultisampleState = &(VkPipelineMultisampleStateCreateInfo){ - .sType = - VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, .rasterizationSamples = self->sample_count, .minSampleShading = 0.0f, .pSampleMask = &(uint32_t){0xFFFFFFFF}, @@ -306,8 +289,7 @@ _init_graphics_pipeline(struct comp_layer_renderer *self, .pDepthStencilState = config.depth_stencil_state, .pColorBlendState = &(VkPipelineColorBlendStateCreateInfo){ - .sType = - VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .logicOpEnable = VK_FALSE, .attachmentCount = 1, .blendConstants = {0, 0, 0, 0}, @@ -318,8 +300,7 @@ _init_graphics_pipeline(struct comp_layer_renderer *self, .renderPass = self->render_pass, .pDynamicState = &(VkPipelineDynamicStateCreateInfo){ - .sType = - VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, .dynamicStateCount = 2, .pDynamicStates = (VkDynamicState[]){ @@ -331,8 +312,7 @@ _init_graphics_pipeline(struct comp_layer_renderer *self, }; VkResult res; - res = vk->vkCreateGraphicsPipelines(vk->device, self->pipeline_cache, 1, - &pipeline_info, NULL, pipeline); + res = vk->vkCreateGraphicsPipelines(vk->device, self->pipeline_cache, 1, &pipeline_info, NULL, pipeline); vk_check_error("vkCreateGraphicsPipelines", res, false); @@ -357,18 +337,15 @@ _init_vertex_buffer(struct comp_layer_renderer *self) struct vk_bundle *vk = self->vk; VkBufferUsageFlags usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; - VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + VkMemoryPropertyFlags properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - if (!vk_buffer_init(vk, sizeof(float) * ARRAY_SIZE(plane_vertices), - usage, properties, &self->vertex_buffer.handle, - &self->vertex_buffer.memory)) + if (!vk_buffer_init(vk, sizeof(float) * ARRAY_SIZE(plane_vertices), usage, properties, + &self->vertex_buffer.handle, &self->vertex_buffer.memory)) return false; self->vertex_buffer.size = PLANE_VERTICES; - return vk_update_buffer(vk, plane_vertices, - sizeof(float) * ARRAY_SIZE(plane_vertices), + return vk_update_buffer(vk, plane_vertices, sizeof(float) * ARRAY_SIZE(plane_vertices), self->vertex_buffer.memory); } @@ -381,68 +358,51 @@ _render_eye(struct comp_layer_renderer *self, struct xrt_matrix_4x4 vp_world; struct xrt_matrix_4x4 vp_eye; struct xrt_matrix_4x4 vp_inv; - math_matrix_4x4_multiply(&self->mat_projection[eye], - &self->mat_world_view[eye], &vp_world); - math_matrix_4x4_multiply(&self->mat_projection[eye], - &self->mat_eye_view[eye], &vp_eye); + math_matrix_4x4_multiply(&self->mat_projection[eye], &self->mat_world_view[eye], &vp_world); + math_matrix_4x4_multiply(&self->mat_projection[eye], &self->mat_eye_view[eye], &vp_eye); - math_matrix_4x4_inverse_view_projection( - &self->mat_world_view[eye], &self->mat_projection[eye], &vp_inv); + math_matrix_4x4_inverse_view_projection(&self->mat_world_view[eye], &self->mat_projection[eye], &vp_inv); for (uint32_t i = 0; i < self->num_layers; i++) { - bool unpremultiplied_alpha = - self->layers[i]->flags & - XRT_LAYER_COMPOSITION_UNPREMULTIPLIED_ALPHA_BIT; + bool unpremultiplied_alpha = self->layers[i]->flags & XRT_LAYER_COMPOSITION_UNPREMULTIPLIED_ALPHA_BIT; struct vk_buffer *vertex_buffer; if (self->layers[i]->type == XRT_LAYER_CYLINDER) { - vertex_buffer = comp_layer_get_cylinder_vertex_buffer( - self->layers[i]); + vertex_buffer = comp_layer_get_cylinder_vertex_buffer(self->layers[i]); } else { vertex_buffer = &self->vertex_buffer; } VkPipeline pipeline = - unpremultiplied_alpha - ? self->pipeline_premultiplied_alpha - : self->pipeline_unpremultiplied_alpha; + unpremultiplied_alpha ? self->pipeline_premultiplied_alpha : self->pipeline_unpremultiplied_alpha; if (self->layers[i]->type == XRT_LAYER_EQUIRECT2) { pipeline = self->pipeline_equirect2; - comp_layer_draw(self->layers[i], eye, pipeline, - pipeline_layout, cmd_buffer, - vertex_buffer, &vp_inv, &vp_inv); + comp_layer_draw(self->layers[i], eye, pipeline, pipeline_layout, cmd_buffer, vertex_buffer, + &vp_inv, &vp_inv); } else if (self->layers[i]->type == XRT_LAYER_EQUIRECT1) { pipeline = self->pipeline_equirect1; - comp_layer_draw(self->layers[i], eye, pipeline, - pipeline_layout, cmd_buffer, - vertex_buffer, &vp_inv, &vp_inv); + comp_layer_draw(self->layers[i], eye, pipeline, pipeline_layout, cmd_buffer, vertex_buffer, + &vp_inv, &vp_inv); } else { - comp_layer_draw(self->layers[i], eye, pipeline, - pipeline_layout, cmd_buffer, - vertex_buffer, &vp_world, &vp_eye); + comp_layer_draw(self->layers[i], eye, pipeline, pipeline_layout, cmd_buffer, vertex_buffer, + &vp_world, &vp_eye); } } } static bool -_init_frame_buffer(struct comp_layer_renderer *self, - VkFormat format, - VkRenderPass rp, - uint32_t eye) +_init_frame_buffer(struct comp_layer_renderer *self, VkFormat format, VkRenderPass rp, uint32_t eye) { struct vk_bundle *vk = self->vk; - VkImageUsageFlags usage = - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - VkResult res = vk_create_image_simple(vk, self->extent, format, usage, - &self->framebuffers[eye].memory, + VkResult res = vk_create_image_simple(vk, self->extent, format, usage, &self->framebuffers[eye].memory, &self->framebuffers[eye].image); vk_check_error("vk_create_image_simple", res, false); - vk_create_sampler(vk, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, - &self->framebuffers[eye].sampler); + vk_create_sampler(vk, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, &self->framebuffers[eye].sampler); VkImageSubresourceRange subresource_range = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, @@ -452,8 +412,8 @@ _init_frame_buffer(struct comp_layer_renderer *self, .layerCount = 1, }; - res = vk_create_view(vk, self->framebuffers[eye].image, format, - subresource_range, &self->framebuffers[eye].view); + res = + vk_create_view(vk, self->framebuffers[eye].image, format, subresource_range, &self->framebuffers[eye].view); vk_check_error("vk_create_view", res, false); @@ -467,27 +427,23 @@ _init_frame_buffer(struct comp_layer_renderer *self, .layers = 1, }; - res = vk->vkCreateFramebuffer(vk->device, &framebuffer_info, NULL, - &self->framebuffers[eye].handle); + res = vk->vkCreateFramebuffer(vk->device, &framebuffer_info, NULL, &self->framebuffers[eye].handle); vk_check_error("vkCreateFramebuffer", res, false); return true; } void -comp_layer_renderer_allocate_layers(struct comp_layer_renderer *self, - uint32_t num_layers) +comp_layer_renderer_allocate_layers(struct comp_layer_renderer *self, uint32_t num_layers) { struct vk_bundle *vk = self->vk; self->num_layers = num_layers; - self->layers = - U_TYPED_ARRAY_CALLOC(struct comp_render_layer *, self->num_layers); + self->layers = U_TYPED_ARRAY_CALLOC(struct comp_render_layer *, self->num_layers); for (uint32_t i = 0; i < self->num_layers; i++) { self->layers[i] = - comp_layer_create(vk, &self->descriptor_set_layout, - &self->descriptor_set_layout_equirect); + comp_layer_create(vk, &self->descriptor_set_layout, &self->descriptor_set_layout_equirect); } } @@ -503,11 +459,8 @@ comp_layer_renderer_destroy_layers(struct comp_layer_renderer *self) } static bool -_init(struct comp_layer_renderer *self, - struct comp_shaders *s, - struct vk_bundle *vk, - VkExtent2D extent, - VkFormat format) +_init( + struct comp_layer_renderer *self, struct comp_shaders *s, struct vk_bundle *vk, VkExtent2D extent, VkFormat format) { self->vk = vk; @@ -529,9 +482,8 @@ _init(struct comp_layer_renderer *self, math_matrix_4x4_identity(&self->mat_eye_view[i]); } - if (!_init_render_pass(vk, format, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - self->sample_count, &self->render_pass)) + if (!_init_render_pass(vk, format, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, self->sample_count, + &self->render_pass)) return false; for (uint32_t i = 0; i < 2; i++) @@ -548,23 +500,19 @@ _init(struct comp_layer_renderer *self, return false; - if (!_init_graphics_pipeline(self, s->layer_vert, s->layer_frag, false, - &self->pipeline_premultiplied_alpha)) { + if (!_init_graphics_pipeline(self, s->layer_vert, s->layer_frag, false, &self->pipeline_premultiplied_alpha)) { return false; } - if (!_init_graphics_pipeline(self, s->layer_vert, s->layer_frag, true, - &self->pipeline_unpremultiplied_alpha)) { + if (!_init_graphics_pipeline(self, s->layer_vert, s->layer_frag, true, &self->pipeline_unpremultiplied_alpha)) { return false; } - if (!_init_graphics_pipeline(self, s->equirect1_vert, s->equirect1_frag, - true, &self->pipeline_equirect1)) { + if (!_init_graphics_pipeline(self, s->equirect1_vert, s->equirect1_frag, true, &self->pipeline_equirect1)) { return false; } - if (!_init_graphics_pipeline(self, s->equirect2_vert, s->equirect2_frag, - true, &self->pipeline_equirect2)) { + if (!_init_graphics_pipeline(self, s->equirect2_vert, s->equirect2_frag, true, &self->pipeline_equirect2)) { return false; } @@ -575,13 +523,9 @@ _init(struct comp_layer_renderer *self, } struct comp_layer_renderer * -comp_layer_renderer_create(struct vk_bundle *vk, - struct comp_shaders *s, - VkExtent2D extent, - VkFormat format) +comp_layer_renderer_create(struct vk_bundle *vk, struct comp_shaders *s, VkExtent2D extent, VkFormat format) { - struct comp_layer_renderer *r = - U_TYPED_CALLOC(struct comp_layer_renderer); + struct comp_layer_renderer *r = U_TYPED_CALLOC(struct comp_layer_renderer); _init(r, s, vk, extent, format); return r; } @@ -623,14 +567,11 @@ _render_pass_begin(struct vk_bundle *vk, }, }; - vk->vkCmdBeginRenderPass(cmd_buffer, &render_pass_info, - VK_SUBPASS_CONTENTS_INLINE); + vk->vkCmdBeginRenderPass(cmd_buffer, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE); } static void -_render_stereo(struct comp_layer_renderer *self, - struct vk_bundle *vk, - VkCommandBuffer cmd_buffer) +_render_stereo(struct comp_layer_renderer *self, struct vk_bundle *vk, VkCommandBuffer cmd_buffer) { VkViewport viewport = { 0.0f, 0.0f, self->extent.width, self->extent.height, 0.0f, 1.0f, @@ -643,8 +584,7 @@ _render_stereo(struct comp_layer_renderer *self, vk->vkCmdSetScissor(cmd_buffer, 0, 1, &scissor); for (uint32_t eye = 0; eye < 2; eye++) { - _render_pass_begin(vk, self->render_pass, self->extent, - background_color, + _render_pass_begin(vk, self->render_pass, self->extent, background_color, self->framebuffers[eye].handle, cmd_buffer); _render_eye(self, eye, cmd_buffer, self->pipeline_layout); @@ -677,8 +617,7 @@ _destroy_framebuffer(struct comp_layer_renderer *self, uint32_t i) vk->vkDestroyImageView(vk->device, self->framebuffers[i].view, NULL); vk->vkDestroyImage(vk->device, self->framebuffers[i].image, NULL); vk->vkFreeMemory(vk->device, self->framebuffers[i].memory, NULL); - vk->vkDestroyFramebuffer(vk->device, self->framebuffers[i].handle, - NULL); + vk->vkDestroyFramebuffer(vk->device, self->framebuffers[i].handle, NULL); vk->vkDestroySampler(vk->device, self->framebuffers[i].sampler, NULL); } @@ -702,20 +641,15 @@ comp_layer_renderer_destroy(struct comp_layer_renderer *self) vk->vkDestroyRenderPass(vk->device, self->render_pass, NULL); vk->vkDestroyPipelineLayout(vk->device, self->pipeline_layout, NULL); - vk->vkDestroyDescriptorSetLayout(vk->device, - self->descriptor_set_layout, NULL); - vk->vkDestroyDescriptorSetLayout( - vk->device, self->descriptor_set_layout_equirect, NULL); - vk->vkDestroyPipeline(vk->device, self->pipeline_premultiplied_alpha, - NULL); - vk->vkDestroyPipeline(vk->device, self->pipeline_unpremultiplied_alpha, - NULL); + vk->vkDestroyDescriptorSetLayout(vk->device, self->descriptor_set_layout, NULL); + vk->vkDestroyDescriptorSetLayout(vk->device, self->descriptor_set_layout_equirect, NULL); + vk->vkDestroyPipeline(vk->device, self->pipeline_premultiplied_alpha, NULL); + vk->vkDestroyPipeline(vk->device, self->pipeline_unpremultiplied_alpha, NULL); vk->vkDestroyPipeline(vk->device, self->pipeline_equirect1, NULL); vk->vkDestroyPipeline(vk->device, self->pipeline_equirect2, NULL); for (uint32_t i = 0; i < ARRAY_SIZE(self->shader_modules); i++) - vk->vkDestroyShaderModule(vk->device, self->shader_modules[i], - NULL); + vk->vkDestroyShaderModule(vk->device, self->shader_modules[i], NULL); vk_buffer_destroy(&self->vertex_buffer, vk); @@ -723,9 +657,7 @@ comp_layer_renderer_destroy(struct comp_layer_renderer *self) } void -comp_layer_renderer_set_fov(struct comp_layer_renderer *self, - const struct xrt_fov *fov, - uint32_t eye) +comp_layer_renderer_set_fov(struct comp_layer_renderer *self, const struct xrt_fov *fov, uint32_t eye) { const float tan_left = tanf(fov->angle_left); const float tan_right = tanf(fov->angle_right); @@ -743,8 +675,7 @@ comp_layer_renderer_set_fov(struct comp_layer_renderer *self, const float a32 = (tan_up + tan_down) / tan_height; const float a33 = -self->farZ / (self->farZ - self->nearZ); - const float a43 = - -(self->farZ * self->nearZ) / (self->farZ - self->nearZ); + const float a43 = -(self->farZ * self->nearZ) / (self->farZ - self->nearZ); // clang-format off self->mat_projection[eye] = (struct xrt_matrix_4x4) { diff --git a/src/xrt/compositor/main/comp_layer_renderer.h b/src/xrt/compositor/main/comp_layer_renderer.h index a9283bac6..5fbf4cd12 100644 --- a/src/xrt/compositor/main/comp_layer_renderer.h +++ b/src/xrt/compositor/main/comp_layer_renderer.h @@ -64,10 +64,7 @@ struct comp_layer_renderer }; struct comp_layer_renderer * -comp_layer_renderer_create(struct vk_bundle *vk, - struct comp_shaders *s, - VkExtent2D extent, - VkFormat format); +comp_layer_renderer_create(struct vk_bundle *vk, struct comp_shaders *s, VkExtent2D extent, VkFormat format); void comp_layer_renderer_destroy(struct comp_layer_renderer *self); @@ -76,9 +73,7 @@ void comp_layer_renderer_draw(struct comp_layer_renderer *self); void -comp_layer_renderer_set_fov(struct comp_layer_renderer *self, - const struct xrt_fov *fov, - uint32_t eye); +comp_layer_renderer_set_fov(struct comp_layer_renderer *self, const struct xrt_fov *fov, uint32_t eye); void comp_layer_renderer_set_pose(struct comp_layer_renderer *self, @@ -87,8 +82,7 @@ comp_layer_renderer_set_pose(struct comp_layer_renderer *self, uint32_t eye); void -comp_layer_renderer_allocate_layers(struct comp_layer_renderer *self, - uint32_t num_layers); +comp_layer_renderer_allocate_layers(struct comp_layer_renderer *self, uint32_t num_layers); void comp_layer_renderer_destroy_layers(struct comp_layer_renderer *self); diff --git a/src/xrt/compositor/main/comp_renderer.c b/src/xrt/compositor/main/comp_renderer.c index cee19ef19..eb65edc51 100644 --- a/src/xrt/compositor/main/comp_renderer.c +++ b/src/xrt/compositor/main/comp_renderer.c @@ -153,8 +153,7 @@ renderer_submit_queue(struct comp_renderer *r) VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, }; - ret = vk->vkWaitForFences(vk->device, 1, &r->fences[r->current_buffer], - VK_TRUE, UINT64_MAX); + ret = vk->vkWaitForFences(vk->device, 1, &r->fences[r->current_buffer], VK_TRUE, UINT64_MAX); if (ret != VK_SUCCESS) COMP_ERROR(r->c, "vkWaitForFences: %s", vk_result_string(ret)); @@ -173,17 +172,14 @@ renderer_submit_queue(struct comp_renderer *r) .pSignalSemaphores = &r->semaphores.render_complete, }; - ret = vk_locked_submit(vk, r->queue, 1, &comp_submit_info, - r->fences[r->current_buffer]); + ret = vk_locked_submit(vk, r->queue, 1, &comp_submit_info, r->fences[r->current_buffer]); if (ret != VK_SUCCESS) { COMP_ERROR(r->c, "vkQueueSubmit: %s", vk_result_string(ret)); } } static void -renderer_build_rendering(struct comp_renderer *r, - struct comp_rendering *rr, - uint32_t index) +renderer_build_rendering(struct comp_renderer *r, struct comp_rendering *rr, uint32_t index) { struct comp_compositor *c = r->c; @@ -194,10 +190,8 @@ renderer_build_rendering(struct comp_renderer *r, data.height = r->c->target->height; bool pre_rotate = false; - if (r->c->target->surface_transform & - VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR || - r->c->target->surface_transform & - VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR) { + if (r->c->target->surface_transform & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR || + r->c->target->surface_transform & VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR) { COMP_DEBUG(c, "Swapping width and height," "since we are pre rotating"); @@ -205,10 +199,8 @@ renderer_build_rendering(struct comp_renderer *r, } - float w = pre_rotate ? r->c->xdev->hmd->screens[0].h_pixels - : r->c->xdev->hmd->screens[0].w_pixels; - float h = pre_rotate ? r->c->xdev->hmd->screens[0].w_pixels - : r->c->xdev->hmd->screens[0].h_pixels; + float w = pre_rotate ? r->c->xdev->hmd->screens[0].h_pixels : r->c->xdev->hmd->screens[0].w_pixels; + float h = pre_rotate ? r->c->xdev->hmd->screens[0].w_pixels : r->c->xdev->hmd->screens[0].h_pixels; float scale_x = (float)r->c->target->width / w; float scale_y = (float)r->c->target->height / h; @@ -249,8 +241,7 @@ renderer_build_rendering(struct comp_renderer *r, }; if (pre_rotate) { - math_matrix_2x2_multiply(&l_v->rot, &rotation_90_cw, - &l_data.rot); + math_matrix_2x2_multiply(&l_v->rot, &rotation_90_cw, &l_data.rot); } struct xrt_view *r_v = &r->c->xdev->hmd->views[1]; @@ -279,8 +270,7 @@ renderer_build_rendering(struct comp_renderer *r, }; if (pre_rotate) { - math_matrix_2x2_multiply(&r_v->rot, &rotation_90_cw, - &r_data.rot); + math_matrix_2x2_multiply(&r_v->rot, &rotation_90_cw, &r_data.rot); } /* @@ -352,15 +342,12 @@ renderer_create_fences(struct comp_renderer *r) struct vk_bundle *vk = &r->c->vk; for (uint32_t i = 0; i < r->num_buffers; i++) { - VkResult ret = vk->vkCreateFence( - vk->device, - &(VkFenceCreateInfo){ - .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, - .flags = VK_FENCE_CREATE_SIGNALED_BIT}, - NULL, &r->fences[i]); + VkResult ret = vk->vkCreateFence(vk->device, + &(VkFenceCreateInfo){.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, + .flags = VK_FENCE_CREATE_SIGNALED_BIT}, + NULL, &r->fences[i]); if (ret != VK_SUCCESS) { - COMP_ERROR(r->c, "vkCreateFence: %s", - vk_result_string(ret)); + COMP_ERROR(r->c, "vkCreateFence: %s", vk_result_string(ret)); } } } @@ -370,8 +357,7 @@ renderer_get_view_projection(struct comp_renderer *r) { struct xrt_space_relation relation; - xrt_device_get_tracked_pose(r->c->xdev, XRT_INPUT_GENERIC_HEAD_POSE, - r->c->last_frame_time_ns, &relation); + xrt_device_get_tracked_pose(r->c->xdev, XRT_INPUT_GENERIC_HEAD_POSE, r->c->last_frame_time_ns, &relation); struct xrt_vec3 eye_relation = { 0.063000f, /* TODO: get actual ipd_meters */ @@ -390,8 +376,7 @@ renderer_get_view_projection(struct comp_renderer *r) comp_layer_renderer_set_fov(r->lr, &fov, i); struct xrt_pose eye_pose; - xrt_device_get_view_pose(r->c->xdev, &eye_relation, i, - &eye_pose); + xrt_device_get_view_pose(r->c->xdev, &eye_relation, i, &eye_pose); struct xrt_space_relation result = {0}; struct xrt_space_graph xsg = {0}; @@ -409,8 +394,7 @@ renderer_init(struct comp_renderer *r) { struct vk_bundle *vk = &r->c->vk; - vk->vkGetDeviceQueue(vk->device, r->c->vk.queue_family_index, 0, - &r->queue); + vk->vkGetDeviceQueue(vk->device, r->c->vk.queue_family_index, 0, &r->queue); renderer_init_semaphores(r); assert(r->c->target->num_images > 0); @@ -419,10 +403,8 @@ renderer_init(struct comp_renderer *r) renderer_create_fences(r); VkExtent2D extent; - if (r->c->target->surface_transform & - VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR || - r->c->target->surface_transform & - VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR) { + if (r->c->target->surface_transform & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR || + r->c->target->surface_transform & VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR) { // Swapping width and height, since we are pre rotating extent = (VkExtent2D){ .width = r->c->xdev->hmd->screens[0].h_pixels, @@ -435,17 +417,14 @@ renderer_init(struct comp_renderer *r) }; } - r->lr = comp_layer_renderer_create(vk, &r->c->shaders, extent, - VK_FORMAT_B8G8R8A8_SRGB); + r->lr = comp_layer_renderer_create(vk, &r->c->shaders, extent, VK_FORMAT_B8G8R8A8_SRGB); renderer_allocate_renderings(r); renderer_build_renderings(r); } VkImageView -get_image_view(struct comp_swapchain_image *image, - enum xrt_layer_composition_flags flags, - uint32_t array_index) +get_image_view(struct comp_swapchain_image *image, enum xrt_layer_composition_flags flags, uint32_t array_index) { if (flags & XRT_LAYER_COMPOSITION_BLEND_TEXTURE_SOURCE_ALPHA_BIT) { return image->views.alpha[array_index]; @@ -464,9 +443,8 @@ comp_renderer_set_quad_layer(struct comp_renderer *r, l->transformation_ubo_binding = r->lr->transformation_ubo_binding; l->texture_binding = r->lr->texture_binding; - comp_layer_update_descriptors( - l, image->sampler, - get_image_view(image, data->flags, data->quad.sub.array_index)); + comp_layer_update_descriptors(l, image->sampler, + get_image_view(image, data->flags, data->quad.sub.array_index)); struct xrt_vec3 s = {data->quad.size.x, data->quad.size.y, 1.0f}; struct xrt_matrix_4x4 model_matrix; @@ -479,8 +457,7 @@ comp_renderer_set_quad_layer(struct comp_renderer *r, l->type = XRT_LAYER_QUAD; l->visibility = data->quad.visibility; l->flags = data->flags; - l->view_space = - (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; + l->view_space = (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; for (uint32_t i = 0; i < 2; i++) { l->transformation[i].offset = data->quad.sub.rect.offset; @@ -502,25 +479,21 @@ comp_renderer_set_cylinder_layer(struct comp_renderer *r, l->type = XRT_LAYER_CYLINDER; l->visibility = data->cylinder.visibility; l->flags = data->flags; - l->view_space = - (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; + l->view_space = (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; // skip "infinite cylinder" - if (data->cylinder.radius == 0.f || - data->cylinder.aspect_ratio == INFINITY) { + if (data->cylinder.radius == 0.f || data->cylinder.aspect_ratio == INFINITY) { /* skipping the descriptor set update means the renderer must * entirely skip rendering of invisible layer */ l->visibility = XRT_LAYER_EYE_VISIBILITY_NONE; return; } - comp_layer_update_descriptors( - r->lr->layers[layer], image->sampler, - get_image_view(image, data->flags, data->cylinder.sub.array_index)); + comp_layer_update_descriptors(r->lr->layers[layer], image->sampler, + get_image_view(image, data->flags, data->cylinder.sub.array_index)); - float height = (data->cylinder.radius * data->cylinder.central_angle) / - data->cylinder.aspect_ratio; + float height = (data->cylinder.radius * data->cylinder.central_angle) / data->cylinder.aspect_ratio; // scale unit cylinder to diameter float diameter = data->cylinder.radius * 2; @@ -537,8 +510,7 @@ comp_renderer_set_cylinder_layer(struct comp_renderer *r, l->transformation[i].extent = data->cylinder.sub.rect.extent; } - comp_layer_update_cylinder_vertex_buffer(l, - data->cylinder.central_angle); + comp_layer_update_cylinder_vertex_buffer(l, data->cylinder.central_angle); } void @@ -556,17 +528,15 @@ comp_renderer_set_projection_layer(struct comp_renderer *r, l->transformation_ubo_binding = r->lr->transformation_ubo_binding; l->texture_binding = r->lr->texture_binding; - comp_layer_update_stereo_descriptors( - l, left_image->sampler, right_image->sampler, - get_image_view(left_image, data->flags, left_array_index), - get_image_view(right_image, data->flags, right_array_index)); + comp_layer_update_stereo_descriptors(l, left_image->sampler, right_image->sampler, + get_image_view(left_image, data->flags, left_array_index), + get_image_view(right_image, data->flags, right_array_index)); comp_layer_set_flip_y(l, data->flip_y); l->type = XRT_LAYER_STEREO_PROJECTION; l->flags = data->flags; - l->view_space = - (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; + l->view_space = (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; l->transformation[0].offset = data->stereo.l.sub.rect.offset; l->transformation[0].extent = data->stereo.l.sub.rect.extent; @@ -592,15 +562,12 @@ comp_renderer_set_equirect1_layer(struct comp_renderer *r, l->type = XRT_LAYER_EQUIRECT1; l->visibility = data->equirect1.visibility; l->flags = data->flags; - l->view_space = - (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; + l->view_space = (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; l->transformation_ubo_binding = r->lr->transformation_ubo_binding; l->texture_binding = r->lr->texture_binding; - comp_layer_update_descriptors( - l, image->repeat_sampler, - get_image_view(image, data->flags, - data->equirect1.sub.array_index)); + comp_layer_update_descriptors(l, image->repeat_sampler, + get_image_view(image, data->flags, data->equirect1.sub.array_index)); comp_layer_update_equirect1_descriptor(l, &data->equirect1); @@ -628,15 +595,12 @@ comp_renderer_set_equirect2_layer(struct comp_renderer *r, l->type = XRT_LAYER_EQUIRECT2; l->visibility = data->equirect2.visibility; l->flags = data->flags; - l->view_space = - (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; + l->view_space = (data->flags & XRT_LAYER_COMPOSITION_VIEW_SPACE_BIT) != 0; l->transformation_ubo_binding = r->lr->transformation_ubo_binding; l->texture_binding = r->lr->texture_binding; - comp_layer_update_descriptors( - l, image->repeat_sampler, - get_image_view(image, data->flags, - data->equirect2.sub.array_index)); + comp_layer_update_descriptors(l, image->repeat_sampler, + get_image_view(image, data->flags, data->equirect2.sub.array_index)); comp_layer_update_equirect2_descriptor(l, &data->equirect2); @@ -709,18 +673,14 @@ renderer_init_semaphores(struct comp_renderer *r) .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, }; - ret = vk->vkCreateSemaphore(vk->device, &info, NULL, - &r->semaphores.present_complete); + ret = vk->vkCreateSemaphore(vk->device, &info, NULL, &r->semaphores.present_complete); if (ret != VK_SUCCESS) { - COMP_ERROR(r->c, "vkCreateSemaphore: %s", - vk_result_string(ret)); + COMP_ERROR(r->c, "vkCreateSemaphore: %s", vk_result_string(ret)); } - ret = vk->vkCreateSemaphore(vk->device, &info, NULL, - &r->semaphores.render_complete); + ret = vk->vkCreateSemaphore(vk->device, &info, NULL, &r->semaphores.render_complete); if (ret != VK_SUCCESS) { - COMP_ERROR(r->c, "vkCreateSemaphore: %s", - vk_result_string(ret)); + COMP_ERROR(r->c, "vkCreateSemaphore: %s", vk_result_string(ret)); } } @@ -760,24 +720,19 @@ renderer_acquire_swapchain_image(struct comp_renderer *r) { VkResult ret; - ret = comp_target_acquire(r->c->target, r->semaphores.present_complete, - &r->current_buffer); + ret = comp_target_acquire(r->c->target, r->semaphores.present_complete, &r->current_buffer); if ((ret == VK_ERROR_OUT_OF_DATE_KHR) || (ret == VK_SUBOPTIMAL_KHR)) { COMP_DEBUG(r->c, "Received %s.", vk_result_string(ret)); renderer_resize(r); /* Acquire image again to silence validation error */ - ret = comp_target_acquire(r->c->target, - r->semaphores.present_complete, - &r->current_buffer); + ret = comp_target_acquire(r->c->target, r->semaphores.present_complete, &r->current_buffer); if (ret != VK_SUCCESS) { - COMP_ERROR(r->c, "vk_swapchain_acquire_next_image: %s", - vk_result_string(ret)); + COMP_ERROR(r->c, "vk_swapchain_acquire_next_image: %s", vk_result_string(ret)); } } else if (ret != VK_SUCCESS) { - COMP_ERROR(r->c, "vk_swapchain_acquire_next_image: %s", - vk_result_string(ret)); + COMP_ERROR(r->c, "vk_swapchain_acquire_next_image: %s", vk_result_string(ret)); } } @@ -786,15 +741,13 @@ renderer_present_swapchain_image(struct comp_renderer *r) { VkResult ret; - ret = comp_target_present(r->c->target, r->queue, r->current_buffer, - r->semaphores.render_complete); + ret = comp_target_present(r->c->target, r->queue, r->current_buffer, r->semaphores.render_complete); if (ret == VK_ERROR_OUT_OF_DATE_KHR) { renderer_resize(r); return; } if (ret != VK_SUCCESS) { - COMP_ERROR(r->c, "vk_swapchain_present: %s", - vk_result_string(ret)); + COMP_ERROR(r->c, "vk_swapchain_present: %s", vk_result_string(ret)); } } @@ -818,13 +771,11 @@ renderer_destroy(struct comp_renderer *r) // Semaphores if (r->semaphores.present_complete != VK_NULL_HANDLE) { - vk->vkDestroySemaphore(vk->device, - r->semaphores.present_complete, NULL); + vk->vkDestroySemaphore(vk->device, r->semaphores.present_complete, NULL); r->semaphores.present_complete = VK_NULL_HANDLE; } if (r->semaphores.render_complete != VK_NULL_HANDLE) { - vk->vkDestroySemaphore(vk->device, - r->semaphores.render_complete, NULL); + vk->vkDestroySemaphore(vk->device, r->semaphores.render_complete, NULL); r->semaphores.render_complete = VK_NULL_HANDLE; } diff --git a/src/xrt/compositor/main/comp_settings.h b/src/xrt/compositor/main/comp_settings.h index c1ab5fe0e..4fc28463a 100644 --- a/src/xrt/compositor/main/comp_settings.h +++ b/src/xrt/compositor/main/comp_settings.h @@ -28,10 +28,8 @@ extern "C" { * We may wish to allow user configuration to extend this list. */ XRT_MAYBE_UNUSED static const char *NV_DIRECT_WHITELIST[] = { - "Sony SIE HMD *08", - "HTC Corporation HTC-VIVE", - "HTC Corporation VIVE Pro", - "Oculus VR Inc. Rift", /* Matches DK1, DK2 and CV1 */ + "Sony SIE HMD *08", "HTC Corporation HTC-VIVE", + "HTC Corporation VIVE Pro", "Oculus VR Inc. Rift", /* Matches DK1, DK2 and CV1 */ "Valve Corporation Index HMD", }; diff --git a/src/xrt/compositor/main/comp_shaders.c b/src/xrt/compositor/main/comp_shaders.c index a71b9358b..e0bdc2f85 100644 --- a/src/xrt/compositor/main/comp_shaders.c +++ b/src/xrt/compositor/main/comp_shaders.c @@ -40,10 +40,7 @@ */ static VkResult -shader_load(struct vk_bundle *vk, - const uint32_t *code, - size_t size, - VkShaderModule *out_module) +shader_load(struct vk_bundle *vk, const uint32_t *code, size_t size, VkShaderModule *out_module) { VkResult ret; @@ -60,8 +57,7 @@ shader_load(struct vk_bundle *vk, NULL, // &module); // if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkCreateShaderModule failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkCreateShaderModule failed: %s", vk_result_string(ret)); return ret; } @@ -70,13 +66,13 @@ shader_load(struct vk_bundle *vk, return VK_SUCCESS; } -#define C(c) \ - do { \ - VkResult ret = c; \ - if (ret != VK_SUCCESS) { \ - comp_shaders_close(vk, s); \ - return false; \ - } \ +#define C(c) \ + do { \ + VkResult ret = c; \ + if (ret != VK_SUCCESS) { \ + comp_shaders_close(vk, s); \ + return false; \ + } \ } while (false) bool @@ -123,10 +119,10 @@ comp_shaders_load(struct vk_bundle *vk, struct comp_shaders *s) return true; } -#define D(shader) \ - if (s->shader != VK_NULL_HANDLE) { \ - vk->vkDestroyShaderModule(vk->device, s->shader, NULL); \ - s->shader = VK_NULL_HANDLE; \ +#define D(shader) \ + if (s->shader != VK_NULL_HANDLE) { \ + vk->vkDestroyShaderModule(vk->device, s->shader, NULL); \ + s->shader = VK_NULL_HANDLE; \ } void diff --git a/src/xrt/compositor/main/comp_swapchain.c b/src/xrt/compositor/main/comp_swapchain.c index f1042ff34..92eff57e0 100644 --- a/src/xrt/compositor/main/comp_swapchain.c +++ b/src/xrt/compositor/main/comp_swapchain.c @@ -51,9 +51,7 @@ swapchain_acquire_image(struct xrt_swapchain *xsc, uint32_t *out_index) } static xrt_result_t -swapchain_wait_image(struct xrt_swapchain *xsc, - uint64_t timeout, - uint32_t index) +swapchain_wait_image(struct xrt_swapchain *xsc, uint64_t timeout, uint32_t index) { struct comp_swapchain *sc = comp_swapchain(xsc); @@ -84,10 +82,10 @@ swapchain_release_image(struct xrt_swapchain *xsc, uint32_t index) * */ -#define D(TYPE, thing) \ - if (thing != VK_NULL_HANDLE) { \ - vk->vkDestroy##TYPE(vk->device, thing, NULL); \ - thing = VK_NULL_HANDLE; \ +#define D(TYPE, thing) \ + if (thing != VK_NULL_HANDLE) { \ + vk->vkDestroy##TYPE(vk->device, thing, NULL); \ + thing = VK_NULL_HANDLE; \ } static struct comp_swapchain * @@ -119,8 +117,7 @@ static bool is_depth_stencil_format(VkFormat format) { - return format == VK_FORMAT_D16_UNORM_S8_UINT || - format == VK_FORMAT_D24_UNORM_S8_UINT || + return format == VK_FORMAT_D16_UNORM_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT_S8_UINT; } @@ -153,8 +150,7 @@ do_post_create_vulkan_setup(struct comp_compositor *c, aspect |= VK_IMAGE_ASPECT_DEPTH_BIT; } if (is_depth_stencil_format(info->format)) { - aspect |= VK_IMAGE_ASPECT_DEPTH_BIT | - VK_IMAGE_ASPECT_STENCIL_BIT; + aspect |= VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; } if (is_stencil_only_format(info->format)) { aspect |= VK_IMAGE_ASPECT_STENCIL_BIT; @@ -172,17 +168,13 @@ do_post_create_vulkan_setup(struct comp_compositor *c, #endif for (uint32_t i = 0; i < num_images; i++) { - sc->images[i].views.alpha = - U_TYPED_ARRAY_CALLOC(VkImageView, info->array_size); - sc->images[i].views.no_alpha = - U_TYPED_ARRAY_CALLOC(VkImageView, info->array_size); + sc->images[i].views.alpha = U_TYPED_ARRAY_CALLOC(VkImageView, info->array_size); + sc->images[i].views.no_alpha = U_TYPED_ARRAY_CALLOC(VkImageView, info->array_size); sc->images[i].array_size = info->array_size; - vk_create_sampler(&c->vk, VK_SAMPLER_ADDRESS_MODE_REPEAT, - &sc->images[i].repeat_sampler); + vk_create_sampler(&c->vk, VK_SAMPLER_ADDRESS_MODE_REPEAT, &sc->images[i].repeat_sampler); - vk_create_sampler(&c->vk, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, - &sc->images[i].sampler); + vk_create_sampler(&c->vk, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, &sc->images[i].sampler); for (uint32_t layer = 0; layer < info->array_size; ++layer) { @@ -194,14 +186,10 @@ do_post_create_vulkan_setup(struct comp_compositor *c, .layerCount = 1, }; - vk_create_view(&c->vk, sc->vkic.images[i].handle, - (VkFormat)info->format, - subresource_range, + vk_create_view(&c->vk, sc->vkic.images[i].handle, (VkFormat)info->format, subresource_range, &sc->images[i].views.alpha[layer]); - vk_create_view_swizzle( - &c->vk, sc->vkic.images[i].handle, format, - subresource_range, components, - &sc->images[i].views.no_alpha[layer]); + vk_create_view_swizzle(&c->vk, sc->vkic.images[i].handle, format, subresource_range, components, + &sc->images[i].views.no_alpha[layer]); } } @@ -228,20 +216,16 @@ do_post_create_vulkan_setup(struct comp_compositor *c, }; for (uint32_t i = 0; i < num_images; i++) { - vk_set_image_layout( - &c->vk, cmd_buffer, sc->vkic.images[i].handle, 0, - VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - subresource_range); + vk_set_image_layout(&c->vk, cmd_buffer, sc->vkic.images[i].handle, 0, VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + subresource_range); } vk_submit_cmd_buffer(&c->vk, cmd_buffer); } static void -clean_image_views(struct vk_bundle *vk, - size_t array_size, - VkImageView **views_ptr) +clean_image_views(struct vk_bundle *vk, size_t array_size, VkImageView **views_ptr) { VkImageView *views = *views_ptr; if (views == NULL) { @@ -349,12 +333,10 @@ comp_swapchain_import(struct xrt_compositor *xc, struct comp_swapchain *sc = alloc_and_set_funcs(c, num_images); - COMP_DEBUG(c, "CREATE FROM NATIVE %p %dx%d", (void *)sc, info->width, - info->height); + COMP_DEBUG(c, "CREATE FROM NATIVE %p %dx%d", (void *)sc, info->width, info->height); // Use the image helper to get the images. - ret = vk_ic_from_natives(&c->vk, info, native_images, num_images, - &sc->vkic); + ret = vk_ic_from_natives(&c->vk, info, native_images, num_images, &sc->vkic); if (ret != VK_SUCCESS) { return XRT_ERROR_VULKAN; } diff --git a/src/xrt/compositor/main/comp_target.h b/src/xrt/compositor/main/comp_target.h index 088dafd6c..1c3b35f77 100644 --- a/src/xrt/compositor/main/comp_target.h +++ b/src/xrt/compositor/main/comp_target.h @@ -70,9 +70,7 @@ struct comp_target * Do any initialization that requires Vulkan to be loaded, you need to * call @ref create_images after calling this function. */ - bool (*init_post_vulkan)(struct comp_target *ct, - uint32_t preferred_width, - uint32_t preferred_height); + bool (*init_post_vulkan)(struct comp_target *ct, uint32_t preferred_width, uint32_t preferred_height); /*! * Create or recreate the image(s) of the target, for swapchain based @@ -88,17 +86,12 @@ struct comp_target /*! * Acquire the next image for rendering. */ - VkResult (*acquire)(struct comp_target *ct, - VkSemaphore semaphore, - uint32_t *out_index); + VkResult (*acquire)(struct comp_target *ct, VkSemaphore semaphore, uint32_t *out_index); /*! * Present the image at index to the screen. */ - VkResult (*present)(struct comp_target *ct, - VkQueue queue, - uint32_t index, - VkSemaphore semaphore); + VkResult (*present)(struct comp_target *ct, VkQueue queue, uint32_t index, VkSemaphore semaphore); /*! * Flush any WSI state before rendering. @@ -135,9 +128,7 @@ comp_target_init_pre_vulkan(struct comp_target *ct) * @ingroup comp_main */ static inline bool -comp_target_init_post_vulkan(struct comp_target *ct, - uint32_t preferred_width, - uint32_t preferred_height) +comp_target_init_post_vulkan(struct comp_target *ct, uint32_t preferred_width, uint32_t preferred_height) { return ct->init_post_vulkan(ct, preferred_width, preferred_height); } @@ -156,8 +147,7 @@ comp_target_create_images(struct comp_target *ct, VkColorSpaceKHR preferred_color_space, VkPresentModeKHR present_mode) { - ct->create_images(ct, preferred_width, preferred_height, - preferred_color_format, preferred_color_space, + ct->create_images(ct, preferred_width, preferred_height, preferred_color_format, preferred_color_space, present_mode); } @@ -168,9 +158,7 @@ comp_target_create_images(struct comp_target *ct, * @ingroup comp_main */ static inline VkResult -comp_target_acquire(struct comp_target *ct, - VkSemaphore semaphore, - uint32_t *out_index) +comp_target_acquire(struct comp_target *ct, VkSemaphore semaphore, uint32_t *out_index) { return ct->acquire(ct, semaphore, out_index); } @@ -182,10 +170,7 @@ comp_target_acquire(struct comp_target *ct, * @ingroup comp_main */ static inline VkResult -comp_target_present(struct comp_target *ct, - VkQueue queue, - uint32_t index, - VkSemaphore semaphore) +comp_target_present(struct comp_target *ct, VkQueue queue, uint32_t index, VkSemaphore semaphore) { return ct->present(ct, queue, index, semaphore); diff --git a/src/xrt/compositor/main/comp_target_swapchain.c b/src/xrt/compositor/main/comp_target_swapchain.c index bf64dba36..cd016fd4b 100644 --- a/src/xrt/compositor/main/comp_target_swapchain.c +++ b/src/xrt/compositor/main/comp_target_swapchain.c @@ -51,8 +51,7 @@ static void comp_target_swapchain_destroy_image_views(struct comp_target_swapchain *cts); static void -comp_target_swapchain_destroy_old(struct comp_target_swapchain *cts, - VkSwapchainKHR old); +comp_target_swapchain_destroy_old(struct comp_target_swapchain *cts, VkSwapchainKHR old); static VkExtent2D comp_target_swapchain_select_extent(struct comp_target_swapchain *cts, @@ -61,14 +60,10 @@ comp_target_swapchain_select_extent(struct comp_target_swapchain *cts, uint32_t height); static bool -_find_surface_format(struct comp_target_swapchain *cts, - VkSurfaceKHR surface, - VkSurfaceFormatKHR *format); +_find_surface_format(struct comp_target_swapchain *cts, VkSurfaceKHR surface, VkSurfaceFormatKHR *format); static bool -_check_surface_present_mode(struct comp_target_swapchain *cts, - VkSurfaceKHR surface, - VkPresentModeKHR present_mode); +_check_surface_present_mode(struct comp_target_swapchain *cts, VkSurfaceKHR surface, VkPresentModeKHR present_mode); /* @@ -109,8 +104,7 @@ comp_target_swapchain_create_images(struct comp_target *ct, // Sanity check. - ret = vk->vkGetPhysicalDeviceSurfaceSupportKHR( - vk->physical_device, 0, cts->surface.handle, &supported); + ret = vk->vkGetPhysicalDeviceSurfaceSupportKHR(vk->physical_device, 0, cts->surface.handle, &supported); if (!supported) { COMP_ERROR(ct->c, "vkGetPhysicalDeviceSurfaceSupportKHR: surface not " @@ -119,16 +113,14 @@ comp_target_swapchain_create_images(struct comp_target *ct, } // More sanity checks. - if (!_check_surface_present_mode(cts, cts->surface.handle, - cts->present_mode)) { + if (!_check_surface_present_mode(cts, cts->surface.handle, cts->present_mode)) { // Free old. comp_target_swapchain_destroy_old(cts, old_swapchain_handle); return; } // Find the correct format. - if (!_find_surface_format(cts, cts->surface.handle, - &cts->surface.format)) { + if (!_find_surface_format(cts, cts->surface.handle, &cts->surface.format)) { // Free old. comp_target_swapchain_destroy_old(cts, old_swapchain_handle); return; @@ -136,12 +128,9 @@ comp_target_swapchain_create_images(struct comp_target *ct, // Get the caps first. VkSurfaceCapabilitiesKHR surface_caps; - ret = vk->vkGetPhysicalDeviceSurfaceCapabilitiesKHR( - vk->physical_device, cts->surface.handle, &surface_caps); + ret = vk->vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vk->physical_device, cts->surface.handle, &surface_caps); if (ret != VK_SUCCESS) { - COMP_ERROR(ct->c, - "vkGetPhysicalDeviceSurfaceCapabilitiesKHR: %s", - vk_result_string(ret)); + COMP_ERROR(ct->c, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR: %s", vk_result_string(ret)); // Free old. comp_target_swapchain_destroy_old(cts, old_swapchain_handle); @@ -149,13 +138,10 @@ comp_target_swapchain_create_images(struct comp_target *ct, } // Get the extents of the swapchain. - VkExtent2D extent = comp_target_swapchain_select_extent( - cts, surface_caps, width, height); + VkExtent2D extent = comp_target_swapchain_select_extent(cts, surface_caps, width, height); - if (surface_caps.currentTransform & - VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR || - surface_caps.currentTransform & - VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR) { + if (surface_caps.currentTransform & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR || + surface_caps.currentTransform & VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR) { COMP_DEBUG(ct->c, "Swapping width and height," "since we are going to pre rotate"); @@ -188,15 +174,13 @@ comp_target_swapchain_create_images(struct comp_target *ct, .oldSwapchain = old_swapchain_handle, }; - ret = vk->vkCreateSwapchainKHR(vk->device, &swapchain_info, NULL, - &cts->swapchain.handle); + ret = vk->vkCreateSwapchainKHR(vk->device, &swapchain_info, NULL, &cts->swapchain.handle); // Always destroy the old. comp_target_swapchain_destroy_old(cts, old_swapchain_handle); if (ret != VK_SUCCESS) { - COMP_ERROR(ct->c, "vkCreateSwapchainKHR: %s", - vk_result_string(ret)); + COMP_ERROR(ct->c, "vkCreateSwapchainKHR: %s", vk_result_string(ret)); return; } @@ -229,21 +213,18 @@ comp_target_swapchain_select_extent(struct comp_target_swapchain *cts, return extent; } - if (caps.currentExtent.width != width || - caps.currentExtent.height != height) { + if (caps.currentExtent.width != width || caps.currentExtent.height != height) { COMP_DEBUG(cts->base.c, "Using swap chain extent dimensions %dx%d instead " "of requested %dx%d.", - caps.currentExtent.width, caps.currentExtent.height, - width, height); + caps.currentExtent.width, caps.currentExtent.height, width, height); } return caps.currentExtent; } static void -comp_target_swapchain_destroy_old(struct comp_target_swapchain *cts, - VkSwapchainKHR old) +comp_target_swapchain_destroy_old(struct comp_target_swapchain *cts, VkSwapchainKHR old) { struct vk_bundle *vk = get_vk(cts); @@ -253,9 +234,7 @@ comp_target_swapchain_destroy_old(struct comp_target_swapchain *cts, } VkResult -comp_target_swapchain_acquire_next_image(struct comp_target *ct, - VkSemaphore semaphore, - uint32_t *out_index) +comp_target_swapchain_acquire_next_image(struct comp_target *ct, VkSemaphore semaphore, uint32_t *out_index) { struct comp_target_swapchain *cts = (struct comp_target_swapchain *)ct; struct vk_bundle *vk = get_vk(cts); @@ -271,10 +250,7 @@ comp_target_swapchain_acquire_next_image(struct comp_target *ct, } VkResult -comp_target_swapchain_present(struct comp_target *ct, - VkQueue queue, - uint32_t index, - VkSemaphore semaphore) +comp_target_swapchain_present(struct comp_target *ct, VkQueue queue, uint32_t index, VkSemaphore semaphore) { struct comp_target_swapchain *cts = (struct comp_target_swapchain *)ct; struct vk_bundle *vk = get_vk(cts); @@ -292,32 +268,25 @@ comp_target_swapchain_present(struct comp_target *ct, } static bool -_find_surface_format(struct comp_target_swapchain *cts, - VkSurfaceKHR surface, - VkSurfaceFormatKHR *format) +_find_surface_format(struct comp_target_swapchain *cts, VkSurfaceKHR surface, VkSurfaceFormatKHR *format) { struct vk_bundle *vk = get_vk(cts); uint32_t num_formats; VkSurfaceFormatKHR *formats = NULL; VkResult ret; - ret = vk->vkGetPhysicalDeviceSurfaceFormatsKHR( - vk->physical_device, surface, &num_formats, NULL); + ret = vk->vkGetPhysicalDeviceSurfaceFormatsKHR(vk->physical_device, surface, &num_formats, NULL); if (num_formats != 0) { formats = U_TYPED_ARRAY_CALLOC(VkSurfaceFormatKHR, num_formats); - vk->vkGetPhysicalDeviceSurfaceFormatsKHR( - vk->physical_device, surface, &num_formats, formats); + vk->vkGetPhysicalDeviceSurfaceFormatsKHR(vk->physical_device, surface, &num_formats, formats); } else { - COMP_ERROR(cts->base.c, - "Could not enumerate surface formats. '%s'", - vk_result_string(ret)); + COMP_ERROR(cts->base.c, "Could not enumerate surface formats. '%s'", vk_result_string(ret)); return false; } VkSurfaceFormatKHR *formats_for_colorspace = NULL; - formats_for_colorspace = - U_TYPED_ARRAY_CALLOC(VkSurfaceFormatKHR, num_formats); + formats_for_colorspace = U_TYPED_ARRAY_CALLOC(VkSurfaceFormatKHR, num_formats); uint32_t num_formats_cs = 0; uint32_t num_pref_formats = ARRAY_SIZE(preferred_color_formats); @@ -337,8 +306,7 @@ _find_surface_format(struct comp_target_swapchain *cts, // if we have one that is on our preferred formats list, use it for (uint32_t i = 0; i < num_formats_cs; i++) { - if (formats_for_colorspace[i].format == - cts->preferred.color_format) { + if (formats_for_colorspace[i].format == cts->preferred.color_format) { // perfect match. *format = formats_for_colorspace[i]; goto cleanup; @@ -350,8 +318,7 @@ _find_surface_format(struct comp_target_swapchain *cts, // correct colorspace. for (uint32_t i = 0; i < num_formats_cs; i++) { for (uint32_t j = 0; j < num_pref_formats; j++) { - if (formats_for_colorspace[i].format == - preferred_color_formats[j]) { + if (formats_for_colorspace[i].format == preferred_color_formats[j]) { *format = formats_for_colorspace[i]; goto cleanup; } @@ -372,13 +339,11 @@ _find_surface_format(struct comp_target_swapchain *cts, // return a preferred format at least for (uint32_t i = 0; i < num_formats; i++) { for (uint32_t j = 0; j < num_pref_formats; j++) { - if (formats[i].format == - preferred_color_formats[j]) { + if (formats[i].format == preferred_color_formats[j]) { *format = formats_for_colorspace[i]; - COMP_ERROR( - cts->base.c, - "Returning known-wrong color " - "space! Color shift may occur."); + COMP_ERROR(cts->base.c, + "Returning known-wrong color " + "space! Color shift may occur."); goto cleanup; } } @@ -408,28 +373,21 @@ error: } static bool -_check_surface_present_mode(struct comp_target_swapchain *cts, - VkSurfaceKHR surface, - VkPresentModeKHR present_mode) +_check_surface_present_mode(struct comp_target_swapchain *cts, VkSurfaceKHR surface, VkPresentModeKHR present_mode) { struct vk_bundle *vk = get_vk(cts); VkResult ret; uint32_t num_present_modes; VkPresentModeKHR *present_modes; - ret = vk->vkGetPhysicalDeviceSurfacePresentModesKHR( - vk->physical_device, surface, &num_present_modes, NULL); + ret = vk->vkGetPhysicalDeviceSurfacePresentModesKHR(vk->physical_device, surface, &num_present_modes, NULL); if (num_present_modes != 0) { - present_modes = - U_TYPED_ARRAY_CALLOC(VkPresentModeKHR, num_present_modes); - vk->vkGetPhysicalDeviceSurfacePresentModesKHR( - vk->physical_device, surface, &num_present_modes, - present_modes); + present_modes = U_TYPED_ARRAY_CALLOC(VkPresentModeKHR, num_present_modes); + vk->vkGetPhysicalDeviceSurfacePresentModesKHR(vk->physical_device, surface, &num_present_modes, + present_modes); } else { - COMP_ERROR(cts->base.c, - "Could not enumerate present modes. '%s'", - vk_result_string(ret)); + COMP_ERROR(cts->base.c, "Could not enumerate present modes. '%s'", vk_result_string(ret)); return false; } @@ -459,8 +417,7 @@ comp_target_swapchain_destroy_image_views(struct comp_target_swapchain *cts) continue; } - vk->vkDestroyImageView(vk->device, cts->base.images[i].view, - NULL); + vk->vkDestroyImageView(vk->device, cts->base.images[i].view, NULL); cts->base.images[i].view = VK_NULL_HANDLE; } @@ -479,8 +436,7 @@ comp_target_swapchain_create_image_views(struct comp_target_swapchain *cts) &cts->base.num_images, // pSwapchainImageCount NULL); // pSwapchainImages assert(cts->base.num_images > 0); - COMP_DEBUG(cts->base.c, "Creating %d image views.", - cts->base.num_images); + COMP_DEBUG(cts->base.c, "Creating %d image views.", cts->base.num_images); VkImage *images = U_TYPED_ARRAY_CALLOC(VkImage, cts->base.num_images); vk->vkGetSwapchainImagesKHR( // @@ -491,8 +447,7 @@ comp_target_swapchain_create_image_views(struct comp_target_swapchain *cts) comp_target_swapchain_destroy_image_views(cts); - cts->base.images = U_TYPED_ARRAY_CALLOC(struct comp_target_image, - cts->base.num_images); + cts->base.images = U_TYPED_ARRAY_CALLOC(struct comp_target_image, cts->base.num_images); VkImageSubresourceRange subresource_range = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, @@ -504,8 +459,7 @@ comp_target_swapchain_create_image_views(struct comp_target_swapchain *cts) for (uint32_t i = 0; i < cts->base.num_images; i++) { cts->base.images[i].handle = images[i]; - vk_create_view(vk, cts->base.images[i].handle, - cts->surface.format.format, subresource_range, + vk_create_view(vk, cts->base.images[i].handle, cts->surface.format.format, subresource_range, &cts->base.images[i].view); } diff --git a/src/xrt/compositor/main/comp_window_android.c b/src/xrt/compositor/main/comp_window_android.c index 55600378f..187a01a54 100644 --- a/src/xrt/compositor/main/comp_window_android.c +++ b/src/xrt/compositor/main/comp_window_android.c @@ -79,8 +79,7 @@ comp_window_android_destroy(struct comp_target *ct) } static void -comp_window_android_update_window_title(struct comp_target *ct, - const char *title) +comp_window_android_update_window_title(struct comp_target *ct, const char *title) { (void)ct; } @@ -88,18 +87,16 @@ comp_window_android_update_window_title(struct comp_target *ct, static struct ANativeWindow * _create_android_window(struct comp_window_android *cwa) { - cwa->custom_surface = android_custom_surface_async_start( - android_globals_get_vm(), android_globals_get_activity()); + cwa->custom_surface = + android_custom_surface_async_start(android_globals_get_vm(), android_globals_get_activity()); if (cwa->custom_surface == NULL) { - COMP_ERROR( - cwa->base.base.c, - "comp_window_android_create_surface: could not " - "start asynchronous attachment of our custom surface"); + COMP_ERROR(cwa->base.base.c, + "comp_window_android_create_surface: could not " + "start asynchronous attachment of our custom surface"); return NULL; } - return android_custom_surface_wait_get_surface(cwa->custom_surface, - 2000); + return android_custom_surface_wait_get_surface(cwa->custom_surface, 2000); } static VkResult @@ -122,8 +119,7 @@ comp_window_android_create_surface(struct comp_window_android *cwa, NULL, // vk_surface); // if (ret != VK_SUCCESS) { - COMP_ERROR(cwa->base.base.c, "vkCreateAndroidSurfaceKHR: %s", - vk_result_string(ret)); + COMP_ERROR(cwa->base.base.c, "vkCreateAndroidSurfaceKHR: %s", vk_result_string(ret)); return ret; } @@ -131,9 +127,7 @@ comp_window_android_create_surface(struct comp_window_android *cwa, } static bool -comp_window_android_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height) +comp_window_android_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height) { struct comp_window_android *cwa = (struct comp_window_android *)ct; VkResult ret; @@ -153,11 +147,9 @@ comp_window_android_init_swapchain(struct comp_target *ct, return false; } - ret = comp_window_android_create_surface(cwa, window, - &cwa->base.surface.handle); + ret = comp_window_android_create_surface(cwa, window, &cwa->base.surface.handle); if (ret != VK_SUCCESS) { - COMP_ERROR(ct->c, "Failed to create surface '%s'!", - vk_result_string(ret)); + COMP_ERROR(ct->c, "Failed to create surface '%s'!", vk_result_string(ret)); return false; } @@ -173,8 +165,7 @@ comp_window_android_flush(struct comp_target *ct) struct comp_target * comp_window_android_create(struct comp_compositor *c) { - struct comp_window_android *w = - U_TYPED_CALLOC(struct comp_window_android); + struct comp_window_android *w = U_TYPED_CALLOC(struct comp_window_android); comp_target_swapchain_init_set_fnptrs(&w->base); diff --git a/src/xrt/compositor/main/comp_window_direct.c b/src/xrt/compositor/main/comp_window_direct.c index 96ab3cff7..8b5cec0c8 100644 --- a/src/xrt/compositor/main/comp_window_direct.c +++ b/src/xrt/compositor/main/comp_window_direct.c @@ -22,9 +22,7 @@ get_vk(struct comp_target_swapchain *cts) } static int -choose_best_vk_mode_auto(struct comp_target *ct, - VkDisplayModePropertiesKHR *mode_properties, - int mode_count) +choose_best_vk_mode_auto(struct comp_target *ct, VkDisplayModePropertiesKHR *mode_properties, int mode_count) { if (mode_count == 1) return 0; @@ -34,40 +32,29 @@ choose_best_vk_mode_auto(struct comp_target *ct, // First priority: choose mode that maximizes rendered pixels. // Second priority: choose mode with highest refresh rate. for (int i = 1; i < mode_count; i++) { - VkDisplayModeParametersKHR current = - mode_properties[i].parameters; - COMP_DEBUG(ct->c, "Available Vk direct mode %d: %dx%d@%.2f", i, - current.visibleRegion.width, - current.visibleRegion.height, - (float)current.refreshRate / 1000.); + VkDisplayModeParametersKHR current = mode_properties[i].parameters; + COMP_DEBUG(ct->c, "Available Vk direct mode %d: %dx%d@%.2f", i, current.visibleRegion.width, + current.visibleRegion.height, (float)current.refreshRate / 1000.); - VkDisplayModeParametersKHR best = - mode_properties[best_index].parameters; + VkDisplayModeParametersKHR best = mode_properties[best_index].parameters; - int best_pixels = - best.visibleRegion.width * best.visibleRegion.height; - int pixels = - current.visibleRegion.width * current.visibleRegion.height; + int best_pixels = best.visibleRegion.width * best.visibleRegion.height; + int pixels = current.visibleRegion.width * current.visibleRegion.height; if (pixels > best_pixels) { best_index = i; - } else if (pixels == best_pixels && - current.refreshRate > best.refreshRate) { + } else if (pixels == best_pixels && current.refreshRate > best.refreshRate) { best_index = i; } } - VkDisplayModeParametersKHR best = - mode_properties[best_index].parameters; - COMP_DEBUG(ct->c, "Auto choosing Vk direct mode %d: %dx%d@%.2f", - best_index, best.visibleRegion.width, + VkDisplayModeParametersKHR best = mode_properties[best_index].parameters; + COMP_DEBUG(ct->c, "Auto choosing Vk direct mode %d: %dx%d@%.2f", best_index, best.visibleRegion.width, best.visibleRegion.width, (float)best.refreshRate / 1000.); return best_index; } static void -print_modes(struct comp_target *ct, - VkDisplayModePropertiesKHR *mode_properties, - int mode_count) +print_modes(struct comp_target *ct, VkDisplayModePropertiesKHR *mode_properties, int mode_count) { COMP_PRINT_MODE(ct->c, "Available Vk modes for direct mode"); for (int i = 0; i < mode_count; i++) { @@ -76,38 +63,31 @@ print_modes(struct comp_target *ct, uint16_t height = props.parameters.visibleRegion.height; float refresh = (float)props.parameters.refreshRate / 1000.; - COMP_PRINT_MODE(ct->c, "| %2d | %dx%d@%.2f", i, width, height, - refresh); + COMP_PRINT_MODE(ct->c, "| %2d | %dx%d@%.2f", i, width, height, refresh); } COMP_PRINT_MODE(ct->c, "Listed %d modes", mode_count); } VkDisplayModeKHR -comp_window_direct_get_primary_display_mode(struct comp_target_swapchain *cts, - VkDisplayKHR display) +comp_window_direct_get_primary_display_mode(struct comp_target_swapchain *cts, VkDisplayKHR display) { struct vk_bundle *vk = get_vk(cts); struct comp_target *ct = &cts->base; uint32_t mode_count; VkResult ret; - ret = vk->vkGetDisplayModePropertiesKHR(vk->physical_device, display, - &mode_count, NULL); + ret = vk->vkGetDisplayModePropertiesKHR(vk->physical_device, display, &mode_count, NULL); if (ret != VK_SUCCESS) { - COMP_ERROR(ct->c, "vkGetDisplayModePropertiesKHR: %s", - vk_result_string(ret)); + COMP_ERROR(ct->c, "vkGetDisplayModePropertiesKHR: %s", vk_result_string(ret)); return VK_NULL_HANDLE; } COMP_DEBUG(ct->c, "Found %d modes", mode_count); - VkDisplayModePropertiesKHR *mode_properties = - U_TYPED_ARRAY_CALLOC(VkDisplayModePropertiesKHR, mode_count); - ret = vk->vkGetDisplayModePropertiesKHR(vk->physical_device, display, - &mode_count, mode_properties); + VkDisplayModePropertiesKHR *mode_properties = U_TYPED_ARRAY_CALLOC(VkDisplayModePropertiesKHR, mode_count); + ret = vk->vkGetDisplayModePropertiesKHR(vk->physical_device, display, &mode_count, mode_properties); if (ret != VK_SUCCESS) { - COMP_ERROR(ct->c, "vkGetDisplayModePropertiesKHR: %s", - vk_result_string(ret)); + COMP_ERROR(ct->c, "vkGetDisplayModePropertiesKHR: %s", vk_result_string(ret)); free(mode_properties); return VK_NULL_HANDLE; } @@ -123,35 +103,27 @@ comp_window_direct_get_primary_display_mode(struct comp_target_swapchain *cts, "Requested mode index %d, but max is %d. Falling " "back to automatic mode selection", desired_mode, mode_count); - chosen_mode = - choose_best_vk_mode_auto(ct, mode_properties, mode_count); + chosen_mode = choose_best_vk_mode_auto(ct, mode_properties, mode_count); } else if (desired_mode < 0) { - chosen_mode = - choose_best_vk_mode_auto(ct, mode_properties, mode_count); + chosen_mode = choose_best_vk_mode_auto(ct, mode_properties, mode_count); } else { - COMP_DEBUG(ct->c, "Using manually chosen mode %d", - desired_mode); + COMP_DEBUG(ct->c, "Using manually chosen mode %d", desired_mode); chosen_mode = desired_mode; } VkDisplayModePropertiesKHR props = mode_properties[chosen_mode]; - COMP_DEBUG(ct->c, "found display mode %dx%d@%.2f", - props.parameters.visibleRegion.width, - props.parameters.visibleRegion.height, - (float)props.parameters.refreshRate / 1000.); + COMP_DEBUG(ct->c, "found display mode %dx%d@%.2f", props.parameters.visibleRegion.width, + props.parameters.visibleRegion.height, (float)props.parameters.refreshRate / 1000.); - int64_t new_frame_interval = - 1000. * 1000. * 1000. * 1000. / props.parameters.refreshRate; + int64_t new_frame_interval = 1000. * 1000. * 1000. * 1000. / props.parameters.refreshRate; - COMP_DEBUG( - ct->c, - "Updating compositor settings nominal frame interval from %" PRIu64 - " (%f Hz) to %" PRIu64 " (%f Hz)", - ct->c->settings.nominal_frame_interval_ns, - 1000. * 1000. * 1000. / - (float)ct->c->settings.nominal_frame_interval_ns, - new_frame_interval, (float)props.parameters.refreshRate / 1000.); + COMP_DEBUG(ct->c, + "Updating compositor settings nominal frame interval from %" PRIu64 " (%f Hz) to %" PRIu64 + " (%f Hz)", + ct->c->settings.nominal_frame_interval_ns, + 1000. * 1000. * 1000. / (float)ct->c->settings.nominal_frame_interval_ns, new_frame_interval, + (float)props.parameters.refreshRate / 1000.); ct->c->settings.nominal_frame_interval_ns = new_frame_interval; @@ -182,39 +154,32 @@ comp_window_direct_create_surface(struct comp_target_swapchain *cts, // Get plane properties uint32_t plane_property_count; - VkResult ret = vk->vkGetPhysicalDeviceDisplayPlanePropertiesKHR( - vk->physical_device, &plane_property_count, NULL); + VkResult ret = + vk->vkGetPhysicalDeviceDisplayPlanePropertiesKHR(vk->physical_device, &plane_property_count, NULL); if (ret != VK_SUCCESS) { - COMP_ERROR(cts->base.c, - "vkGetPhysicalDeviceDisplayPlanePropertiesKHR: %s", - vk_result_string(ret)); + COMP_ERROR(cts->base.c, "vkGetPhysicalDeviceDisplayPlanePropertiesKHR: %s", vk_result_string(ret)); return ret; } - COMP_DEBUG(cts->base.c, "Found %d plane properites.", - plane_property_count); + COMP_DEBUG(cts->base.c, "Found %d plane properites.", plane_property_count); - VkDisplayPlanePropertiesKHR *plane_properties = U_TYPED_ARRAY_CALLOC( - VkDisplayPlanePropertiesKHR, plane_property_count); + VkDisplayPlanePropertiesKHR *plane_properties = + U_TYPED_ARRAY_CALLOC(VkDisplayPlanePropertiesKHR, plane_property_count); - ret = vk->vkGetPhysicalDeviceDisplayPlanePropertiesKHR( - vk->physical_device, &plane_property_count, plane_properties); + ret = vk->vkGetPhysicalDeviceDisplayPlanePropertiesKHR(vk->physical_device, &plane_property_count, + plane_properties); if (ret != VK_SUCCESS) { - COMP_ERROR(cts->base.c, - "vkGetPhysicalDeviceDisplayPlanePropertiesKHR: %s", - vk_result_string(ret)); + COMP_ERROR(cts->base.c, "vkGetPhysicalDeviceDisplayPlanePropertiesKHR: %s", vk_result_string(ret)); free(plane_properties); return ret; } uint32_t plane_index = 0; - VkDisplayModeKHR display_mode = - comp_window_direct_get_primary_display_mode(cts, display); + VkDisplayModeKHR display_mode = comp_window_direct_get_primary_display_mode(cts, display); VkDisplayPlaneCapabilitiesKHR plane_caps; - vk->vkGetDisplayPlaneCapabilitiesKHR(vk->physical_device, display_mode, - plane_index, &plane_caps); + vk->vkGetDisplayPlaneCapabilitiesKHR(vk->physical_device, display_mode, plane_index, &plane_caps); VkDisplaySurfaceCreateInfoKHR surface_info = { .sType = VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR, @@ -233,8 +198,7 @@ comp_window_direct_create_surface(struct comp_target_swapchain *cts, }, }; - VkResult result = vk->vkCreateDisplayPlaneSurfaceKHR( - vk->instance, &surface_info, NULL, &cts->surface.handle); + VkResult result = vk->vkCreateDisplayPlaneSurfaceKHR(vk->instance, &surface_info, NULL, &cts->surface.handle); free(plane_properties); @@ -253,18 +217,15 @@ comp_window_direct_connect(struct comp_target_swapchain *cts, Display **dpy) } VkResult -comp_window_direct_acquire_xlib_display(struct comp_target_swapchain *cts, - Display *dpy, - VkDisplayKHR display) +comp_window_direct_acquire_xlib_display(struct comp_target_swapchain *cts, Display *dpy, VkDisplayKHR display) { struct vk_bundle *vk = get_vk(cts); VkResult ret; ret = vk->vkAcquireXlibDisplayEXT(vk->physical_device, dpy, display); if (ret != VK_SUCCESS) { - COMP_ERROR(cts->base.c, - "vkAcquireXlibDisplayEXT: %s (0x%016" PRIx64 ")", - vk_result_string(ret), (uint64_t)display); + COMP_ERROR(cts->base.c, "vkAcquireXlibDisplayEXT: %s (0x%016" PRIx64 ")", vk_result_string(ret), + (uint64_t)display); if (cts->base.c->settings.window_type == WINDOW_DIRECT_NVIDIA && ret == VK_ERROR_INITIALIZATION_FAILED) { COMP_ERROR(cts->base.c, @@ -279,11 +240,8 @@ comp_window_direct_acquire_xlib_display(struct comp_target_swapchain *cts, } bool -comp_window_direct_init_swapchain(struct comp_target_swapchain *cts, - Display *dpy, - VkDisplayKHR display, - uint32_t width, - uint32_t height) +comp_window_direct_init_swapchain( + struct comp_target_swapchain *cts, Display *dpy, VkDisplayKHR display, uint32_t width, uint32_t height) { VkResult ret; ret = comp_window_direct_acquire_xlib_display(cts, dpy, display); @@ -294,8 +252,7 @@ comp_window_direct_init_swapchain(struct comp_target_swapchain *cts, ret = comp_window_direct_create_surface(cts, display, width, height); if (ret != VK_SUCCESS) { - COMP_ERROR(cts->base.c, "Failed to create surface! '%s'", - vk_result_string(ret)); + COMP_ERROR(cts->base.c, "Failed to create surface! '%s'", vk_result_string(ret)); return false; } diff --git a/src/xrt/compositor/main/comp_window_direct.h b/src/xrt/compositor/main/comp_window_direct.h index 37cda2e11..2608e0229 100644 --- a/src/xrt/compositor/main/comp_window_direct.h +++ b/src/xrt/compositor/main/comp_window_direct.h @@ -17,8 +17,7 @@ extern "C" { #endif VkDisplayModeKHR -comp_window_direct_get_primary_display_mode(struct comp_target_swapchain *cts, - VkDisplayKHR display); +comp_window_direct_get_primary_display_mode(struct comp_target_swapchain *cts, VkDisplayKHR display); VkResult comp_window_direct_create_surface(struct comp_target_swapchain *cts, @@ -30,16 +29,11 @@ int comp_window_direct_connect(struct comp_target_swapchain *cts, Display **dpy); VkResult -comp_window_direct_acquire_xlib_display(struct comp_target_swapchain *cts, - Display *dpy, - VkDisplayKHR display); +comp_window_direct_acquire_xlib_display(struct comp_target_swapchain *cts, Display *dpy, VkDisplayKHR display); bool -comp_window_direct_init_swapchain(struct comp_target_swapchain *cts, - Display *dpy, - VkDisplayKHR display, - uint32_t width, - uint32_t height); +comp_window_direct_init_swapchain( + struct comp_target_swapchain *cts, Display *dpy, VkDisplayKHR display, uint32_t width, uint32_t height); #ifdef __cplusplus } diff --git a/src/xrt/compositor/main/comp_window_direct_nvidia.c b/src/xrt/compositor/main/comp_window_direct_nvidia.c index 4909569a5..fa1f0aeb0 100644 --- a/src/xrt/compositor/main/comp_window_direct_nvidia.c +++ b/src/xrt/compositor/main/comp_window_direct_nvidia.c @@ -59,9 +59,7 @@ static struct comp_window_direct_nvidia_display * comp_window_direct_nvidia_current_display(struct comp_window_direct_nvidia *w); static bool -comp_window_direct_nvidia_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height); +comp_window_direct_nvidia_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height); /* @@ -86,8 +84,7 @@ _update_window_title(struct comp_target *ct, const char *title) struct comp_target * comp_window_direct_nvidia_create(struct comp_compositor *c) { - struct comp_window_direct_nvidia *w = - U_TYPED_CALLOC(struct comp_window_direct_nvidia); + struct comp_window_direct_nvidia *w = U_TYPED_CALLOC(struct comp_window_direct_nvidia); comp_target_swapchain_init_set_fnptrs(&w->base); @@ -95,8 +92,7 @@ comp_window_direct_nvidia_create(struct comp_compositor *c) w->base.base.destroy = comp_window_direct_nvidia_destroy; w->base.base.flush = _flush; w->base.base.init_pre_vulkan = comp_window_direct_nvidia_init; - w->base.base.init_post_vulkan = - comp_window_direct_nvidia_init_swapchain; + w->base.base.init_post_vulkan = comp_window_direct_nvidia_init_swapchain; w->base.base.set_title = _update_window_title; w->base.base.c = c; @@ -106,14 +102,12 @@ comp_window_direct_nvidia_create(struct comp_compositor *c) static void comp_window_direct_nvidia_destroy(struct comp_target *ct) { - struct comp_window_direct_nvidia *w_direct = - (struct comp_window_direct_nvidia *)ct; + struct comp_window_direct_nvidia *w_direct = (struct comp_window_direct_nvidia *)ct; comp_target_swapchain_cleanup(&w_direct->base); for (uint32_t i = 0; i < w_direct->num_displays; i++) { - struct comp_window_direct_nvidia_display *d = - &w_direct->displays[i]; + struct comp_window_direct_nvidia_display *d = &w_direct->displays[i]; d->display = VK_NULL_HANDLE; free(d->name); } @@ -143,27 +137,21 @@ append_nvidia_entry_on_match(struct comp_window_direct_nvidia *w, return false; // we have a match with this whitelist entry. - w->base.base.c->settings.preferred.width = - disp->physicalResolution.width; - w->base.base.c->settings.preferred.height = - disp->physicalResolution.height; - struct comp_window_direct_nvidia_display d = { - .name = U_TYPED_ARRAY_CALLOC(char, disp_entry_length + 1), - .display_properties = *disp, - .display = disp->display}; + w->base.base.c->settings.preferred.width = disp->physicalResolution.width; + w->base.base.c->settings.preferred.height = disp->physicalResolution.height; + struct comp_window_direct_nvidia_display d = {.name = U_TYPED_ARRAY_CALLOC(char, disp_entry_length + 1), + .display_properties = *disp, + .display = disp->display}; memcpy(d.name, disp->displayName, disp_entry_length); d.name[disp_entry_length] = '\0'; w->num_displays += 1; - U_ARRAY_REALLOC_OR_FREE(w->displays, - struct comp_window_direct_nvidia_display, - w->num_displays); + U_ARRAY_REALLOC_OR_FREE(w->displays, struct comp_window_direct_nvidia_display, w->num_displays); if (w->displays == NULL) - COMP_ERROR(w->base.base.c, - "Unable to reallocate randr_displays"); + COMP_ERROR(w->base.base.c, "Unable to reallocate randr_displays"); w->displays[w->num_displays - 1] = d; @@ -173,8 +161,7 @@ append_nvidia_entry_on_match(struct comp_window_direct_nvidia *w, static bool comp_window_direct_nvidia_init(struct comp_target *ct) { - struct comp_window_direct_nvidia *w_direct = - (struct comp_window_direct_nvidia *)ct; + struct comp_window_direct_nvidia *w_direct = (struct comp_window_direct_nvidia *)ct; // Sanity check. if (ct->c->vk.instance == VK_NULL_HANDLE) { @@ -192,8 +179,8 @@ comp_window_direct_nvidia_init(struct comp_target *ct) // find our display using nvidia whitelist, enumerate its modes, and // pick the best one get a list of attached displays uint32_t display_count; - if (comp_vk.vkGetPhysicalDeviceDisplayPropertiesKHR( - comp_vk.physical_device, &display_count, NULL) != VK_SUCCESS) { + if (comp_vk.vkGetPhysicalDeviceDisplayPropertiesKHR(comp_vk.physical_device, &display_count, NULL) != + VK_SUCCESS) { COMP_ERROR(ct->c, "Failed to get vulkan display count"); return false; } @@ -203,12 +190,10 @@ comp_window_direct_nvidia_init(struct comp_target *ct) return false; } - struct VkDisplayPropertiesKHR *display_props = - U_TYPED_ARRAY_CALLOC(VkDisplayPropertiesKHR, display_count); + struct VkDisplayPropertiesKHR *display_props = U_TYPED_ARRAY_CALLOC(VkDisplayPropertiesKHR, display_count); - if (display_props && comp_vk.vkGetPhysicalDeviceDisplayPropertiesKHR( - comp_vk.physical_device, &display_count, - display_props) != VK_SUCCESS) { + if (display_props && comp_vk.vkGetPhysicalDeviceDisplayPropertiesKHR(comp_vk.physical_device, &display_count, + display_props) != VK_SUCCESS) { COMP_ERROR(ct->c, "Failed to get display properties"); free(display_props); return false; @@ -219,14 +204,12 @@ comp_window_direct_nvidia_init(struct comp_target *ct) struct VkDisplayPropertiesKHR disp = *(display_props + i); if (ct->c->settings.nvidia_display) { - append_nvidia_entry_on_match( - w_direct, ct->c->settings.nvidia_display, &disp); + append_nvidia_entry_on_match(w_direct, ct->c->settings.nvidia_display, &disp); } // check this display against our whitelist for (uint32_t j = 0; j < ARRAY_SIZE(NV_DIRECT_WHITELIST); j++) - if (append_nvidia_entry_on_match( - w_direct, NV_DIRECT_WHITELIST[j], &disp)) + if (append_nvidia_entry_on_match(w_direct, NV_DIRECT_WHITELIST[j], &disp)) break; } @@ -249,15 +232,11 @@ comp_window_direct_nvidia_current_display(struct comp_window_direct_nvidia *w) } static bool -comp_window_direct_nvidia_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height) +comp_window_direct_nvidia_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height) { - struct comp_window_direct_nvidia *w_direct = - (struct comp_window_direct_nvidia *)ct; + struct comp_window_direct_nvidia *w_direct = (struct comp_window_direct_nvidia *)ct; - struct comp_window_direct_nvidia_display *d = - comp_window_direct_nvidia_current_display(w_direct); + struct comp_window_direct_nvidia_display *d = comp_window_direct_nvidia_current_display(w_direct); if (!d) { COMP_ERROR(ct->c, "NVIDIA could not find any HMDs."); return false; @@ -265,6 +244,5 @@ comp_window_direct_nvidia_init_swapchain(struct comp_target *ct, COMP_DEBUG(ct->c, "Will use display: %s", d->name); - return comp_window_direct_init_swapchain(&w_direct->base, w_direct->dpy, - d->display, width, height); + return comp_window_direct_init_swapchain(&w_direct->base, w_direct->dpy, d->display, width, height); } diff --git a/src/xrt/compositor/main/comp_window_direct_randr.c b/src/xrt/compositor/main/comp_window_direct_randr.c index b2637b089..ed5dd7287 100644 --- a/src/xrt/compositor/main/comp_window_direct_randr.c +++ b/src/xrt/compositor/main/comp_window_direct_randr.c @@ -75,13 +75,10 @@ static struct comp_window_direct_randr_display * comp_window_direct_randr_current_display(struct comp_window_direct_randr *w); static bool -comp_window_direct_randr_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height); +comp_window_direct_randr_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height); static VkDisplayKHR -comp_window_direct_randr_get_output(struct comp_window_direct_randr *w, - RROutput output); +comp_window_direct_randr_get_output(struct comp_window_direct_randr *w, RROutput output); static void comp_window_direct_randr_get_outputs(struct comp_window_direct_randr *w); @@ -114,8 +111,7 @@ _update_window_title(struct comp_target *ct, const char *title) struct comp_target * comp_window_direct_randr_create(struct comp_compositor *c) { - struct comp_window_direct_randr *w = - U_TYPED_CALLOC(struct comp_window_direct_randr); + struct comp_window_direct_randr *w = U_TYPED_CALLOC(struct comp_window_direct_randr); comp_target_swapchain_init_set_fnptrs(&w->base); @@ -133,16 +129,14 @@ comp_window_direct_randr_create(struct comp_compositor *c) static void comp_window_direct_randr_destroy(struct comp_target *ct) { - struct comp_window_direct_randr *w_direct = - (struct comp_window_direct_randr *)ct; + struct comp_window_direct_randr *w_direct = (struct comp_window_direct_randr *)ct; comp_target_swapchain_cleanup(&w_direct->base); struct vk_bundle *vk = get_vk(w_direct); for (uint32_t i = 0; i < w_direct->num_displays; i++) { - struct comp_window_direct_randr_display *d = - &w_direct->displays[i]; + struct comp_window_direct_randr_display *d = &w_direct->displays[i]; if (d->display == VK_NULL_HANDLE) { continue; @@ -168,21 +162,17 @@ static void comp_window_direct_randr_list_screens(struct comp_window_direct_randr *w) { for (int i = 0; i < w->num_displays; i++) { - const struct comp_window_direct_randr_display *d = - &w->displays[i]; - COMP_DEBUG( - w->base.base.c, "%d: %s %dx%d@%.2f", i, d->name, - d->primary_mode.width, d->primary_mode.height, - (double)d->primary_mode.dot_clock / - (d->primary_mode.htotal * d->primary_mode.vtotal)); + const struct comp_window_direct_randr_display *d = &w->displays[i]; + COMP_DEBUG(w->base.base.c, "%d: %s %dx%d@%.2f", i, d->name, d->primary_mode.width, + d->primary_mode.height, + (double)d->primary_mode.dot_clock / (d->primary_mode.htotal * d->primary_mode.vtotal)); } } static bool comp_window_direct_randr_init(struct comp_target *ct) { - struct comp_window_direct_randr *w_direct = - (struct comp_window_direct_randr *)ct; + struct comp_window_direct_randr *w_direct = (struct comp_window_direct_randr *)ct; // Sanity check. if (ct->c->vk.instance != VK_NULL_HANDLE) { @@ -197,8 +187,7 @@ comp_window_direct_randr_init(struct comp_target *ct) xcb_connection_t *connection = XGetXCBConnection(w_direct->dpy); - xcb_screen_iterator_t iter = - xcb_setup_roots_iterator(xcb_get_setup(connection)); + xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(connection)); w_direct->screen = iter.data; @@ -216,20 +205,17 @@ comp_window_direct_randr_init(struct comp_target *ct) ct->c->settings.display, w_direct->num_displays); ct->c->settings.display = 0; - struct comp_window_direct_randr_display *d = - comp_window_direct_randr_current_display(w_direct); + struct comp_window_direct_randr_display *d = comp_window_direct_randr_current_display(w_direct); COMP_DEBUG(ct->c, "Selecting '%s' instead.", d->name); } if (ct->c->settings.display < 0) { ct->c->settings.display = 0; - struct comp_window_direct_randr_display *d = - comp_window_direct_randr_current_display(w_direct); + struct comp_window_direct_randr_display *d = comp_window_direct_randr_current_display(w_direct); COMP_DEBUG(ct->c, "Selecting '%s' first display.", d->name); } - struct comp_window_direct_randr_display *d = - comp_window_direct_randr_current_display(w_direct); + struct comp_window_direct_randr_display *d = comp_window_direct_randr_current_display(w_direct); ct->c->settings.preferred.width = d->primary_mode.width; ct->c->settings.preferred.height = d->primary_mode.height; @@ -250,48 +236,38 @@ comp_window_direct_randr_current_display(struct comp_window_direct_randr *w) } static bool -comp_window_direct_randr_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height) +comp_window_direct_randr_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height) { - struct comp_window_direct_randr *w_direct = - (struct comp_window_direct_randr *)ct; + struct comp_window_direct_randr *w_direct = (struct comp_window_direct_randr *)ct; - struct comp_window_direct_randr_display *d = - comp_window_direct_randr_current_display(w_direct); + struct comp_window_direct_randr_display *d = comp_window_direct_randr_current_display(w_direct); if (!d) { COMP_ERROR(ct->c, "RandR could not find any HMDs."); return false; } - COMP_DEBUG(ct->c, "Will use display: %s %dx%d@%.2f", d->name, - d->primary_mode.width, d->primary_mode.height, - (double)d->primary_mode.dot_clock / - (d->primary_mode.htotal * d->primary_mode.vtotal)); + COMP_DEBUG(ct->c, "Will use display: %s %dx%d@%.2f", d->name, d->primary_mode.width, d->primary_mode.height, + (double)d->primary_mode.dot_clock / (d->primary_mode.htotal * d->primary_mode.vtotal)); d->display = comp_window_direct_randr_get_output(w_direct, d->output); if (d->display == VK_NULL_HANDLE) { return false; } - return comp_window_direct_init_swapchain(&w_direct->base, w_direct->dpy, - d->display, width, height); + return comp_window_direct_init_swapchain(&w_direct->base, w_direct->dpy, d->display, width, height); } static VkDisplayKHR -comp_window_direct_randr_get_output(struct comp_window_direct_randr *w, - RROutput output) +comp_window_direct_randr_get_output(struct comp_window_direct_randr *w, RROutput output) { struct vk_bundle *vk = get_vk(w); VkResult ret; VkDisplayKHR display; - ret = vk->vkGetRandROutputDisplayEXT(vk->physical_device, w->dpy, - output, &display); + ret = vk->vkGetRandROutputDisplayEXT(vk->physical_device, w->dpy, output, &display); if (ret != VK_SUCCESS) { - COMP_ERROR(w->base.base.c, "vkGetRandROutputDisplayEXT: %s", - vk_result_string(ret)); + COMP_ERROR(w->base.base.c, "vkGetRandROutputDisplayEXT: %s", vk_result_string(ret)); return VK_NULL_HANDLE; } @@ -312,8 +288,7 @@ append_randr_display(struct comp_window_direct_randr *w, xcb_randr_get_screen_resources_reply_t *resources_reply, xcb_randr_output_t xcb_output) { - xcb_randr_mode_t *output_modes = - xcb_randr_get_output_info_modes(output_reply); + xcb_randr_mode_t *output_modes = xcb_randr_get_output_info_modes(output_reply); uint8_t *name = xcb_randr_get_output_info_name(output_reply); int name_len = xcb_randr_get_output_info_name_length(output_reply); @@ -327,8 +302,7 @@ append_randr_display(struct comp_window_direct_randr *w, name); } - xcb_randr_mode_info_t *mode_infos = - xcb_randr_get_screen_resources_modes(resources_reply); + xcb_randr_mode_info_t *mode_infos = xcb_randr_get_screen_resources_modes(resources_reply); int n = xcb_randr_get_screen_resources_modes_length(resources_reply); @@ -338,8 +312,7 @@ append_randr_display(struct comp_window_direct_randr *w, mode_info = &mode_infos[i]; if (mode_info == NULL) - COMP_ERROR(w->base.base.c, "No mode with id %d found??", - output_modes[0]); + COMP_ERROR(w->base.base.c, "No mode with id %d found??", output_modes[0]); struct comp_window_direct_randr_display d = { @@ -354,13 +327,10 @@ append_randr_display(struct comp_window_direct_randr *w, w->num_displays += 1; - U_ARRAY_REALLOC_OR_FREE(w->displays, - struct comp_window_direct_randr_display, - w->num_displays); + U_ARRAY_REALLOC_OR_FREE(w->displays, struct comp_window_direct_randr_display, w->num_displays); if (w->displays == NULL) - COMP_ERROR(w->base.base.c, - "Unable to reallocate randr_displays"); + COMP_ERROR(w->base.base.c, "Unable to reallocate randr_displays"); w->displays[w->num_displays - 1] = d; } @@ -372,8 +342,7 @@ comp_window_direct_randr_get_outputs(struct comp_window_direct_randr *w) xcb_connection_t *connection = XGetXCBConnection(w->dpy); xcb_randr_query_version_cookie_t version_cookie = - xcb_randr_query_version(connection, XCB_RANDR_MAJOR_VERSION, - XCB_RANDR_MINOR_VERSION); + xcb_randr_query_version(connection, XCB_RANDR_MAJOR_VERSION, XCB_RANDR_MINOR_VERSION); xcb_randr_query_version_reply_t *version_reply = xcb_randr_query_version_reply(connection, version_cookie, NULL); @@ -382,25 +351,21 @@ comp_window_direct_randr_get_outputs(struct comp_window_direct_randr *w) return; } - COMP_DEBUG(ct->c, "RandR version %d.%d", version_reply->major_version, - version_reply->minor_version); + COMP_DEBUG(ct->c, "RandR version %d.%d", version_reply->major_version, version_reply->minor_version); - if (version_reply->major_version < 1 || - version_reply->minor_version < 6) { + if (version_reply->major_version < 1 || version_reply->minor_version < 6) { COMP_DEBUG(ct->c, "RandR version below 1.6."); } free(version_reply); xcb_generic_error_t *error = NULL; - xcb_intern_atom_cookie_t non_desktop_cookie = xcb_intern_atom( - connection, 1, strlen("non-desktop"), "non-desktop"); - xcb_intern_atom_reply_t *non_desktop_reply = - xcb_intern_atom_reply(connection, non_desktop_cookie, &error); + xcb_intern_atom_cookie_t non_desktop_cookie = + xcb_intern_atom(connection, 1, strlen("non-desktop"), "non-desktop"); + xcb_intern_atom_reply_t *non_desktop_reply = xcb_intern_atom_reply(connection, non_desktop_cookie, &error); if (error != NULL) { - COMP_ERROR(ct->c, "xcb_intern_atom_reply returned error %d", - error->error_code); + COMP_ERROR(ct->c, "xcb_intern_atom_reply returned error %d", error->error_code); return; } @@ -417,24 +382,19 @@ comp_window_direct_randr_get_outputs(struct comp_window_direct_randr *w) xcb_randr_get_screen_resources_cookie_t resources_cookie = xcb_randr_get_screen_resources(connection, w->screen->root); xcb_randr_get_screen_resources_reply_t *resources_reply = - xcb_randr_get_screen_resources_reply(connection, resources_cookie, - NULL); - xcb_randr_output_t *xcb_outputs = - xcb_randr_get_screen_resources_outputs(resources_reply); + xcb_randr_get_screen_resources_reply(connection, resources_cookie, NULL); + xcb_randr_output_t *xcb_outputs = xcb_randr_get_screen_resources_outputs(resources_reply); - int count = - xcb_randr_get_screen_resources_outputs_length(resources_reply); + int count = xcb_randr_get_screen_resources_outputs_length(resources_reply); if (count < 1) { COMP_ERROR(ct->c, "failed to retrieve randr outputs"); } for (int i = 0; i < count; i++) { xcb_randr_get_output_info_cookie_t output_cookie = - xcb_randr_get_output_info(connection, xcb_outputs[i], - XCB_CURRENT_TIME); + xcb_randr_get_output_info(connection, xcb_outputs[i], XCB_CURRENT_TIME); xcb_randr_get_output_info_reply_t *output_reply = - xcb_randr_get_output_info_reply(connection, output_cookie, - NULL); + xcb_randr_get_output_info_reply(connection, output_cookie, NULL); // Only outputs with an available mode should be used // (it is possible to see 'ghost' outputs with non-desktop=1). @@ -445,12 +405,10 @@ comp_window_direct_randr_get_outputs(struct comp_window_direct_randr *w) // Find the first output that has the non-desktop property set. xcb_randr_get_output_property_cookie_t prop_cookie; - prop_cookie = xcb_randr_get_output_property( - connection, xcb_outputs[i], non_desktop_reply->atom, - XCB_ATOM_NONE, 0, 4, 0, 0); + prop_cookie = xcb_randr_get_output_property(connection, xcb_outputs[i], non_desktop_reply->atom, + XCB_ATOM_NONE, 0, 4, 0, 0); xcb_randr_get_output_property_reply_t *prop_reply = NULL; - prop_reply = xcb_randr_get_output_property_reply( - connection, prop_cookie, &error); + prop_reply = xcb_randr_get_output_property_reply(connection, prop_cookie, &error); if (error != NULL) { COMP_ERROR(ct->c, "xcb_randr_get_output_property_reply " @@ -466,18 +424,15 @@ comp_window_direct_randr_get_outputs(struct comp_window_direct_randr *w) continue; } - if (prop_reply->type != XCB_ATOM_INTEGER || - prop_reply->num_items != 1 || prop_reply->format != 32) { + if (prop_reply->type != XCB_ATOM_INTEGER || prop_reply->num_items != 1 || prop_reply->format != 32) { COMP_ERROR(ct->c, "Invalid non-desktop reply"); free(prop_reply); continue; } - uint8_t non_desktop = - *xcb_randr_get_output_property_data(prop_reply); + uint8_t non_desktop = *xcb_randr_get_output_property_data(prop_reply); if (non_desktop == 1) - append_randr_display(w, output_reply, resources_reply, - xcb_outputs[i]); + append_randr_display(w, output_reply, resources_reply, xcb_outputs[i]); free(prop_reply); free(output_reply); diff --git a/src/xrt/compositor/main/comp_window_mswin.c b/src/xrt/compositor/main/comp_window_mswin.c index e89917c0e..ae27e233d 100644 --- a/src/xrt/compositor/main/comp_window_mswin.c +++ b/src/xrt/compositor/main/comp_window_mswin.c @@ -99,8 +99,7 @@ comp_window_mswin_fullscreen(struct comp_window_mswin *w) } static VkResult -comp_window_mswin_create_surface(struct comp_window_mswin *w, - VkSurfaceKHR *vk_surface) +comp_window_mswin_create_surface(struct comp_window_mswin *w, VkSurfaceKHR *vk_surface) { struct vk_bundle *vk = get_vk(w); VkResult ret; @@ -110,11 +109,9 @@ comp_window_mswin_create_surface(struct comp_window_mswin *w, .hwnd = w->window, }; - ret = vk->vkCreateWin32SurfaceKHR(vk->instance, &surface_info, NULL, - vk_surface); + ret = vk->vkCreateWin32SurfaceKHR(vk->instance, &surface_info, NULL, vk_surface); if (ret != VK_SUCCESS) { - COMP_ERROR(w->base.base.c, "vkCreateWin32SurfaceKHR: %s", - vk_result_string(ret)); + COMP_ERROR(w->base.base.c, "vkCreateWin32SurfaceKHR: %s", vk_result_string(ret)); return ret; } @@ -122,9 +119,7 @@ comp_window_mswin_create_surface(struct comp_window_mswin *w, } static bool -comp_window_mswin_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height) +comp_window_mswin_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height) { struct comp_window_mswin *cwm = (struct comp_window_mswin *)ct; VkResult ret; @@ -173,18 +168,14 @@ comp_window_mswin_init(struct comp_target *ct) #endif RegisterClassExW(&wcex); - cwm->window = - CreateWindowW(szWindowClass, L"Monado (Windowed)", - WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, - 0, NULL, NULL, cwm->instance, NULL); + cwm->window = CreateWindowW(szWindowClass, L"Monado (Windowed)", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, + CW_USEDEFAULT, 0, NULL, NULL, cwm->instance, NULL); return true; } static void -comp_window_mswin_configure(struct comp_window_mswin *w, - int32_t width, - int32_t height) +comp_window_mswin_configure(struct comp_window_mswin *w, int32_t width, int32_t height) { if (w->base.base.c->settings.fullscreen && !w->fullscreen_requested) { COMP_DEBUG(w->base.base.c, "Setting full screen"); diff --git a/src/xrt/compositor/main/comp_window_wayland.c b/src/xrt/compositor/main/comp_window_wayland.c index 030eb5029..771b5a6ed 100644 --- a/src/xrt/compositor/main/comp_window_wayland.c +++ b/src/xrt/compositor/main/comp_window_wayland.c @@ -61,8 +61,7 @@ static bool comp_window_wayland_init(struct comp_target *ct); static void -comp_window_wayland_update_window_title(struct comp_target *ct, - const char *title); +comp_window_wayland_update_window_title(struct comp_target *ct, const char *title); static void comp_window_wayland_registry_global(struct comp_window_wayland *w, @@ -74,21 +73,16 @@ static void comp_window_wayland_fullscreen(struct comp_window_wayland *w); static bool -comp_window_wayland_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height); +comp_window_wayland_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height); static VkResult -comp_window_wayland_create_surface(struct comp_window_wayland *w, - VkSurfaceKHR *vk_surface); +comp_window_wayland_create_surface(struct comp_window_wayland *w, VkSurfaceKHR *vk_surface); static void comp_window_wayland_flush(struct comp_target *ct); static void -comp_window_wayland_configure(struct comp_window_wayland *w, - int32_t width, - int32_t height); +comp_window_wayland_configure(struct comp_window_wayland *w, int32_t width, int32_t height); /* @@ -106,8 +100,7 @@ get_vk(struct comp_window_wayland *cww) struct comp_target * comp_window_wayland_create(struct comp_compositor *c) { - struct comp_window_wayland *w = - U_TYPED_CALLOC(struct comp_window_wayland); + struct comp_window_wayland *w = U_TYPED_CALLOC(struct comp_window_wayland); comp_target_swapchain_init_set_fnptrs(&w->base); @@ -146,11 +139,9 @@ comp_window_wayland_destroy(struct comp_target *ct) } static void -comp_window_wayland_update_window_title(struct comp_target *ct, - const char *title) +comp_window_wayland_update_window_title(struct comp_target *ct, const char *title) { - struct comp_window_wayland *w_wayland = - (struct comp_window_wayland *)ct; + struct comp_window_wayland *w_wayland = (struct comp_window_wayland *)ct; xdg_toplevel_set_title(w_wayland->xdg_toplevel, title); } @@ -162,19 +153,14 @@ comp_window_wayland_fullscreen(struct comp_window_wayland *w) } static void -_xdg_surface_configure_cb(void *data, - struct xdg_surface *surface, - uint32_t serial) +_xdg_surface_configure_cb(void *data, struct xdg_surface *surface, uint32_t serial) { xdg_surface_ack_configure(surface, serial); } static void -_xdg_toplevel_configure_cb(void *data, - struct xdg_toplevel *toplevel, - int32_t width, - int32_t height, - struct wl_array *states) +_xdg_toplevel_configure_cb( + void *data, struct xdg_toplevel *toplevel, int32_t width, int32_t height, struct wl_array *states) { struct comp_window_wayland *w = (struct comp_window_wayland *)data; comp_window_wayland_configure(w, width, height); @@ -204,16 +190,12 @@ static const struct xdg_wm_base_listener xdg_wm_base_listener = { }; static bool -comp_window_wayland_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height) +comp_window_wayland_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height) { - struct comp_window_wayland *w_wayland = - (struct comp_window_wayland *)ct; + struct comp_window_wayland *w_wayland = (struct comp_window_wayland *)ct; VkResult ret; - ret = comp_window_wayland_create_surface( - w_wayland, &w_wayland->base.surface.handle); + ret = comp_window_wayland_create_surface(w_wayland, &w_wayland->base.surface.handle); if (ret != VK_SUCCESS) { COMP_ERROR(ct->c, "Failed to create surface!"); return false; @@ -226,8 +208,7 @@ comp_window_wayland_init_swapchain(struct comp_target *ct, } static VkResult -comp_window_wayland_create_surface(struct comp_window_wayland *w, - VkSurfaceKHR *vk_surface) +comp_window_wayland_create_surface(struct comp_window_wayland *w, VkSurfaceKHR *vk_surface) { struct vk_bundle *vk = get_vk(w); VkResult ret; @@ -238,11 +219,9 @@ comp_window_wayland_create_surface(struct comp_window_wayland *w, .surface = w->surface, }; - ret = vk->vkCreateWaylandSurfaceKHR(vk->instance, &surface_info, NULL, - vk_surface); + ret = vk->vkCreateWaylandSurfaceKHR(vk->instance, &surface_info, NULL, vk_surface); if (ret != VK_SUCCESS) { - COMP_ERROR(w->base.base.c, "vkCreateWaylandSurfaceKHR: %s", - vk_result_string(ret)); + COMP_ERROR(w->base.base.c, "vkCreateWaylandSurfaceKHR: %s", vk_result_string(ret)); return ret; } @@ -252,8 +231,7 @@ comp_window_wayland_create_surface(struct comp_window_wayland *w, static void comp_window_wayland_flush(struct comp_target *ct) { - struct comp_window_wayland *w_wayland = - (struct comp_window_wayland *)ct; + struct comp_window_wayland *w_wayland = (struct comp_window_wayland *)ct; while (wl_display_prepare_read(w_wayland->display) != 0) wl_display_dispatch_pending(w_wayland->display); @@ -279,17 +257,11 @@ comp_window_wayland_flush(struct comp_target *ct) } static void -_registry_global_remove_cb(void *data, - struct wl_registry *registry, - uint32_t name) +_registry_global_remove_cb(void *data, struct wl_registry *registry, uint32_t name) {} static void -_registry_global_cb(void *data, - struct wl_registry *registry, - uint32_t name, - const char *interface, - uint32_t version) +_registry_global_cb(void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version) { struct comp_window_wayland *w = (struct comp_window_wayland *)data; // vik_log_d("Interface: %s Version %d", interface, version); @@ -308,11 +280,9 @@ comp_window_wayland_registry_global(struct comp_window_wayland *w, const char *interface) { if (strcmp(interface, "wl_compositor") == 0) { - w->compositor = (struct wl_compositor *)wl_registry_bind( - registry, name, &wl_compositor_interface, 4); + w->compositor = (struct wl_compositor *)wl_registry_bind(registry, name, &wl_compositor_interface, 4); } else if (strcmp(interface, "xdg_wm_base") == 0) { - w->wm_base = (struct xdg_wm_base *)wl_registry_bind( - registry, name, &xdg_wm_base_interface, 1); + w->wm_base = (struct xdg_wm_base *)wl_registry_bind(registry, name, &xdg_wm_base_interface, 1); xdg_wm_base_add_listener(w->wm_base, &xdg_wm_base_listener, w); } } @@ -320,40 +290,33 @@ comp_window_wayland_registry_global(struct comp_window_wayland *w, static bool comp_window_wayland_init(struct comp_target *ct) { - struct comp_window_wayland *w_wayland = - (struct comp_window_wayland *)ct; + struct comp_window_wayland *w_wayland = (struct comp_window_wayland *)ct; w_wayland->display = wl_display_connect(NULL); if (!w_wayland->display) { return false; } - struct wl_registry *registry = - wl_display_get_registry(w_wayland->display); + struct wl_registry *registry = wl_display_get_registry(w_wayland->display); wl_registry_add_listener(registry, ®istry_listener, w_wayland); wl_display_roundtrip(w_wayland->display); wl_registry_destroy(registry); - w_wayland->surface = - wl_compositor_create_surface(w_wayland->compositor); + w_wayland->surface = wl_compositor_create_surface(w_wayland->compositor); if (!w_wayland->wm_base) { COMP_ERROR(ct->c, "Compositor is missing xdg-shell support"); } - w_wayland->xdg_surface = - xdg_wm_base_get_xdg_surface(w_wayland->wm_base, w_wayland->surface); + w_wayland->xdg_surface = xdg_wm_base_get_xdg_surface(w_wayland->wm_base, w_wayland->surface); - xdg_surface_add_listener(w_wayland->xdg_surface, &xdg_surface_listener, - w_wayland); + xdg_surface_add_listener(w_wayland->xdg_surface, &xdg_surface_listener, w_wayland); - w_wayland->xdg_toplevel = - xdg_surface_get_toplevel(w_wayland->xdg_surface); + w_wayland->xdg_toplevel = xdg_surface_get_toplevel(w_wayland->xdg_surface); - xdg_toplevel_add_listener(w_wayland->xdg_toplevel, - &xdg_toplevel_listener, w_wayland); + xdg_toplevel_add_listener(w_wayland->xdg_toplevel, &xdg_toplevel_listener, w_wayland); /* Sane defaults */ xdg_toplevel_set_app_id(w_wayland->xdg_toplevel, "openxr"); xdg_toplevel_set_title(w_wayland->xdg_toplevel, "OpenXR application"); @@ -364,9 +327,7 @@ comp_window_wayland_init(struct comp_target *ct) } static void -comp_window_wayland_configure(struct comp_window_wayland *w, - int32_t width, - int32_t height) +comp_window_wayland_configure(struct comp_window_wayland *w, int32_t width, int32_t height) { if (w->base.base.c->settings.fullscreen && !w->fullscreen_requested) { COMP_DEBUG(w->base.base.c, "Setting full screen"); diff --git a/src/xrt/compositor/main/comp_window_xcb.c b/src/xrt/compositor/main/comp_window_xcb.c index 2da7ebf92..5ec992cbf 100644 --- a/src/xrt/compositor/main/comp_window_xcb.c +++ b/src/xrt/compositor/main/comp_window_xcb.c @@ -84,17 +84,13 @@ static struct comp_window_xcb_display * comp_window_xcb_current_display(struct comp_window_xcb *w); static bool -comp_window_xcb_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height); +comp_window_xcb_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height); static int comp_window_xcb_connect(struct comp_window_xcb *w); static void -comp_window_xcb_create_window(struct comp_window_xcb *w, - uint32_t width, - uint32_t height); +comp_window_xcb_create_window(struct comp_window_xcb *w, uint32_t width, uint32_t height); static void comp_window_xcb_get_randr_outputs(struct comp_window_xcb *w); @@ -109,8 +105,7 @@ static xcb_atom_t comp_window_xcb_get_atom(struct comp_window_xcb *w, const char *name); static VkResult -comp_window_xcb_create_surface(struct comp_window_xcb *w, - VkSurfaceKHR *surface); +comp_window_xcb_create_surface(struct comp_window_xcb *w, VkSurfaceKHR *surface); static void comp_window_xcb_update_window_title(struct comp_target *ct, const char *title); @@ -167,15 +162,13 @@ comp_window_xcb_destroy(struct comp_target *ct) static void comp_window_xcb_list_screens(struct comp_window_xcb *w, xcb_screen_t *screen) { - COMP_DEBUG(w->base.base.c, "Screen 0 %dx%d", screen->width_in_pixels, - screen->height_in_pixels); + COMP_DEBUG(w->base.base.c, "Screen 0 %dx%d", screen->width_in_pixels, screen->height_in_pixels); comp_window_xcb_get_randr_outputs(w); for (uint16_t i = 0; i < w->num_displays; i++) { struct comp_window_xcb_display *d = &w->displays[i]; - COMP_DEBUG(w->base.base.c, "%d: %s %dx%d [%d, %d]", i, d->name, - d->size.width, d->size.height, d->position.x, - d->position.y); + COMP_DEBUG(w->base.base.c, "%d: %s %dx%d [%d, %d]", i, d->name, d->size.width, d->size.height, + d->position.x, d->position.y); } } @@ -188,8 +181,7 @@ comp_window_xcb_init(struct comp_target *ct) return false; } - xcb_screen_iterator_t iter = - xcb_setup_roots_iterator(xcb_get_setup(w_xcb->connection)); + xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(w_xcb->connection)); w_xcb->screen = iter.data; @@ -200,28 +192,24 @@ comp_window_xcb_init(struct comp_target *ct) COMP_DEBUG(ct->c, "Requested display %d, but only %d " "displays are available.", - ct->c->settings.display, - w_xcb->num_displays); + ct->c->settings.display, w_xcb->num_displays); ct->c->settings.display = 0; - struct comp_window_xcb_display *d = - comp_window_xcb_current_display(w_xcb); + struct comp_window_xcb_display *d = comp_window_xcb_current_display(w_xcb); COMP_DEBUG(ct->c, "Selecting '%s' instead.", d->name); } if (ct->c->settings.display == -1) ct->c->settings.display = 0; - struct comp_window_xcb_display *d = - comp_window_xcb_current_display(w_xcb); + struct comp_window_xcb_display *d = comp_window_xcb_current_display(w_xcb); ct->c->settings.preferred.width = d->size.width; ct->c->settings.preferred.height = d->size.height; // TODO: size cb // set_size_cb(settings->width, settings->height); } - comp_window_xcb_create_window(w_xcb, ct->c->settings.preferred.width, - ct->c->settings.preferred.height); + comp_window_xcb_create_window(w_xcb, ct->c->settings.preferred.width, ct->c->settings.preferred.height); comp_window_xcb_connect_delete_event(w_xcb); @@ -246,15 +234,12 @@ comp_window_xcb_flush(struct comp_target *ct) } static bool -comp_window_xcb_init_swapchain(struct comp_target *ct, - uint32_t width, - uint32_t height) +comp_window_xcb_init_swapchain(struct comp_target *ct, uint32_t width, uint32_t height) { struct comp_window_xcb *w_xcb = (struct comp_window_xcb *)ct; VkResult ret; - ret = - comp_window_xcb_create_surface(w_xcb, &w_xcb->base.surface.handle); + ret = comp_window_xcb_create_surface(w_xcb, &w_xcb->base.surface.handle); if (ret != VK_SUCCESS) { return false; } @@ -270,9 +255,7 @@ comp_window_xcb_connect(struct comp_window_xcb *w) } static void -comp_window_xcb_create_window(struct comp_window_xcb *w, - uint32_t width, - uint32_t height) +comp_window_xcb_create_window(struct comp_window_xcb *w, uint32_t width, uint32_t height) { w->window = xcb_generate_id(w->connection); @@ -286,10 +269,8 @@ comp_window_xcb_create_window(struct comp_window_xcb *w, uint32_t value_list = XCB_EVENT_MASK_STRUCTURE_NOTIFY; - xcb_create_window(w->connection, XCB_COPY_FROM_PARENT, w->window, - w->screen->root, x, y, width, height, 0, - XCB_WINDOW_CLASS_INPUT_OUTPUT, w->screen->root_visual, - XCB_CW_EVENT_MASK, &value_list); + xcb_create_window(w->connection, XCB_COPY_FROM_PARENT, w->window, w->screen->root, x, y, width, height, 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, w->screen->root_visual, XCB_CW_EVENT_MASK, &value_list); } static void @@ -298,44 +279,33 @@ comp_window_xcb_get_randr_outputs(struct comp_window_xcb *w) xcb_randr_get_screen_resources_cookie_t resources_cookie = xcb_randr_get_screen_resources(w->connection, w->screen->root); xcb_randr_get_screen_resources_reply_t *resources_reply = - xcb_randr_get_screen_resources_reply(w->connection, - resources_cookie, NULL); - xcb_randr_output_t *xcb_outputs = - xcb_randr_get_screen_resources_outputs(resources_reply); + xcb_randr_get_screen_resources_reply(w->connection, resources_cookie, NULL); + xcb_randr_output_t *xcb_outputs = xcb_randr_get_screen_resources_outputs(resources_reply); - w->num_displays = - xcb_randr_get_screen_resources_outputs_length(resources_reply); + w->num_displays = xcb_randr_get_screen_resources_outputs_length(resources_reply); if (w->num_displays < 1) COMP_ERROR(w->base.base.c, "Failed to retrieve randr outputs"); - w->displays = - calloc(w->num_displays, sizeof(struct comp_window_xcb_display)); + w->displays = calloc(w->num_displays, sizeof(struct comp_window_xcb_display)); for (int i = 0; i < w->num_displays; i++) { xcb_randr_get_output_info_cookie_t output_cookie = - xcb_randr_get_output_info(w->connection, xcb_outputs[i], - XCB_CURRENT_TIME); + xcb_randr_get_output_info(w->connection, xcb_outputs[i], XCB_CURRENT_TIME); xcb_randr_get_output_info_reply_t *output_reply = - xcb_randr_get_output_info_reply(w->connection, - output_cookie, NULL); + xcb_randr_get_output_info_reply(w->connection, output_cookie, NULL); - if (output_reply->connection != - XCB_RANDR_CONNECTION_CONNECTED || - output_reply->crtc == XCB_NONE) { + if (output_reply->connection != XCB_RANDR_CONNECTION_CONNECTED || output_reply->crtc == XCB_NONE) { free(output_reply); continue; } xcb_randr_get_crtc_info_cookie_t crtc_cookie = - xcb_randr_get_crtc_info(w->connection, output_reply->crtc, - XCB_CURRENT_TIME); + xcb_randr_get_crtc_info(w->connection, output_reply->crtc, XCB_CURRENT_TIME); xcb_randr_get_crtc_info_reply_t *crtc_reply = - xcb_randr_get_crtc_info_reply(w->connection, crtc_cookie, - NULL); + xcb_randr_get_crtc_info_reply(w->connection, crtc_cookie, NULL); uint8_t *name = xcb_randr_get_output_info_name(output_reply); - int name_len = - xcb_randr_get_output_info_name_length(output_reply); + int name_len = xcb_randr_get_output_info_name_length(output_reply); w->displays[i] = (struct comp_window_xcb_display){ .name = U_TYPED_ARRAY_CALLOC(char, name_len + 1), @@ -356,10 +326,8 @@ static void comp_window_xcb_connect_delete_event(struct comp_window_xcb *w) { w->atom_wm_protocols = comp_window_xcb_get_atom(w, "WM_PROTOCOLS"); - w->atom_wm_delete_window = - comp_window_xcb_get_atom(w, "WM_DELETE_WINDOW"); - xcb_change_property(w->connection, XCB_PROP_MODE_REPLACE, w->window, - w->atom_wm_protocols, XCB_ATOM_ATOM, 32, 1, + w->atom_wm_delete_window = comp_window_xcb_get_atom(w, "WM_DELETE_WINDOW"); + xcb_change_property(w->connection, XCB_PROP_MODE_REPLACE, w->window, w->atom_wm_protocols, XCB_ATOM_ATOM, 32, 1, &w->atom_wm_delete_window); } @@ -367,10 +335,8 @@ static void comp_window_xcb_set_full_screen(struct comp_window_xcb *w) { xcb_atom_t atom_wm_state = comp_window_xcb_get_atom(w, "_NET_WM_STATE"); - xcb_atom_t atom_wm_fullscreen = - comp_window_xcb_get_atom(w, "_NET_WM_STATE_FULLSCREEN"); - xcb_change_property(w->connection, XCB_PROP_MODE_REPLACE, w->window, - atom_wm_state, XCB_ATOM_ATOM, 32, 1, + xcb_atom_t atom_wm_fullscreen = comp_window_xcb_get_atom(w, "_NET_WM_STATE_FULLSCREEN"); + xcb_change_property(w->connection, XCB_PROP_MODE_REPLACE, w->window, atom_wm_state, XCB_ATOM_ATOM, 32, 1, &atom_wm_fullscreen); } @@ -405,11 +371,9 @@ comp_window_xcb_create_surface(struct comp_window_xcb *w, VkSurfaceKHR *surface) .window = w->window, }; - ret = vk->vkCreateXcbSurfaceKHR(vk->instance, &surface_info, NULL, - surface); + ret = vk->vkCreateXcbSurfaceKHR(vk->instance, &surface_info, NULL, surface); if (ret != VK_SUCCESS) { - COMP_ERROR(w->base.base.c, "vkCreateXcbSurfaceKHR: %s", - vk_result_string(ret)); + COMP_ERROR(w->base.base.c, "vkCreateXcbSurfaceKHR: %s", vk_result_string(ret)); return ret; } @@ -421,7 +385,6 @@ comp_window_xcb_update_window_title(struct comp_target *ct, const char *title) { struct comp_window_xcb *w_xcb = (struct comp_window_xcb *)ct; - xcb_change_property(w_xcb->connection, XCB_PROP_MODE_REPLACE, - w_xcb->window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8, - strlen(title), title); + xcb_change_property(w_xcb->connection, XCB_PROP_MODE_REPLACE, w_xcb->window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, + 8, strlen(title), title); } diff --git a/src/xrt/compositor/render/comp_buffer.c b/src/xrt/compositor/render/comp_buffer.c index f40c112eb..96146b347 100644 --- a/src/xrt/compositor/render/comp_buffer.c +++ b/src/xrt/compositor/render/comp_buffer.c @@ -46,8 +46,7 @@ create_buffer(struct vk_bundle *vk, NULL, // &buffer); // if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkCreateBuffer failed: '%s'", - vk_result_string(ret)); + VK_ERROR(vk, "vkCreateBuffer failed: '%s'", vk_result_string(ret)); return ret; } @@ -76,8 +75,7 @@ create_buffer(struct vk_bundle *vk, NULL, // &memory); // if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkAllocateMemory failed: '%s'", - vk_result_string(ret)); + VK_ERROR(vk, "vkAllocateMemory failed: '%s'", vk_result_string(ret)); goto err_buffer; } @@ -88,8 +86,7 @@ create_buffer(struct vk_bundle *vk, memory, // memory 0); // memoryOffset if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkBindBufferMemory failed: '%s'", - vk_result_string(ret)); + VK_ERROR(vk, "vkBindBufferMemory failed: '%s'", vk_result_string(ret)); goto err_memory; } @@ -168,10 +165,7 @@ comp_buffer_unmap(struct vk_bundle *vk, struct comp_buffer *buffer) } VkResult -comp_buffer_map_and_write(struct vk_bundle *vk, - struct comp_buffer *buffer, - void *data, - VkDeviceSize size) +comp_buffer_map_and_write(struct vk_bundle *vk, struct comp_buffer *buffer, void *data, VkDeviceSize size) { VkResult ret; @@ -193,10 +187,7 @@ comp_buffer_map_and_write(struct vk_bundle *vk, } VkResult -comp_buffer_write(struct vk_bundle *vk, - struct comp_buffer *buffer, - void *data, - VkDeviceSize size) +comp_buffer_write(struct vk_bundle *vk, struct comp_buffer *buffer, void *data, VkDeviceSize size) { if (size > buffer->allocation_size) { VK_ERROR(vk, "Trying to write more the buffer size!"); diff --git a/src/xrt/compositor/render/comp_render.h b/src/xrt/compositor/render/comp_render.h index b8df3d1d7..4c470d3cf 100644 --- a/src/xrt/compositor/render/comp_render.h +++ b/src/xrt/compositor/render/comp_render.h @@ -90,19 +90,13 @@ comp_buffer_unmap(struct vk_bundle *vk, struct comp_buffer *buffer); * Maps the buffer, and copies the given data to the buffer. */ VkResult -comp_buffer_map_and_write(struct vk_bundle *vk, - struct comp_buffer *buffer, - void *data, - VkDeviceSize size); +comp_buffer_map_and_write(struct vk_bundle *vk, struct comp_buffer *buffer, void *data, VkDeviceSize size); /*! * Writes the given data to the buffer, will map it temporarily if not mapped. */ VkResult -comp_buffer_write(struct vk_bundle *vk, - struct comp_buffer *buffer, - void *data, - VkDeviceSize size); +comp_buffer_write(struct vk_bundle *vk, struct comp_buffer *buffer, void *data, VkDeviceSize size); /* @@ -253,9 +247,7 @@ struct comp_rendering * Init struct and create resources needed for rendering. */ bool -comp_rendering_init(struct comp_compositor *c, - struct comp_resources *r, - struct comp_rendering *rr); +comp_rendering_init(struct comp_compositor *c, struct comp_resources *r, struct comp_rendering *rr); /*! * Frees all resources held by the rendering, does not free the struct itself. @@ -294,9 +286,7 @@ struct comp_mesh_ubo_data * to comp_draw_begin_view. */ bool -comp_draw_begin_target_single(struct comp_rendering *rr, - VkImageView target, - struct comp_target_data *data); +comp_draw_begin_target_single(struct comp_rendering *rr, VkImageView target, struct comp_target_data *data); void comp_draw_end_target(struct comp_rendering *rr); @@ -326,18 +316,12 @@ comp_draw_projection_layer(struct comp_rendering *rr, struct xrt_layer_data *data); void -comp_draw_quad_layer(struct comp_rendering *rr, - uint32_t layer, - VkSampler sampler, - VkImageView image_view, - struct xrt_layer_data *data); +comp_draw_quad_layer( + struct comp_rendering *rr, uint32_t layer, VkSampler sampler, VkImageView image_view, struct xrt_layer_data *data); void -comp_draw_cylinder_layer(struct comp_rendering *rr, - uint32_t layer, - VkSampler sampler, - VkImageView image_view, - struct xrt_layer_data *data); +comp_draw_cylinder_layer( + struct comp_rendering *rr, uint32_t layer, VkSampler sampler, VkImageView image_view, struct xrt_layer_data *data); void comp_draw_distortion(struct comp_rendering *rr, diff --git a/src/xrt/compositor/render/comp_rendering.c b/src/xrt/compositor/render/comp_rendering.c index badf0a22b..0bb1c0326 100644 --- a/src/xrt/compositor/render/comp_rendering.c +++ b/src/xrt/compositor/render/comp_rendering.c @@ -20,30 +20,28 @@ * */ -#define C(c) \ - do { \ - VkResult ret = c; \ - if (ret != VK_SUCCESS) { \ - return false; \ - } \ +#define C(c) \ + do { \ + VkResult ret = c; \ + if (ret != VK_SUCCESS) { \ + return false; \ + } \ } while (false) -#define D(TYPE, thing) \ - if (thing != VK_NULL_HANDLE) { \ - vk->vkDestroy##TYPE(vk->device, thing, NULL); \ - thing = VK_NULL_HANDLE; \ +#define D(TYPE, thing) \ + if (thing != VK_NULL_HANDLE) { \ + vk->vkDestroy##TYPE(vk->device, thing, NULL); \ + thing = VK_NULL_HANDLE; \ } -#define DD(pool, thing) \ - if (thing != VK_NULL_HANDLE) { \ - free_descriptor_set(vk, pool, thing); \ - thing = VK_NULL_HANDLE; \ +#define DD(pool, thing) \ + if (thing != VK_NULL_HANDLE) { \ + free_descriptor_set(vk, pool, thing); \ + thing = VK_NULL_HANDLE; \ } static VkResult -create_external_render_pass(struct vk_bundle *vk, - VkFormat format, - VkRenderPass *out_render_pass) +create_external_render_pass(struct vk_bundle *vk, VkFormat format, VkRenderPass *out_render_pass) { VkResult ret; @@ -86,8 +84,7 @@ create_external_render_pass(struct vk_bundle *vk, .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, .srcAccessMask = 0, - .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, }, }; @@ -107,8 +104,7 @@ create_external_render_pass(struct vk_bundle *vk, NULL, // &render_pass); // if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkCreateRenderPass failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkCreateRenderPass failed: %s", vk_result_string(ret)); return ret; } @@ -137,8 +133,7 @@ create_descriptor_set(struct vk_bundle *vk, &alloc_info, // &descriptor_set); // if (ret != VK_SUCCESS) { - VK_DEBUG(vk, "vkAllocateDescriptorSets failed: %s", - vk_result_string(ret)); + VK_DEBUG(vk, "vkAllocateDescriptorSets failed: %s", vk_result_string(ret)); return ret; } @@ -148,9 +143,7 @@ create_descriptor_set(struct vk_bundle *vk, } static void -free_descriptor_set(struct vk_bundle *vk, - VkDescriptorPool descriptor_pool, - VkDescriptorSet descriptor_set) +free_descriptor_set(struct vk_bundle *vk, VkDescriptorPool descriptor_pool, VkDescriptorSet descriptor_set) { VkResult ret; @@ -160,8 +153,7 @@ free_descriptor_set(struct vk_bundle *vk, 1, // descriptorSetCount &descriptor_set); // pDescriptorSets if (ret != VK_SUCCESS) { - VK_DEBUG(vk, "vkFreeDescriptorSets failed: %s", - vk_result_string(ret)); + VK_DEBUG(vk, "vkFreeDescriptorSets failed: %s", vk_result_string(ret)); } } @@ -193,8 +185,7 @@ create_framebuffer(struct vk_bundle *vk, NULL, // &framebuffer); // if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkCreateFramebuffer failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkCreateFramebuffer failed: %s", vk_result_string(ret)); return ret; } @@ -226,8 +217,7 @@ create_command_buffer(struct vk_bundle *vk, VkCommandBuffer *out_cmd) os_mutex_unlock(&vk->cmd_pool_mutex); if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkCreateFramebuffer failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkCreateFramebuffer failed: %s", vk_result_string(ret)); return ret; } @@ -247,8 +237,7 @@ begin_command_buffer(struct vk_bundle *vk, VkCommandBuffer command_buffer) ret = vk->vkBeginCommandBuffer(command_buffer, &command_buffer_info); if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkBeginCommandBuffer failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkBeginCommandBuffer failed: %s", vk_result_string(ret)); return ret; } @@ -288,8 +277,7 @@ begin_render_pass(struct vk_bundle *vk, .pClearValues = clear_color, }; - vk->vkCmdBeginRenderPass(command_buffer, &render_pass_begin_info, - VK_SUBPASS_CONTENTS_INLINE); + vk->vkCmdBeginRenderPass(command_buffer, &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); } @@ -323,8 +311,7 @@ create_mesh_pipeline(struct vk_bundle *vk, } VkPipelineInputAssemblyStateCreateInfo input_assembly_state = { - .sType = - VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, + .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, .topology = topology, .primitiveRestartEnable = VK_FALSE, }; @@ -461,8 +448,7 @@ create_mesh_pipeline(struct vk_bundle *vk, NULL, // &pipeline); // if (ret != VK_SUCCESS) { - VK_DEBUG(vk, "vkCreateGraphicsPipelines failed: %s", - vk_result_string(ret)); + VK_DEBUG(vk, "vkCreateGraphicsPipelines failed: %s", vk_result_string(ret)); return ret; } @@ -472,15 +458,12 @@ create_mesh_pipeline(struct vk_bundle *vk, } static bool -init_mesh_ubo_buffers(struct vk_bundle *vk, - struct comp_buffer *l_ubo, - struct comp_buffer *r_ubo) +init_mesh_ubo_buffers(struct vk_bundle *vk, struct comp_buffer *l_ubo, struct comp_buffer *r_ubo) { // Using the same flags for all ubos. VkBufferUsageFlags ubo_usage_flags = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; VkMemoryPropertyFlags memory_property_flags = - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; // Distortion ubo size. VkDeviceSize ubo_size = sizeof(struct comp_mesh_ubo_data); @@ -544,12 +527,11 @@ update_mesh_discriptor_set(struct vk_bundle *vk, }, }; - vk->vkUpdateDescriptorSets( - vk->device, // - ARRAY_SIZE(write_descriptor_sets), // descriptorWriteCount - write_descriptor_sets, // pDescriptorWrites - 0, // descriptorCopyCount - NULL); // pDescriptorCopies + vk->vkUpdateDescriptorSets(vk->device, // + ARRAY_SIZE(write_descriptor_sets), // descriptorWriteCount + write_descriptor_sets, // pDescriptorWrites + 0, // descriptorCopyCount + NULL); // pDescriptorCopies } @@ -560,9 +542,7 @@ update_mesh_discriptor_set(struct vk_bundle *vk, */ bool -comp_rendering_init(struct comp_compositor *c, - struct comp_resources *r, - struct comp_rendering *rr) +comp_rendering_init(struct comp_compositor *c, struct comp_resources *r, struct comp_rendering *rr) { struct vk_bundle *vk = &c->vk; rr->c = c; @@ -580,17 +560,15 @@ comp_rendering_init(struct comp_compositor *c, * Mesh per view */ - C(create_descriptor_set( - vk, // vk_bundle - r->mesh_descriptor_pool, // descriptor_pool - r->mesh.descriptor_set_layout, // descriptor_set_layout - &rr->views[0].mesh.descriptor_set)); // descriptor_set + C(create_descriptor_set(vk, // vk_bundle + r->mesh_descriptor_pool, // descriptor_pool + r->mesh.descriptor_set_layout, // descriptor_set_layout + &rr->views[0].mesh.descriptor_set)); // descriptor_set - C(create_descriptor_set( - vk, // vk_bundle - r->mesh_descriptor_pool, // descriptor_pool - r->mesh.descriptor_set_layout, // descriptor_set_layout - &rr->views[1].mesh.descriptor_set)); // descriptor_set + C(create_descriptor_set(vk, // vk_bundle + r->mesh_descriptor_pool, // descriptor_pool + r->mesh.descriptor_set_layout, // descriptor_set_layout + &rr->views[1].mesh.descriptor_set)); // descriptor_set if (!init_mesh_ubo_buffers(vk, // &rr->views[0].mesh.ubo, // @@ -627,9 +605,7 @@ comp_rendering_close(struct comp_rendering *rr) */ bool -comp_draw_begin_target_single(struct comp_rendering *rr, - VkImageView target, - struct comp_target_data *data) +comp_draw_begin_target_single(struct comp_rendering *rr, VkImageView target, struct comp_target_data *data) { struct vk_bundle *vk = &rr->c->vk; struct comp_resources *r = rr->r; @@ -644,25 +620,23 @@ comp_draw_begin_target_single(struct comp_rendering *rr, data->format, // target_format &rr->render_pass)); // out_render_pass - C(create_mesh_pipeline( - vk, // vk_bundle - rr->render_pass, // render_pass - r->mesh.pipeline_layout, // pipeline_layout - r->pipeline_cache, // pipeline_cache - r->mesh.src_binding, // src_binding - r->mesh.total_num_indices, // mesh_total_num_indices - r->mesh.stride, // mesh_stride - rr->c->shaders.mesh_vert, // mesh_vert - rr->c->shaders.mesh_frag, // mesh_frag - &rr->mesh.pipeline)); // out_mesh_pipeline - - C(create_framebuffer( - vk, // vk_bundle, - target, // image_view, - rr->render_pass, // render_pass, - data->width, // width, - data->height, // height, - &rr->targets[0].framebuffer)); // out_external_framebuffer + C(create_mesh_pipeline(vk, // vk_bundle + rr->render_pass, // render_pass + r->mesh.pipeline_layout, // pipeline_layout + r->pipeline_cache, // pipeline_cache + r->mesh.src_binding, // src_binding + r->mesh.total_num_indices, // mesh_total_num_indices + r->mesh.stride, // mesh_stride + rr->c->shaders.mesh_vert, // mesh_vert + rr->c->shaders.mesh_frag, // mesh_frag + &rr->mesh.pipeline)); // out_mesh_pipeline + + C(create_framebuffer(vk, // vk_bundle, + target, // image_view, + rr->render_pass, // render_pass, + data->width, // width, + data->height, // height, + &rr->targets[0].framebuffer)); // out_external_framebuffer C(begin_command_buffer(vk, rr->cmd)); @@ -692,8 +666,7 @@ comp_draw_end_target(struct comp_rendering *rr) // End the command buffer. ret = vk->vkEndCommandBuffer(rr->cmd); if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkEndCommandBuffer failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkEndCommandBuffer failed: %s", vk_result_string(ret)); return; } } @@ -778,8 +751,7 @@ comp_draw_distortion(struct comp_rendering *rr, * Descriptors and pipeline. */ - comp_buffer_write(vk, &v->mesh.ubo, data, - sizeof(struct comp_mesh_ubo_data)); + comp_buffer_write(vk, &v->mesh.ubo, data, sizeof(struct comp_mesh_ubo_data)); update_mesh_discriptor_set( // vk, // vk_bundle diff --git a/src/xrt/compositor/render/comp_resources.c b/src/xrt/compositor/render/comp_resources.c index 74ee35641..44d05cf22 100644 --- a/src/xrt/compositor/render/comp_resources.c +++ b/src/xrt/compositor/render/comp_resources.c @@ -15,18 +15,18 @@ #include -#define C(c) \ - do { \ - VkResult ret = c; \ - if (ret != VK_SUCCESS) { \ - return false; \ - } \ +#define C(c) \ + do { \ + VkResult ret = c; \ + if (ret != VK_SUCCESS) { \ + return false; \ + } \ } while (false) -#define D(TYPE, thing) \ - if (thing != VK_NULL_HANDLE) { \ - vk->vkDestroy##TYPE(vk->device, thing, NULL); \ - thing = VK_NULL_HANDLE; \ +#define D(TYPE, thing) \ + if (thing != VK_NULL_HANDLE) { \ + vk->vkDestroy##TYPE(vk->device, thing, NULL); \ + thing = VK_NULL_HANDLE; \ } static VkResult @@ -44,8 +44,7 @@ create_pipeline_cache(struct vk_bundle *vk, VkPipelineCache *out_pipeline_cache) NULL, // &pipeline_cache); // if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkCreatePipelineCache failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkCreatePipelineCache failed: %s", vk_result_string(ret)); return ret; } @@ -73,8 +72,7 @@ create_pipeline_layout(struct vk_bundle *vk, NULL, // &pipeline_layout); // if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkCreatePipelineLayout failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkCreatePipelineLayout failed: %s", vk_result_string(ret)); return ret; } @@ -118,8 +116,7 @@ create_descriptor_pool(struct vk_bundle *vk, NULL, // &descriptor_pool); // if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkCreateRenderPass failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkCreateRenderPass failed: %s", vk_result_string(ret)); return ret; } @@ -136,11 +133,10 @@ create_descriptor_pool(struct vk_bundle *vk, */ static VkResult -create_mesh_descriptor_set_layout( - struct vk_bundle *vk, - uint32_t src_binding, - uint32_t ubo_binding, - VkDescriptorSetLayout *out_descriptor_set_layout) +create_mesh_descriptor_set_layout(struct vk_bundle *vk, + uint32_t src_binding, + uint32_t ubo_binding, + VkDescriptorSetLayout *out_descriptor_set_layout) { VkResult ret; @@ -171,8 +167,7 @@ create_mesh_descriptor_set_layout( NULL, // &descriptor_set_layout); // if (ret != VK_SUCCESS) { - VK_ERROR(vk, "vkCreateDescriptorSetLayout failed: %s", - vk_result_string(ret)); + VK_ERROR(vk, "vkCreateDescriptorSetLayout failed: %s", vk_result_string(ret)); return ret; } @@ -196,8 +191,7 @@ init_mesh_vertex_buffers(struct vk_bundle *vk, VkBufferUsageFlags vbo_usage_flags = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; VkBufferUsageFlags ibo_usage_flags = VK_BUFFER_USAGE_INDEX_BUFFER_BIT; VkMemoryPropertyFlags memory_property_flags = - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; // Distortion vbo and ibo sizes. VkDeviceSize vbo_size = stride * num_vertices; @@ -280,23 +274,20 @@ comp_resources_init(struct comp_compositor *c, struct comp_resources *r) * Mesh static. */ - C(create_descriptor_pool( - vk, // vk_bundle - 1, // num_uniform_per_desc - 1, // num_sampler_per_desc - 16 * 2, // num_descs - &r->mesh_descriptor_pool)); // out_descriptor_pool - - C(create_mesh_descriptor_set_layout( - vk, // vk_bundle - r->mesh.src_binding, // src_binding - r->mesh.ubo_binding, // ubo_binding - &r->mesh.descriptor_set_layout)); // out_mesh_descriptor_set_layout - - C(create_pipeline_layout( - vk, // vk_bundle - r->mesh.descriptor_set_layout, // descriptor_set_layout - &r->mesh.pipeline_layout)); // out_pipeline_layout + C(create_descriptor_pool(vk, // vk_bundle + 1, // num_uniform_per_desc + 1, // num_sampler_per_desc + 16 * 2, // num_descs + &r->mesh_descriptor_pool)); // out_descriptor_pool + + C(create_mesh_descriptor_set_layout(vk, // vk_bundle + r->mesh.src_binding, // src_binding + r->mesh.ubo_binding, // ubo_binding + &r->mesh.descriptor_set_layout)); // out_mesh_descriptor_set_layout + + C(create_pipeline_layout(vk, // vk_bundle + r->mesh.descriptor_set_layout, // descriptor_set_layout + &r->mesh.pipeline_layout)); // out_pipeline_layout if (!init_mesh_vertex_buffers(vk, // &r->mesh.vbo, // diff --git a/src/xrt/drivers/android/android_prober.c b/src/xrt/drivers/android/android_prober.c index 9bd628c94..3830ed3b2 100644 --- a/src/xrt/drivers/android/android_prober.c +++ b/src/xrt/drivers/android/android_prober.c @@ -63,10 +63,7 @@ android_prober_destroy(struct xrt_auto_prober *p) //! @public @memberof android_prober static struct xrt_device * -android_prober_autoprobe(struct xrt_auto_prober *xap, - cJSON *attached_data, - bool no_hmds, - struct xrt_prober *xp) +android_prober_autoprobe(struct xrt_auto_prober *xap, cJSON *attached_data, bool no_hmds, struct xrt_prober *xp) { struct android_device *dd = android_device_create(); return &dd->base; diff --git a/src/xrt/drivers/android/android_sensors.c b/src/xrt/drivers/android/android_sensors.c index 120215f79..bad38b5b7 100644 --- a/src/xrt/drivers/android/android_sensors.c +++ b/src/xrt/drivers/android/android_sensors.c @@ -54,9 +54,7 @@ android_sensor_callback(int fd, int events, void *data) accel.y = -event.acceleration.x; accel.z = event.acceleration.z; - ANDROID_TRACE(d, "accel %ld %.2f %.2f %.2f", - event.timestamp, accel.x, accel.y, - accel.z); + ANDROID_TRACE(d, "accel %ld %.2f %.2f %.2f", event.timestamp, accel.x, accel.y, accel.z); break; } case ASENSOR_TYPE_GYROSCOPE: { @@ -64,8 +62,7 @@ android_sensor_callback(int fd, int events, void *data) gyro.y = event.data[0]; gyro.z = event.data[2]; - ANDROID_TRACE(d, "gyro %ld %.2f %.2f %.2f", - event.timestamp, gyro.x, gyro.y, gyro.z); + ANDROID_TRACE(d, "gyro %ld %.2f %.2f %.2f", event.timestamp, gyro.x, gyro.y, gyro.z); // TODO: Make filter handle accelerometer struct xrt_vec3 null_accel; @@ -73,14 +70,12 @@ android_sensor_callback(int fd, int events, void *data) // Lock last and the fusion. os_mutex_lock(&d->lock); - m_imu_3dof_update(&d->fusion, event.timestamp, - &null_accel, &gyro); + m_imu_3dof_update(&d->fusion, event.timestamp, &null_accel, &gyro); // Now done. os_mutex_unlock(&d->lock); } - default: - ANDROID_TRACE(d, "Unhandled event type %d", event.type); + default: ANDROID_TRACE(d, "Unhandled event type %d", event.type); } } @@ -93,34 +88,27 @@ android_run_thread(void *ptr) struct android_device *d = (struct android_device *)ptr; #if __ANDROID_API__ >= 26 - d->sensor_manager = - ASensorManager_getInstanceForPackage(XRT_ANDROID_PACKAGE); + d->sensor_manager = ASensorManager_getInstanceForPackage(XRT_ANDROID_PACKAGE); #else d->sensor_manager = ASensorManager_getInstance(); #endif - d->accelerometer = ASensorManager_getDefaultSensor( - d->sensor_manager, ASENSOR_TYPE_ACCELEROMETER); - d->gyroscope = ASensorManager_getDefaultSensor(d->sensor_manager, - ASENSOR_TYPE_GYROSCOPE); + d->accelerometer = ASensorManager_getDefaultSensor(d->sensor_manager, ASENSOR_TYPE_ACCELEROMETER); + d->gyroscope = ASensorManager_getDefaultSensor(d->sensor_manager, ASENSOR_TYPE_GYROSCOPE); ALooper *looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS); - d->event_queue = ASensorManager_createEventQueue( - d->sensor_manager, looper, ALOOPER_POLL_CALLBACK, - android_sensor_callback, (void *)d); + d->event_queue = ASensorManager_createEventQueue(d->sensor_manager, looper, ALOOPER_POLL_CALLBACK, + android_sensor_callback, (void *)d); // Start sensors in case this was not done already. if (d->accelerometer != NULL) { - ASensorEventQueue_enableSensor(d->event_queue, - d->accelerometer); - ASensorEventQueue_setEventRate(d->event_queue, d->accelerometer, - POLL_RATE_USEC); + ASensorEventQueue_enableSensor(d->event_queue, d->accelerometer); + ASensorEventQueue_setEventRate(d->event_queue, d->accelerometer, POLL_RATE_USEC); } if (d->gyroscope != NULL) { ASensorEventQueue_enableSensor(d->event_queue, d->gyroscope); - ASensorEventQueue_setEventRate(d->event_queue, d->gyroscope, - POLL_RATE_USEC); + ASensorEventQueue_setEventRate(d->event_queue, d->gyroscope, POLL_RATE_USEC); } int ret = 0; @@ -176,9 +164,8 @@ android_device_get_tracked_pose(struct xrt_device *xdev, out_relation->pose.orientation = d->fusion.rot; //! @todo assuming that orientation is actually currently tracked. - out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + out_relation->relation_flags = (enum xrt_space_relation_flags)(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); } static void @@ -215,25 +202,19 @@ android_device_get_view_pose(struct xrt_device *xdev, */ static bool -android_device_compute_distortion(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result) +android_device_compute_distortion(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result) { struct android_device *d = android_device(xdev); - return u_compute_distortion_cardboard(&d->cardboard.values[view], u, v, - result); + return u_compute_distortion_cardboard(&d->cardboard.values[view], u, v, result); } struct android_device * android_device_create() { - enum u_device_alloc_flags flags = (enum u_device_alloc_flags)( - U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); - struct android_device *d = - U_DEVICE_ALLOCATE(struct android_device, flags, 1, 0); + enum u_device_alloc_flags flags = + (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); + struct android_device *d = U_DEVICE_ALLOCATE(struct android_device, flags, 1, 0); d->base.name = XRT_DEVICE_GENERIC_HMD; d->base.destroy = android_device_destroy; @@ -258,9 +239,8 @@ android_device_create() } struct xrt_android_display_metrics metrics; - if (!android_custom_surface_get_display_metrics( - android_globals_get_vm(), android_globals_get_activity(), - &metrics)) { + if (!android_custom_surface_get_display_metrics(android_globals_get_vm(), android_globals_get_activity(), + &metrics)) { U_LOG_E("Could not get Android display metrics."); /* Fallback to default values (Pixel 3) */ metrics.width_pixels = 2960; diff --git a/src/xrt/drivers/arduino/arduino_device.c b/src/xrt/drivers/arduino/arduino_device.c index dde400c67..125764a14 100644 --- a/src/xrt/drivers/arduino/arduino_device.c +++ b/src/xrt/drivers/arduino/arduino_device.c @@ -150,8 +150,7 @@ update_fusion(struct arduino_device *ad, time_duration_ns delta_ns) { struct xrt_vec3 accel, gyro; - m_imu_pre_filter_data(&ad->pre_filter, &sample->accel, &sample->gyro, - &accel, &gyro); + m_imu_pre_filter_data(&ad->pre_filter, &sample->accel, &sample->gyro, &accel, &gyro); ad->device_time += (uint64_t)sample->delta * 1000; @@ -160,32 +159,26 @@ update_fusion(struct arduino_device *ad, double delta_device_ms = (double)sample->delta / 1000.0; double delta_host_ms = (double)delta_ns / (1000.0 * 1000.0); ARDUINO_DEBUG(ad, "%+fms %+fms", delta_host_ms, delta_device_ms); - ARDUINO_DEBUG( - ad, "fusion sample %u (ax %d ay %d az %d) (gx %d gy %d gz %d)", - sample->time, sample->accel.x, sample->accel.y, sample->accel.z, - sample->gyro.x, sample->gyro.y, sample->gyro.z); + ARDUINO_DEBUG(ad, "fusion sample %u (ax %d ay %d az %d) (gx %d gy %d gz %d)", sample->time, sample->accel.x, + sample->accel.y, sample->accel.z, sample->gyro.x, sample->gyro.y, sample->gyro.z); ARDUINO_DEBUG(ad, " "); } static void -arduino_parse_input(struct arduino_device *ad, - void *data, - struct arduino_parsed_input *input) +arduino_parse_input(struct arduino_device *ad, void *data, struct arduino_parsed_input *input) { U_ZERO(input); unsigned char *b = (unsigned char *)data; - ARDUINO_TRACE( - ad, - "raw input: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x " - "%02x %02x %02x %02x %02x %02x %02x %02x %02x", - b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], - b[11], b[12], b[13], b[14], b[15], b[16], b[17], b[18], b[19]); + ARDUINO_TRACE(ad, + "raw input: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x " + "%02x %02x %02x %02x %02x %02x %02x %02x %02x", + b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], + b[15], b[16], b[17], b[18], b[19]); uint32_t time = b[5] | b[4] << 8 | b[3] << 16; input->sample.time = time; - input->sample.delta = - calc_delta_and_handle_rollover(time, ad->last_time); + input->sample.delta = calc_delta_and_handle_rollover(time, ad->last_time); ad->last_time = time; input->sample.accel.x = read_i16(b, 6); @@ -279,16 +272,13 @@ arduino_run_thread(void *ptr) */ static void -arduino_get_fusion_pose(struct arduino_device *ad, - enum xrt_input_name name, - struct xrt_space_relation *out_relation) +arduino_get_fusion_pose(struct arduino_device *ad, enum xrt_input_name name, struct xrt_space_relation *out_relation) { out_relation->pose.orientation = ad->fusion.rot; //! @todo assuming that orientation is actually currently tracked. - out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + out_relation->relation_flags = (enum xrt_space_relation_flags)(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); } static void @@ -383,10 +373,8 @@ static struct xrt_binding_profile binding_profiles[1] = { struct xrt_device * arduino_device_create(struct os_ble_device *ble) { - enum u_device_alloc_flags flags = - (enum u_device_alloc_flags)(U_DEVICE_ALLOC_TRACKING_NONE); - struct arduino_device *ad = - U_DEVICE_ALLOCATE(struct arduino_device, flags, 8, 0); + enum u_device_alloc_flags flags = (enum u_device_alloc_flags)(U_DEVICE_ALLOC_TRACKING_NONE); + struct arduino_device *ad = U_DEVICE_ALLOCATE(struct arduino_device, flags, 8, 0); ad->base.name = XRT_DEVICE_DAYDREAM; ad->base.destroy = arduino_device_destroy; @@ -411,8 +399,7 @@ arduino_device_create(struct os_ble_device *ble) float accel_ticks_to_float = (4.0 * MATH_GRAVITY_M_S2) / INT16_MAX; float gyro_ticks_to_float = (2000.0 * DEG_TO_RAD) / INT16_MAX; - m_imu_pre_filter_init(&ad->pre_filter, accel_ticks_to_float, - gyro_ticks_to_float); + m_imu_pre_filter_init(&ad->pre_filter, accel_ticks_to_float, gyro_ticks_to_float); m_imu_pre_filter_set_switch_x_and_y(&ad->pre_filter); #if 0 diff --git a/src/xrt/drivers/arduino/arduino_prober.c b/src/xrt/drivers/arduino/arduino_prober.c index 4b2fc6d30..158266544 100644 --- a/src/xrt/drivers/arduino/arduino_prober.c +++ b/src/xrt/drivers/arduino/arduino_prober.c @@ -67,10 +67,7 @@ arduino_prober_destroy(struct xrt_auto_prober *p) //! @public @memberof arduino_prober static struct xrt_device * -arduino_prober_autoprobe(struct xrt_auto_prober *xap, - cJSON *attached_data, - bool no_hmds, - struct xrt_prober *xp) +arduino_prober_autoprobe(struct xrt_auto_prober *xap, cJSON *attached_data, bool no_hmds, struct xrt_prober *xp) { struct arduino_prober *ap = arduino_prober(xap); if (!ap->enabled) { diff --git a/src/xrt/drivers/daydream/daydream_device.c b/src/xrt/drivers/daydream/daydream_device.c index eea38adac..0fc221cf6 100644 --- a/src/xrt/drivers/daydream/daydream_device.c +++ b/src/xrt/drivers/daydream/daydream_device.c @@ -67,15 +67,11 @@ daydream_device(struct xrt_device *xdev) } static void -daydream_update_input_click(struct daydream_device *daydream, - int index, - int64_t now, - uint32_t bit) +daydream_update_input_click(struct daydream_device *daydream, int index, int64_t now, uint32_t bit) { daydream->base.inputs[index].timestamp = now; - daydream->base.inputs[index].value.boolean = - (daydream->last.buttons & bit) != 0; + daydream->base.inputs[index].value.boolean = (daydream->last.buttons & bit) != 0; } @@ -93,16 +89,14 @@ update_fusion(struct daydream_device *dd, { struct xrt_vec3 accel, gyro; - m_imu_pre_filter_data(&dd->pre_filter, &sample->accel, &sample->gyro, - &accel, &gyro); + m_imu_pre_filter_data(&dd->pre_filter, &sample->accel, &sample->gyro, &accel, &gyro); DAYDREAM_DEBUG(dd, "fusion sample" " (mx %d my %d mz %d)" " (ax %d ay %d az %d)" " (gx %d gy %d gz %d)", - sample->mag.x, sample->mag.y, sample->mag.z, - sample->accel.x, sample->accel.y, sample->accel.z, + sample->mag.x, sample->mag.y, sample->mag.z, sample->accel.x, sample->accel.y, sample->accel.z, sample->gyro.x, sample->gyro.y, sample->gyro.z); DAYDREAM_DEBUG(dd, "fusion calibrated sample" @@ -115,18 +109,15 @@ update_fusion(struct daydream_device *dd, } static int -daydream_parse_input(struct daydream_device *daydream, - void *data, - struct daydream_parsed_input *input) +daydream_parse_input(struct daydream_device *daydream, void *data, struct daydream_parsed_input *input) { U_ZERO(input); unsigned char *b = (unsigned char *)data; - DAYDREAM_DEBUG( - daydream, - "raw input: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x " - "%02x %02x %02x %02x %02x %02x %02x %02x %02x", - b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], - b[11], b[12], b[13], b[14], b[15], b[16], b[17], b[18], b[19]); + DAYDREAM_DEBUG(daydream, + "raw input: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x " + "%02x %02x %02x %02x %02x %02x %02x %02x %02x", + b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], + b[15], b[16], b[17], b[18], b[19]); input->timestamp = get_bits(b, 0, 14); input->sample.mag.x = sign_extend_13(get_bits(b, 14, 13)); input->sample.mag.y = sign_extend_13(get_bits(b, 27, 13)); @@ -156,9 +147,7 @@ daydream_parse_input(struct daydream_device *daydream, * the thread has been told to shut down. */ static bool -daydream_read_one_packet(struct daydream_device *daydream, - uint8_t *buffer, - size_t size) +daydream_read_one_packet(struct daydream_device *daydream, uint8_t *buffer, size_t size) { os_thread_helper_lock(&daydream->oth); @@ -181,8 +170,7 @@ daydream_read_one_packet(struct daydream_device *daydream, continue; } if (ret < 0) { - DAYDREAM_ERROR(daydream, "Failed to read device '%i'!", - ret); + DAYDREAM_ERROR(daydream, "Failed to read device '%i'!", ret); return false; } return true; @@ -257,9 +245,8 @@ daydream_get_fusion_pose(struct daydream_device *daydream, out_relation->pose.orientation = daydream->fusion.rot; //! @todo assuming that orientation is actually currently tracked. - out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + out_relation->relation_flags = (enum xrt_space_relation_flags)(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); } static void @@ -366,10 +353,8 @@ static struct xrt_binding_profile binding_profiles[1] = { struct daydream_device * daydream_device_create(struct os_ble_device *ble) { - enum u_device_alloc_flags flags = - (enum u_device_alloc_flags)(U_DEVICE_ALLOC_TRACKING_NONE); - struct daydream_device *dd = - U_DEVICE_ALLOCATE(struct daydream_device, flags, 8, 0); + enum u_device_alloc_flags flags = (enum u_device_alloc_flags)(U_DEVICE_ALLOC_TRACKING_NONE); + struct daydream_device *dd = U_DEVICE_ALLOCATE(struct daydream_device, flags, 8, 0); dd->base.name = XRT_DEVICE_DAYDREAM; dd->base.destroy = daydream_device_destroy; @@ -390,8 +375,7 @@ daydream_device_create(struct os_ble_device *ble) float accel_ticks_to_float = MATH_GRAVITY_M_S2 / 520.0; float gyro_ticks_to_float = 1.0 / 120.0; - m_imu_pre_filter_init(&dd->pre_filter, accel_ticks_to_float, - gyro_ticks_to_float); + m_imu_pre_filter_init(&dd->pre_filter, accel_ticks_to_float, gyro_ticks_to_float); m_imu_3dof_init(&dd->fusion, M_IMU_3DOF_USE_GRAVITY_DUR_300MS); daydream_get_calibration(dd); diff --git a/src/xrt/drivers/daydream/daydream_prober.c b/src/xrt/drivers/daydream/daydream_prober.c index 2ca9654e5..7d65aa5f9 100644 --- a/src/xrt/drivers/daydream/daydream_prober.c +++ b/src/xrt/drivers/daydream/daydream_prober.c @@ -67,10 +67,7 @@ daydream_prober_destroy(struct xrt_auto_prober *p) //! @public @memberof daydream_prober static struct xrt_device * -daydream_prober_autoprobe(struct xrt_auto_prober *xap, - cJSON *attached_data, - bool no_hmds, - struct xrt_prober *xp) +daydream_prober_autoprobe(struct xrt_auto_prober *xap, cJSON *attached_data, bool no_hmds, struct xrt_prober *xp) { struct daydream_prober *pdaydream = daydream_prober(xap); if (!pdaydream->enabled) { @@ -101,8 +98,7 @@ daydream_prober_autoprobe(struct xrt_auto_prober *xap, struct xrt_auto_prober * daydream_create_auto_prober() { - struct daydream_prober *pdaydream = - U_TYPED_CALLOC(struct daydream_prober); + struct daydream_prober *pdaydream = U_TYPED_CALLOC(struct daydream_prober); pdaydream->base.name = "DayDream"; pdaydream->base.destroy = daydream_prober_destroy; pdaydream->base.lelo_dallas_autoprobe = daydream_prober_autoprobe; diff --git a/src/xrt/drivers/dummy/dummy_hmd.c b/src/xrt/drivers/dummy/dummy_hmd.c index cd592d80f..babe5bb68 100644 --- a/src/xrt/drivers/dummy/dummy_hmd.c +++ b/src/xrt/drivers/dummy/dummy_hmd.c @@ -114,10 +114,9 @@ dummy_hmd_get_tracked_pose(struct xrt_device *xdev, math_quat_normalize(&dh->pose.orientation); out_relation->pose = dh->pose; - out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + out_relation->relation_flags = (enum xrt_space_relation_flags)(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_POSITION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); } static void @@ -150,8 +149,8 @@ dummy_hmd_get_view_pose(struct xrt_device *xdev, struct xrt_device * dummy_hmd_create(void) { - enum u_device_alloc_flags flags = (enum u_device_alloc_flags)( - U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); + enum u_device_alloc_flags flags = + (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); struct dummy_hmd *dh = U_DEVICE_ALLOCATE(struct dummy_hmd, flags, 1, 0); dh->base.update_inputs = dummy_hmd_update_inputs; dh->base.get_tracked_pose = dummy_hmd_get_tracked_pose; diff --git a/src/xrt/drivers/dummy/dummy_prober.c b/src/xrt/drivers/dummy/dummy_prober.c index 14bc2211a..29eaf3880 100644 --- a/src/xrt/drivers/dummy/dummy_prober.c +++ b/src/xrt/drivers/dummy/dummy_prober.c @@ -43,10 +43,7 @@ dummy_prober_destroy(struct xrt_auto_prober *p) //! @public @memberof dummy_prober static struct xrt_device * -dummy_prober_autoprobe(struct xrt_auto_prober *xap, - cJSON *attached_data, - bool no_hmds, - struct xrt_prober *xp) +dummy_prober_autoprobe(struct xrt_auto_prober *xap, cJSON *attached_data, bool no_hmds, struct xrt_prober *xp) { struct dummy_prober *dp = dummy_prober(xap); (void)dp; diff --git a/src/xrt/drivers/hdk/hdk_device.cpp b/src/xrt/drivers/hdk/hdk_device.cpp index 2f93814de..90f3e6efb 100644 --- a/src/xrt/drivers/hdk/hdk_device.cpp +++ b/src/xrt/drivers/hdk/hdk_device.cpp @@ -70,8 +70,7 @@ static inline float fromFixedPoint(IntegerType v) { constexpr size_t SIGN_BIT = std::is_signed::value ? 1 : 0; - static_assert(INT_BITS + FRAC_BITS + SIGN_BIT == - BITS_PER_BYTE * sizeof(IntegerType), + static_assert(INT_BITS + FRAC_BITS + SIGN_BIT == BITS_PER_BYTE * sizeof(IntegerType), "INT_BITS and FRAC_BITS, plus 1 for a sign bit " "if applicable, must sum to the input " "integer width, but do not."); @@ -82,8 +81,7 @@ static inline uint16_t hdk_get_le_uint16(uint8_t *&bufPtr) { assert(bufPtr != nullptr); - uint16_t ret = static_cast(*bufPtr) | - (static_cast(*(bufPtr + 1)) << BITS_PER_BYTE); + uint16_t ret = static_cast(*bufPtr) | (static_cast(*(bufPtr + 1)) << BITS_PER_BYTE); bufPtr += 2; return ret; } @@ -163,8 +161,7 @@ hdk_device_update(struct hdk_device *hd) static constexpr int INT_BITS = 1; static constexpr int FRAC_BITS = 14; quat.x = fromFixedPoint(hdk_get_le_int16(buf)); - quat.z = - fromFixedPoint(hdk_get_le_int16(buf)) * -1; + quat.z = fromFixedPoint(hdk_get_le_int16(buf)) * -1; quat.y = fromFixedPoint(hdk_get_le_int16(buf)); quat.w = fromFixedPoint(hdk_get_le_int16(buf)); @@ -245,16 +242,14 @@ hdk_device_get_tracked_pose(struct xrt_device *xdev, out_relation->angular_velocity.y = hd->ang_vel_quat.y; out_relation->angular_velocity.z = hd->ang_vel_quat.z; - out_relation->relation_flags = xrt_space_relation_flags( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + out_relation->relation_flags = xrt_space_relation_flags(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); os_thread_helper_unlock(&hd->imu_thread); - HDK_TRACE(hd, "GET_TRACKED_POSE (%f, %f, %f, %f) ANG_VEL (%f, %f, %f)", - hd->quat.x, hd->quat.y, hd->quat.z, hd->quat.w, - hd->ang_vel_quat.x, hd->ang_vel_quat.y, hd->ang_vel_quat.z); + HDK_TRACE(hd, "GET_TRACKED_POSE (%f, %f, %f, %f) ANG_VEL (%f, %f, %f)", hd->quat.x, hd->quat.y, hd->quat.z, + hd->quat.w, hd->ang_vel_quat.x, hd->ang_vel_quat.y, hd->ang_vel_quat.z); } static void @@ -305,25 +300,20 @@ hdk_device_run_thread(void *ptr) #define HDK_DEBUG_INT(hd, name, val) HDK_DEBUG(hd, "\t%s = %u", name, val) -#define HDK_DEBUG_MM(hd, name, val) \ - HDK_DEBUG(hd, "\t%s = %i.%02imm", name, (int32_t)(val * 1000.f), \ - abs((int32_t)(val * 100000.f)) % 100) +#define HDK_DEBUG_MM(hd, name, val) \ + HDK_DEBUG(hd, "\t%s = %i.%02imm", name, (int32_t)(val * 1000.f), abs((int32_t)(val * 100000.f)) % 100) -#define HDK_DEBUG_ANGLE(hd, name, val) \ - HDK_DEBUG(hd, "\t%s = %f (%i)", name, val, \ - (int32_t)(val * (180 / M_PI))) +#define HDK_DEBUG_ANGLE(hd, name, val) HDK_DEBUG(hd, "\t%s = %f (%i)", name, val, (int32_t)(val * (180 / M_PI))) -#define HDK_DEBUG_MAT2X2(hd, name, rot) \ - HDK_DEBUG(hd, "\t%s = {%f, %f} {%f, %f}", name, rot.v[0], rot.v[1], \ - rot.v[2], rot.v[3]) +#define HDK_DEBUG_MAT2X2(hd, name, rot) \ + HDK_DEBUG(hd, "\t%s = {%f, %f} {%f, %f}", name, rot.v[0], rot.v[1], rot.v[2], rot.v[3]) struct hdk_device * hdk_device_create(struct os_hid_device *dev, enum HDK_VARIANT variant) { - enum u_device_alloc_flags flags = (enum u_device_alloc_flags)( - U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); - struct hdk_device *hd = - U_DEVICE_ALLOCATE(struct hdk_device, flags, 1, 0); + enum u_device_alloc_flags flags = + (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); + struct hdk_device *hd = U_DEVICE_ALLOCATE(struct hdk_device, flags, 1, 0); hd->base.hmd->blend_mode = XRT_BLEND_MODE_OPAQUE; hd->base.update_inputs = hdk_device_update_inputs; @@ -377,29 +367,23 @@ hdk_device_create(struct os_hid_device *dev, enum HDK_VARIANT variant) constexpr double DEGREES_TO_RADIANS = M_PI / 180.0; { /* right eye */ - math_compute_fovs(1.0, hCOP, hFOV * DEGREES_TO_RADIANS, 1, vCOP, - vFOV * DEGREES_TO_RADIANS, + math_compute_fovs(1.0, hCOP, hFOV * DEGREES_TO_RADIANS, 1, vCOP, vFOV * DEGREES_TO_RADIANS, &hd->base.hmd->views[1].fov); } { /* left eye - just mirroring right eye now */ - hd->base.hmd->views[0].fov.angle_up = - hd->base.hmd->views[1].fov.angle_up; - hd->base.hmd->views[0].fov.angle_down = - hd->base.hmd->views[1].fov.angle_down; - - hd->base.hmd->views[0].fov.angle_left = - -hd->base.hmd->views[1].fov.angle_right; - hd->base.hmd->views[0].fov.angle_right = - -hd->base.hmd->views[1].fov.angle_left; + hd->base.hmd->views[0].fov.angle_up = hd->base.hmd->views[1].fov.angle_up; + hd->base.hmd->views[0].fov.angle_down = hd->base.hmd->views[1].fov.angle_down; + + hd->base.hmd->views[0].fov.angle_left = -hd->base.hmd->views[1].fov.angle_right; + hd->base.hmd->views[0].fov.angle_right = -hd->base.hmd->views[1].fov.angle_left; } switch (variant) { case HDK_UNKNOWN: assert(!"unknown device"); break; case HDK_VARIANT_2: { - hd->base.hmd->screens[0].nominal_frame_interval_ns = - time_s_to_ns(1.0f / 90.0f); + hd->base.hmd->screens[0].nominal_frame_interval_ns = time_s_to_ns(1.0f / 90.0f); constexpr int panel_w = 1080; constexpr int panel_h = 1200; // Padding needed horizontally per side. @@ -455,8 +439,7 @@ hdk_device_create(struct os_hid_device *dev, enum HDK_VARIANT variant) // fallthrough intentional case HDK_VARIANT_1_2: { // 1080x1920 screen, with the top at the left. - hd->base.hmd->screens[0].nominal_frame_interval_ns = - time_s_to_ns(1.0f / 60.0f); + hd->base.hmd->screens[0].nominal_frame_interval_ns = time_s_to_ns(1.0f / 60.0f); constexpr int panel_w = 1080; constexpr int panel_h = 1920; @@ -503,8 +486,7 @@ hdk_device_create(struct os_hid_device *dev, enum HDK_VARIANT variant) // } if (hd->dev) { - int ret = os_thread_helper_start(&hd->imu_thread, - hdk_device_run_thread, hd); + int ret = os_thread_helper_start(&hd->imu_thread, hdk_device_run_thread, hd); if (ret != 0) { HDK_ERROR(hd, "Failed to start mainboard thread!"); hdk_device_destroy((struct xrt_device *)hd); diff --git a/src/xrt/drivers/hdk/hdk_prober.c b/src/xrt/drivers/hdk/hdk_prober.c index c97696c68..bb8942765 100644 --- a/src/xrt/drivers/hdk/hdk_prober.c +++ b/src/xrt/drivers/hdk/hdk_prober.c @@ -36,16 +36,14 @@ hdk_found(struct xrt_prober *xp, struct xrt_prober_device *dev = devices[index]; unsigned char buf[256] = {0}; - int result = xrt_prober_get_string_descriptor( - xp, dev, XRT_PROBER_STRING_PRODUCT, buf, sizeof(buf)); + int result = xrt_prober_get_string_descriptor(xp, dev, XRT_PROBER_STRING_PRODUCT, buf, sizeof(buf)); enum HDK_VARIANT variant = HDK_UNKNOWN; const char *name = NULL; if (0 == strncmp(HDK2_PRODUCT_STRING, (const char *)buf, sizeof(buf))) { variant = HDK_VARIANT_2; name = HDK2_PRODUCT_STRING; - } else if (0 == strncmp(HDK1_PRODUCT_STRING, (const char *)buf, - sizeof(buf))) { + } else if (0 == strncmp(HDK1_PRODUCT_STRING, (const char *)buf, sizeof(buf))) { variant = HDK_VARIANT_1_2; name = HDK12_PRODUCT_STRING; } else { @@ -54,8 +52,7 @@ hdk_found(struct xrt_prober *xp, name = HDK13_PRODUCT_STRING; } - U_LOG_I("%s - Found at least the tracker of some HDK (%s) -- opening\n", - __func__, name); + U_LOG_I("%s - Found at least the tracker of some HDK (%s) -- opening\n", __func__, name); struct os_hid_device *hid = NULL; // Interface 2 is the HID interface. diff --git a/src/xrt/drivers/ht/ht_driver.c b/src/xrt/drivers/ht/ht_driver.c index 7e617be2d..9df1a716f 100644 --- a/src/xrt/drivers/ht/ht_driver.c +++ b/src/xrt/drivers/ht/ht_driver.c @@ -73,18 +73,14 @@ ht_device_get_hand_tracking(struct xrt_device *xdev, - htd->tracker->get_tracked_joints(htd->tracker, name, at_timestamp_ns, - &htd->u_tracking[index].joints, + htd->tracker->get_tracked_joints(htd->tracker, name, at_timestamp_ns, &htd->u_tracking[index].joints, &htd->hand_relation[index]); htd->u_tracking[index].timestamp_ns = at_timestamp_ns; - struct xrt_pose identity = { - .orientation = {.x = 0, .y = 0, .z = 0, .w = 1}, - .position = {.x = 0, .y = 0, .z = 0}}; + struct xrt_pose identity = {.orientation = {.x = 0, .y = 0, .z = 0, .w = 1}, + .position = {.x = 0, .y = 0, .z = 0}}; - u_hand_joints_set_out_data(&htd->u_tracking[index], hand, - &htd->hand_relation[index], &identity, - out_value); + u_hand_joints_set_out_data(&htd->u_tracking[index], hand, &htd->hand_relation[index], &identity, out_value); } static void @@ -99,17 +95,14 @@ ht_device_destroy(struct xrt_device *xdev) } struct xrt_device * -ht_device_create(struct xrt_auto_prober *xap, - cJSON *attached_data, - struct xrt_prober *xp) +ht_device_create(struct xrt_auto_prober *xap, cJSON *attached_data, struct xrt_prober *xp) { enum u_device_alloc_flags flags = U_DEVICE_ALLOC_NO_FLAGS; //! @todo 2 hands hardcoded int num_hands = 2; - struct ht_device *htd = - U_DEVICE_ALLOCATE(struct ht_device, flags, num_hands, 0); + struct ht_device *htd = U_DEVICE_ALLOCATE(struct ht_device, flags, num_hands, 0); htd->base.tracking_origin = &htd->tracking_origin; @@ -125,26 +118,22 @@ ht_device_create(struct xrt_auto_prober *xap, htd->base.get_hand_tracking = ht_device_get_hand_tracking; htd->base.destroy = ht_device_destroy; - strncpy(htd->base.str, "Camera based Hand Tracker", - XRT_DEVICE_NAME_LEN); + strncpy(htd->base.str, "Camera based Hand Tracker", XRT_DEVICE_NAME_LEN); htd->base.inputs[0].name = XRT_INPUT_GENERIC_HAND_TRACKING_LEFT; htd->base.inputs[1].name = XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT; htd->base.name = XRT_DEVICE_HAND_TRACKER; - if (xp->tracking->create_tracked_hand(xp->tracking, &htd->base, - &htd->tracker) < 0) { + if (xp->tracking->create_tracked_hand(xp->tracking, &htd->base, &htd->tracker) < 0) { HT_ERROR(htd, "Failed to create hand tracker module"); return NULL; } - u_hand_joints_init_default_set(&htd->u_tracking[XRT_HAND_LEFT], - XRT_HAND_LEFT, - XRT_HAND_TRACKING_MODEL_CAMERA, 1.0); - u_hand_joints_init_default_set(&htd->u_tracking[XRT_HAND_RIGHT], - XRT_HAND_RIGHT, - XRT_HAND_TRACKING_MODEL_CAMERA, 1.0); + u_hand_joints_init_default_set(&htd->u_tracking[XRT_HAND_LEFT], XRT_HAND_LEFT, XRT_HAND_TRACKING_MODEL_CAMERA, + 1.0); + u_hand_joints_init_default_set(&htd->u_tracking[XRT_HAND_RIGHT], XRT_HAND_RIGHT, XRT_HAND_TRACKING_MODEL_CAMERA, + 1.0); u_var_add_root(htd, "Camera based Hand Tracker", true); u_var_add_ro_text(htd, htd->base.str, "Name"); diff --git a/src/xrt/drivers/ht/ht_prober.c b/src/xrt/drivers/ht/ht_prober.c index c62dde1e3..7165a1883 100644 --- a/src/xrt/drivers/ht/ht_prober.c +++ b/src/xrt/drivers/ht/ht_prober.c @@ -41,10 +41,7 @@ ht_prober_destroy(struct xrt_auto_prober *p) //! @public @memberof ht_prober static struct xrt_device * -ht_prober_autoprobe(struct xrt_auto_prober *xap, - cJSON *attached_data, - bool no_hmds, - struct xrt_prober *xp) +ht_prober_autoprobe(struct xrt_auto_prober *xap, cJSON *attached_data, bool no_hmds, struct xrt_prober *xp) { struct xrt_device *xdev = ht_device_create(xap, attached_data, xp); diff --git a/src/xrt/drivers/hydra/hydra_driver.c b/src/xrt/drivers/hydra/hydra_driver.c index c9f734e33..40d3d7b2d 100644 --- a/src/xrt/drivers/hydra/hydra_driver.c +++ b/src/xrt/drivers/hydra/hydra_driver.c @@ -79,25 +79,19 @@ enum hydra_button_bit static const uint8_t HYDRA_REPORT_START_MOTION[] = { 0x00, // first byte must be report type - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x06, 0x00}; + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00}; static const uint8_t HYDRA_REPORT_START_GAMEPAD[] = { 0x00, // first byte must be report type - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x05, 0x00}; + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00}; struct hydra_controller_state { @@ -223,8 +217,7 @@ hydra_system(struct xrt_tracking_origin *xtrack) * @relates hydra_sm */ static float -hydra_sm_seconds_since_transition(struct hydra_state_machine *hsm, - timepoint_ns now) +hydra_sm_seconds_since_transition(struct hydra_state_machine *hsm, timepoint_ns now) { if (hsm->transition_time == 0) { @@ -242,9 +235,7 @@ hydra_sm_seconds_since_transition(struct hydra_state_machine *hsm, * @relates hydra_sm */ static int -hydra_sm_transition(struct hydra_state_machine *hsm, - enum hydra_sm_state new_state, - timepoint_ns now) +hydra_sm_transition(struct hydra_state_machine *hsm, enum hydra_sm_state new_state, timepoint_ns now) { if (hsm->transition_time == 0) { hsm->transition_time = now; @@ -293,14 +284,10 @@ hydra_device_parse_controller(struct hydra_device *hd, uint8_t *buf) state->pose.position.y = -hydra_read_int16_le(&buf) * SCALE_MM_TO_METER; // the negatives are to fix handedness - state->pose.orientation.w = - hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; - state->pose.orientation.x = - hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; - state->pose.orientation.y = - -hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; - state->pose.orientation.z = - -hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; + state->pose.orientation.w = hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; + state->pose.orientation.x = hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; + state->pose.orientation.y = -hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; + state->pose.orientation.z = -hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; //! @todo the presence of this suggest we're not decoding the //! orientation right. @@ -308,10 +295,8 @@ hydra_device_parse_controller(struct hydra_device *hd, uint8_t *buf) state->buttons = hydra_read_uint8(&buf); - state->js.x = - hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; - state->js.y = - hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; + state->js.x = hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; + state->js.y = hydra_read_int16_le(&buf) * SCALE_INT16_TO_FLOAT_PLUSMINUS_1; state->trigger = hydra_read_uint8(&buf) * SCALE_UINT8_TO_FLOAT_0_TO_1; @@ -323,11 +308,9 @@ hydra_device_parse_controller(struct hydra_device *hd, uint8_t *buf) "buttons: %08x\n\t" "joystick: (%-1.2f, %-1.2f)\n\t" "trigger: %01.2f\n", - (int)hd->index, state->pose.position.x, - state->pose.position.y, state->pose.position.z, - state->pose.orientation.x, state->pose.orientation.y, - state->pose.orientation.z, state->pose.orientation.w, - state->buttons, state->js.x, state->js.y, state->trigger); + (int)hd->index, state->pose.position.x, state->pose.position.y, state->pose.position.z, + state->pose.orientation.x, state->pose.orientation.y, state->pose.orientation.z, + state->pose.orientation.w, state->buttons, state->js.x, state->js.y, state->trigger); } static int @@ -345,16 +328,14 @@ hydra_system_read_data_hid(struct hydra_system *hs, timepoint_ns now) return got_message ? 1 : 0; } if (ret != 52) { - U_LOG_IFL_E(hs->ll, "Unexpected data report of size %d", - ret); + U_LOG_IFL_E(hs->ll, "Unexpected data report of size %d", ret); return -1; } got_message = true; uint8_t new_counter = buffer[7]; bool missed = false; if (hs->report_counter != -1) { - uint8_t expected_counter = - ((hs->report_counter + 1) & 0xff); + uint8_t expected_counter = ((hs->report_counter + 1) & 0xff); missed = new_counter != expected_counter; } hs->report_counter = new_counter; @@ -393,15 +374,13 @@ hydra_system_enter_motion_control(struct hydra_system *hs, timepoint_ns now) "attempt %d", hs->motion_attempt_number); - os_hid_set_feature(hs->command_hid, HYDRA_REPORT_START_MOTION, - sizeof(HYDRA_REPORT_START_MOTION)); + os_hid_set_feature(hs->command_hid, HYDRA_REPORT_START_MOTION, sizeof(HYDRA_REPORT_START_MOTION)); // Doing a dummy get-feature now. uint8_t buf[91] = {0}; os_hid_get_feature(hs->command_hid, 0, buf, sizeof(buf)); - return hydra_sm_transition(&hs->sm, - HYDRA_SM_LISTENING_AFTER_SET_FEATURE, now); + return hydra_sm_transition(&hs->sm, HYDRA_SM_LISTENING_AFTER_SET_FEATURE, now); } /*! * Update the internal state of the Hydra driver. @@ -428,8 +407,7 @@ hydra_system_update(struct hydra_system *hs) switch (hs->sm.current_state) { case HYDRA_SM_LISTENING_AFTER_CONNECT: { - float state_duration_s = - hydra_sm_seconds_since_transition(&hs->sm, now); + float state_duration_s = hydra_sm_seconds_since_transition(&hs->sm, now); if (state_duration_s > 1.0f) { // only waiting 1 second for the initial report after // connect @@ -438,8 +416,7 @@ hydra_system_update(struct hydra_system *hs) } break; case HYDRA_SM_LISTENING_AFTER_SET_FEATURE: { - float state_duration_s = - hydra_sm_seconds_since_transition(&hs->sm, now); + float state_duration_s = hydra_sm_seconds_since_transition(&hs->sm, now); if (state_duration_s > 5.0f) { // giving each motion control attempt 5 seconds to work. hydra_system_enter_motion_control(hs, now); @@ -453,10 +430,7 @@ hydra_system_update(struct hydra_system *hs) } static void -hydra_device_update_input_click(struct hydra_device *hd, - timepoint_ns now, - int index, - uint32_t bit) +hydra_device_update_input_click(struct hydra_device *hd, timepoint_ns now, int index, uint32_t bit) { assert(hd); hd->base.inputs[index].timestamp = now; @@ -481,22 +455,14 @@ hydra_device_update_inputs(struct xrt_device *xdev) timepoint_ns now = hs->report_time; hd->input_time = now; - hydra_device_update_input_click(hd, now, HYDRA_INDEX_1_CLICK, - HYDRA_BUTTON_BIT_1); - hydra_device_update_input_click(hd, now, HYDRA_INDEX_2_CLICK, - HYDRA_BUTTON_BIT_2); - hydra_device_update_input_click(hd, now, HYDRA_INDEX_3_CLICK, - HYDRA_BUTTON_BIT_3); - hydra_device_update_input_click(hd, now, HYDRA_INDEX_4_CLICK, - HYDRA_BUTTON_BIT_4); - - hydra_device_update_input_click( - hd, now, HYDRA_INDEX_MIDDLE_CLICK, HYDRA_BUTTON_BIT_MIDDLE); - hydra_device_update_input_click( - hd, now, HYDRA_INDEX_BUMPER_CLICK, HYDRA_BUTTON_BIT_BUMPER); - hydra_device_update_input_click(hd, now, - HYDRA_INDEX_JOYSTICK_CLICK, - HYDRA_INDEX_JOYSTICK_CLICK); + hydra_device_update_input_click(hd, now, HYDRA_INDEX_1_CLICK, HYDRA_BUTTON_BIT_1); + hydra_device_update_input_click(hd, now, HYDRA_INDEX_2_CLICK, HYDRA_BUTTON_BIT_2); + hydra_device_update_input_click(hd, now, HYDRA_INDEX_3_CLICK, HYDRA_BUTTON_BIT_3); + hydra_device_update_input_click(hd, now, HYDRA_INDEX_4_CLICK, HYDRA_BUTTON_BIT_4); + + hydra_device_update_input_click(hd, now, HYDRA_INDEX_MIDDLE_CLICK, HYDRA_BUTTON_BIT_MIDDLE); + hydra_device_update_input_click(hd, now, HYDRA_INDEX_BUMPER_CLICK, HYDRA_BUTTON_BIT_BUMPER); + hydra_device_update_input_click(hd, now, HYDRA_INDEX_JOYSTICK_CLICK, HYDRA_INDEX_JOYSTICK_CLICK); struct xrt_input *inputs = hd->base.inputs; struct hydra_controller_state *state = &(hd->state); @@ -530,10 +496,8 @@ hydra_device_get_tracked_pose(struct xrt_device *xdev, //! @todo how do we report this is not (necessarily) the same base space //! as the HMD? out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT | - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + XRT_SPACE_RELATION_POSITION_VALID_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT | + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); // struct xrt_vec3 pos = out_relation->pose.position; // struct xrt_quat quat = out_relation->pose.orientation; // HYDRA_SPEW(hd, "GET_TRACKED_POSE (%f, %f, %f) (%f, %f, %f, %f) ", @@ -559,17 +523,14 @@ hydra_system_remove_child(struct hydra_system *hs, struct hydra_device *hd) if (hs->refs == 0) { // No more children, destroy system. - if (hs->data_hid != NULL && hs->command_hid != NULL && - hs->sm.current_state == HYDRA_SM_REPORTING && + if (hs->data_hid != NULL && hs->command_hid != NULL && hs->sm.current_state == HYDRA_SM_REPORTING && hs->was_in_gamepad_mode) { - U_LOG_IFL_D( - hs->ll, - "hydra: Sending command to re-enter gamepad mode " - "and pausing while it takes effect."); + U_LOG_IFL_D(hs->ll, + "hydra: Sending command to re-enter gamepad mode " + "and pausing while it takes effect."); - os_hid_set_feature(hs->command_hid, - HYDRA_REPORT_START_GAMEPAD, + os_hid_set_feature(hs->command_hid, HYDRA_REPORT_START_GAMEPAD, sizeof(HYDRA_REPORT_START_GAMEPAD)); os_nanosleep(2 * 1000 * 1000 * 1000); } @@ -601,10 +562,9 @@ hydra_device_destroy(struct xrt_device *xdev) * Prober functions. * */ -#define SET_INPUT(NAME) \ - do { \ - (hd->base.inputs[HYDRA_INDEX_##NAME].name = \ - XRT_INPUT_HYDRA_##NAME); \ +#define SET_INPUT(NAME) \ + do { \ + (hd->base.inputs[HYDRA_INDEX_##NAME].name = XRT_INPUT_HYDRA_##NAME); \ } while (0) int @@ -633,8 +593,7 @@ hydra_found(struct xrt_prober *xp, // Create the system struct hydra_system *hs = U_TYPED_CALLOC(struct hydra_system); hs->base.type = XRT_TRACKING_TYPE_HYDRA; - snprintf(hs->base.name, XRT_TRACKING_NAME_LEN, "%s", - "Razer Hydra magnetic tracking"); + snprintf(hs->base.name, XRT_TRACKING_NAME_LEN, "%s", "Razer Hydra magnetic tracking"); // Dummy transform from local space to base. hs->base.offset.position.y = 1.0f; hs->base.offset.position.z = -0.25f; @@ -665,8 +624,7 @@ hydra_found(struct xrt_prober *xp, hd->base.get_tracked_pose = hydra_device_get_tracked_pose; // hs->base.set_output = hydra_device_set_output; hd->base.name = XRT_DEVICE_HYDRA; - snprintf(hd->base.str, XRT_DEVICE_NAME_LEN, "%s %i", - "Razer Hydra Controller", (int)(i + 1)); + snprintf(hd->base.str, XRT_DEVICE_NAME_LEN, "%s %i", "Razer Hydra Controller", (int)(i + 1)); SET_INPUT(1_CLICK); SET_INPUT(2_CLICK); SET_INPUT(3_CLICK); diff --git a/src/xrt/drivers/illixr/illixr_component.cpp b/src/xrt/drivers/illixr/illixr_component.cpp index 9e4af3be2..7b412c585 100644 --- a/src/xrt/drivers/illixr/illixr_component.cpp +++ b/src/xrt/drivers/illixr/illixr_component.cpp @@ -24,21 +24,18 @@ class illixr_plugin : public plugin { public: illixr_plugin(std::string name_, phonebook *pb_) - : plugin{name_, pb_}, sb{pb->lookup_impl()}, - sb_pose{pb->lookup_impl()}, - sb_eyebuffer{sb->publish("eyebuffer")}, - sb_vsync_estimate{ - sb->subscribe_latest("vsync_estimate")} + : plugin{name_, pb_}, sb{pb->lookup_impl()}, sb_pose{pb->lookup_impl()}, + sb_eyebuffer{sb->publish("eyebuffer")}, sb_vsync_estimate{sb->subscribe_latest( + "vsync_estimate")} {} const std::shared_ptr sb; const std::shared_ptr sb_pose; const std::unique_ptr> sb_eyebuffer; const std::unique_ptr> sb_vsync_estimate; - fast_pose_type prev_pose; /* stores a copy of pose each time - illixr_read_pose() is called */ - std::chrono::time_point - sample_time; /* when prev_pose was stored */ + fast_pose_type prev_pose; /* stores a copy of pose each time + illixr_read_pose() is called */ + std::chrono::time_point sample_time; /* when prev_pose was stored */ }; static illixr_plugin *illixr_plugin_obj = nullptr; @@ -54,16 +51,13 @@ illixr_monado_create_plugin(phonebook *pb) extern "C" struct xrt_pose illixr_read_pose() { - assert(illixr_plugin_obj && - "illixr_plugin_obj must be initialized first."); + assert(illixr_plugin_obj && "illixr_plugin_obj must be initialized first."); if (!illixr_plugin_obj->sb_pose->fast_pose_reliable()) { - std::cerr << "Pose not reliable yet; returning best guess" - << std::endl; + std::cerr << "Pose not reliable yet; returning best guess" << std::endl; } struct xrt_pose ret; - const fast_pose_type fast_pose = - illixr_plugin_obj->sb_pose->get_fast_pose(); + const fast_pose_type fast_pose = illixr_plugin_obj->sb_pose->get_fast_pose(); const pose_type pose = fast_pose.pose; // record when the pose was read for use in write_frame diff --git a/src/xrt/drivers/illixr/illixr_device.cpp b/src/xrt/drivers/illixr/illixr_device.cpp index 5b0c478c9..81b22f8ac 100644 --- a/src/xrt/drivers/illixr/illixr_device.cpp +++ b/src/xrt/drivers/illixr/illixr_device.cpp @@ -68,29 +68,29 @@ illixr_hmd(struct xrt_device *xdev) DEBUG_GET_ONCE_BOOL_OPTION(illixr_spew, "ILLIXR_PRINT_SPEW", false) DEBUG_GET_ONCE_BOOL_OPTION(illixr_debug, "ILLIXR_PRINT_DEBUG", false) -#define DH_SPEW(dh, ...) \ - do { \ - if (dh->print_spew) { \ - fprintf(stderr, "%s - ", __func__); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n"); \ - } \ +#define DH_SPEW(dh, ...) \ + do { \ + if (dh->print_spew) { \ + fprintf(stderr, "%s - ", __func__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ + } \ } while (false) -#define DH_DEBUG(dh, ...) \ - do { \ - if (dh->print_debug) { \ - fprintf(stderr, "%s - ", __func__); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n"); \ - } \ +#define DH_DEBUG(dh, ...) \ + do { \ + if (dh->print_debug) { \ + fprintf(stderr, "%s - ", __func__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ + } \ } while (false) -#define DH_ERROR(dh, ...) \ - do { \ - fprintf(stderr, "%s - ", __func__); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n"); \ +#define DH_ERROR(dh, ...) \ + do { \ + fprintf(stderr, "%s - ", __func__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ } while (false) static void @@ -126,10 +126,8 @@ illixr_hmd_get_tracked_pose(struct xrt_device *xdev, out_relation->pose = illixr_read_pose(); out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT); + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | + XRT_SPACE_RELATION_POSITION_VALID_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT); } static void @@ -158,13 +156,10 @@ split(const std::string &s, char delimiter) static int illixr_rt_launch(struct illixr_hmd *dh, const char *path, const char *comp) { - dh->runtime_lib = new ILLIXR::dynamic_lib{ - ILLIXR::dynamic_lib::create(std::string{path})}; - dh->runtime = - dh->runtime_lib->get("runtime_factory")(); + dh->runtime_lib = new ILLIXR::dynamic_lib{ILLIXR::dynamic_lib::create(std::string{path})}; + dh->runtime = dh->runtime_lib->get("runtime_factory")(); dh->runtime->load_so(split(std::string{comp}, ':')); - dh->runtime->load_plugin_factory( - (ILLIXR::plugin_factory)illixr_monado_create_plugin); + dh->runtime->load_plugin_factory((ILLIXR::plugin_factory)illixr_monado_create_plugin); return 0; } @@ -173,8 +168,8 @@ extern "C" struct xrt_device * illixr_hmd_create(const char *path_in, const char *comp_in) { struct illixr_hmd *dh; - enum u_device_alloc_flags flags = (enum u_device_alloc_flags)( - U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); + enum u_device_alloc_flags flags = + (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); dh = U_DEVICE_ALLOCATE(struct illixr_hmd, flags, 1, 0); dh->base.update_inputs = illixr_hmd_update_inputs; dh->base.get_tracked_pose = illixr_hmd_get_tracked_pose; diff --git a/src/xrt/drivers/illixr/illixr_prober.c b/src/xrt/drivers/illixr/illixr_prober.c index 3ef2a00bf..5dde4b93e 100644 --- a/src/xrt/drivers/illixr/illixr_prober.c +++ b/src/xrt/drivers/illixr/illixr_prober.c @@ -34,10 +34,7 @@ illixr_prober_destroy(struct xrt_auto_prober *p) } static struct xrt_device * -illixr_prober_autoprobe(struct xrt_auto_prober *xap, - cJSON *attached_data, - bool no_hmds, - struct xrt_prober *xp) +illixr_prober_autoprobe(struct xrt_auto_prober *xap, cJSON *attached_data, bool no_hmds, struct xrt_prober *xp) { struct illixr_prober *dp = illixr_prober(xap); (void)dp; diff --git a/src/xrt/drivers/north_star/distortion/deformation_northstar.cpp b/src/xrt/drivers/north_star/distortion/deformation_northstar.cpp index 0e918c623..e816eedf9 100644 --- a/src/xrt/drivers/north_star/distortion/deformation_northstar.cpp +++ b/src/xrt/drivers/north_star/distortion/deformation_northstar.cpp @@ -94,14 +94,11 @@ OpticalSystem::RegenerateMesh() // walk all the requested stored UVs and regeneate the response values // you probably should have updated the eye position before doing this // :-D - for (outerIter = m_requestedUVs.begin(); - outerIter != m_requestedUVs.end(); outerIter++) { - for (innerIter = outerIter->second.begin(); - innerIter != outerIter->second.end(); innerIter++) { - Vector2 result = SolveDisplayUVToRenderUV( - Vector2(outerIter->first, innerIter->first), - Vector2(innerIter->second.x, innerIter->second.y), - m_iniSolverIters); + for (outerIter = m_requestedUVs.begin(); outerIter != m_requestedUVs.end(); outerIter++) { + for (innerIter = outerIter->second.begin(); innerIter != outerIter->second.end(); innerIter++) { + Vector2 result = SolveDisplayUVToRenderUV(Vector2(outerIter->first, innerIter->first), + Vector2(innerIter->second.x, innerIter->second.y), + m_iniSolverIters); innerIter->second.x = result.x; innerIter->second.y = result.y; } @@ -121,49 +118,34 @@ Vector2 OpticalSystem::RenderUVToDisplayUV(const Vector3 &inputUV) { - Vector3 sphereSpaceRayOrigin = - worldToSphereSpace.MultiplyPoint(eyePosition); + Vector3 sphereSpaceRayOrigin = worldToSphereSpace.MultiplyPoint(eyePosition); Vector3 sphereSpaceRayDirection = - (worldToSphereSpace.MultiplyPoint(eyePosition + inputUV) - - sphereSpaceRayOrigin); - sphereSpaceRayDirection = - sphereSpaceRayDirection / sphereSpaceRayDirection.Magnitude(); + (worldToSphereSpace.MultiplyPoint(eyePosition + inputUV) - sphereSpaceRayOrigin); + sphereSpaceRayDirection = sphereSpaceRayDirection / sphereSpaceRayDirection.Magnitude(); float intersectionTime = - intersectLineSphere(sphereSpaceRayOrigin, sphereSpaceRayDirection, - Vector3::Zero(), 0.5f * 0.5f, false); + intersectLineSphere(sphereSpaceRayOrigin, sphereSpaceRayDirection, Vector3::Zero(), 0.5f * 0.5f, false); if (intersectionTime < 0.f) { // m_logger->DriverLog("No line->ellipsoid intersection. %g %g", // inputUV.x, inputUV.y); return Vector2::zero(); } - Vector3 sphereSpaceIntersection = - sphereSpaceRayOrigin + (sphereSpaceRayDirection * intersectionTime); + Vector3 sphereSpaceIntersection = sphereSpaceRayOrigin + (sphereSpaceRayDirection * intersectionTime); // Ellipsoid Normals - Vector3 sphereSpaceNormal = - (Vector3::Zero() - sphereSpaceIntersection) / - sphereSpaceIntersection.Magnitude(); - sphereSpaceNormal.x = - sphereSpaceNormal.x / powf(ellipseMinorAxis / 2.f, 2.f); - sphereSpaceNormal.y = - sphereSpaceNormal.y / powf(ellipseMinorAxis / 2.f, 2.f); - sphereSpaceNormal.z = - sphereSpaceNormal.z / powf(ellipseMajorAxis / 2.f, 2.f); + Vector3 sphereSpaceNormal = (Vector3::Zero() - sphereSpaceIntersection) / sphereSpaceIntersection.Magnitude(); + sphereSpaceNormal.x = sphereSpaceNormal.x / powf(ellipseMinorAxis / 2.f, 2.f); + sphereSpaceNormal.y = sphereSpaceNormal.y / powf(ellipseMinorAxis / 2.f, 2.f); + sphereSpaceNormal.z = sphereSpaceNormal.z / powf(ellipseMajorAxis / 2.f, 2.f); sphereSpaceNormal = sphereSpaceNormal / sphereSpaceNormal.Magnitude(); - Vector3 worldSpaceIntersection = - sphereToWorldSpace.MultiplyPoint(sphereSpaceIntersection); - Vector3 worldSpaceNormal = - sphereToWorldSpace.MultiplyVector(sphereSpaceNormal); + Vector3 worldSpaceIntersection = sphereToWorldSpace.MultiplyPoint(sphereSpaceIntersection); + Vector3 worldSpaceNormal = sphereToWorldSpace.MultiplyVector(sphereSpaceNormal); worldSpaceNormal = worldSpaceNormal / worldSpaceNormal.Magnitude(); - Ray firstBounce(worldSpaceIntersection, - Vector3::Reflect(inputUV, worldSpaceNormal)); - intersectionTime = - intersectPlane(screenForward, screenPosition, firstBounce.m_Origin, - firstBounce.m_Direction); + Ray firstBounce(worldSpaceIntersection, Vector3::Reflect(inputUV, worldSpaceNormal)); + intersectionTime = intersectPlane(screenForward, screenPosition, firstBounce.m_Origin, firstBounce.m_Direction); if (intersectionTime < 0.f) { // m_logger->DriverLog("No bounce->screen intersection. %g %g", @@ -172,8 +154,7 @@ OpticalSystem::RenderUVToDisplayUV(const Vector3 &inputUV) } Vector3 planeIntersection = firstBounce.GetPoint(intersectionTime); - Vector3 ScreenUVZ = - worldToScreenSpace.MultiplyPoint3x4(planeIntersection); + Vector3 ScreenUVZ = worldToScreenSpace.MultiplyPoint3x4(planeIntersection); Vector2 ScreenUV; ScreenUV.x = ScreenUVZ.x; @@ -188,9 +169,7 @@ OpticalSystem::RenderUVToDisplayUV(const Vector3 &inputUV) } Vector2 -OpticalSystem::SolveDisplayUVToRenderUV(const Vector2 &inputUV, - Vector2 const &initialGuess, - int iterations) +OpticalSystem::SolveDisplayUVToRenderUV(const Vector2 &inputUV, Vector2 const &initialGuess, int iterations) { static const float epsilon = 0.0001f; @@ -207,15 +186,9 @@ OpticalSystem::SolveDisplayUVToRenderUV(const Vector2 &inputUV, // the uvs if we have a list of them curDisplayUV = RenderUVToDisplayUV(curCameraUV); Vector2 displayUVGradX = - (RenderUVToDisplayUV(curCameraUV + - (Vector2(1, 0) * epsilon)) - - curDisplayUV) / - epsilon; + (RenderUVToDisplayUV(curCameraUV + (Vector2(1, 0) * epsilon)) - curDisplayUV) / epsilon; Vector2 displayUVGradY = - (RenderUVToDisplayUV(curCameraUV + - (Vector2(0, 1) * epsilon)) - - curDisplayUV) / - epsilon; + (RenderUVToDisplayUV(curCameraUV + (Vector2(0, 1) * epsilon)) - curDisplayUV) / epsilon; Vector2 error = curDisplayUV - inputUV; Vector2 step = Vector2::zero(); @@ -247,14 +220,10 @@ OpticalSystem::DisplayUVToRenderUVPreviousSeed(Vector2 inputUV) // if the outer value is not there we know the inner is not // so we just slam both in and call it a day std::map inner; - curDisplayUV = SolveDisplayUVToRenderUV( - inputUV, Vector2(0.5f, 0.5f), m_iniSolverIters); - - inner.insert( - std::pair(inputUV.y, curDisplayUV)); - m_requestedUVs.insert( - std::pair>(inputUV.x, - inner)); + curDisplayUV = SolveDisplayUVToRenderUV(inputUV, Vector2(0.5f, 0.5f), m_iniSolverIters); + + inner.insert(std::pair(inputUV.y, curDisplayUV)); + m_requestedUVs.insert(std::pair>(inputUV.x, inner)); // Logger->DriverLog("NorthStar Generated UV %g %g ", // inputUV.x, inputUV.y); @@ -266,11 +235,9 @@ OpticalSystem::DisplayUVToRenderUVPreviousSeed(Vector2 inputUV) // we assume there is no reason to ask for the same // value so no need to check if it exists already so // just add it. - curDisplayUV = SolveDisplayUVToRenderUV( - inputUV, Vector2(0.5f, 0.5f), m_iniSolverIters); + curDisplayUV = SolveDisplayUVToRenderUV(inputUV, Vector2(0.5f, 0.5f), m_iniSolverIters); - outerIter->second.insert( - std::pair(inputUV.y, curDisplayUV)); + outerIter->second.insert(std::pair(inputUV.y, curDisplayUV)); // Logger->DriverLog("NorthStar Generated UV %g %g ", // outerIter->first, innerIter->first); } else { @@ -281,9 +248,7 @@ OpticalSystem::DisplayUVToRenderUVPreviousSeed(Vector2 inputUV) // curDisplayUV.y = innerIter->second.y; curDisplayUV = SolveDisplayUVToRenderUV( - inputUV, - Vector2(innerIter->second.x, innerIter->second.y), - m_optSolverIters); + inputUV, Vector2(innerIter->second.x, innerIter->second.y), m_optSolverIters); // Logger->DriverLog("NorthStar Found UV %g %g ", // outerIter->first, innerIter->first); @@ -304,9 +269,7 @@ ns_create_optical_system(struct ns_v1_eye *eye) } extern "C" void -ns_display_uv_to_render_uv(struct ns_uv in, - struct ns_uv *out, - struct ns_v1_eye *eye) +ns_display_uv_to_render_uv(struct ns_uv in, struct ns_uv *out, struct ns_v1_eye *eye) { OpticalSystem *opticalSystem = (OpticalSystem *)eye->optical_system; Vector2 inUV = Vector2(in.u, 1.f - in.v); diff --git a/src/xrt/drivers/north_star/distortion/deformation_northstar.h b/src/xrt/drivers/north_star/distortion/deformation_northstar.h index 77db03bcd..dd646b3fd 100644 --- a/src/xrt/drivers/north_star/distortion/deformation_northstar.h +++ b/src/xrt/drivers/north_star/distortion/deformation_northstar.h @@ -32,9 +32,7 @@ public: RenderUVToDisplayUV(const Vector2 &inputUV); Vector2 - SolveDisplayUVToRenderUV(const Vector2 &inputUV, - Vector2 const &initialGuess, - int iterations); + SolveDisplayUVToRenderUV(const Vector2 &inputUV, Vector2 const &initialGuess, int iterations); Vector2 DisplayUVToRenderUVPreviousSeed(Vector2 inputUV); @@ -66,29 +64,23 @@ public: void UpdateClipToWorld(Matrix4x4 eyeRotationMatrix) { - Matrix4x4 eyeToWorld = - Matrix4x4::Translate(eyePosition) * eyeRotationMatrix; + Matrix4x4 eyeToWorld = Matrix4x4::Translate(eyePosition) * eyeRotationMatrix; eyeToWorld.m02 *= -1; eyeToWorld.m12 *= -1; eyeToWorld.m22 *= -1; - clipToWorld = - eyeToWorld * cameraProjection.ComposeProjection().Inverse(); + clipToWorld = eyeToWorld * cameraProjection.ComposeProjection().Inverse(); } Vector3 eyePosition; inline void - ViewportPointToRayDirection(Vector2 UV, - Vector3 cameraPosition, - Matrix4x4 clipToWorld, - Vector3 &out) + ViewportPointToRayDirection(Vector2 UV, Vector3 cameraPosition, Matrix4x4 clipToWorld, Vector3 &out) { Vector3 tmp; tmp.x = UV.x - 0.5f; tmp.y = UV.y - 0.5f; tmp.z = 0.f; - Vector3 dir = - clipToWorld.MultiplyPoint(tmp * 2.f) - cameraPosition; + Vector3 dir = clipToWorld.MultiplyPoint(tmp * 2.f) - cameraPosition; float mag = dir.Magnitude(); out = dir / mag; @@ -122,19 +114,13 @@ Project(Vector3 v1, Vector3 v2) } inline float -intersectLineSphere(Vector3 Origin, - Vector3 Direction, - Vector3 spherePos, - float SphereRadiusSqrd, - bool frontSide = true) +intersectLineSphere(Vector3 Origin, Vector3 Direction, Vector3 spherePos, float SphereRadiusSqrd, bool frontSide = true) { Vector3 L = spherePos - Origin; Vector3 offsetFromSphereCenterToRay = Project(L, Direction) - L; return (offsetFromSphereCenterToRay.sqrMagnitude() <= SphereRadiusSqrd) - ? Vector3::Dot(L, Direction) - - (sqrt(SphereRadiusSqrd - - offsetFromSphereCenterToRay.sqrMagnitude()) * - (frontSide ? 1.f : -1.f)) + ? Vector3::Dot(L, Direction) - (sqrt(SphereRadiusSqrd - offsetFromSphereCenterToRay.sqrMagnitude()) * + (frontSide ? 1.f : -1.f)) : -1.f; } diff --git a/src/xrt/drivers/north_star/distortion/utility_northstar.h b/src/xrt/drivers/north_star/distortion/utility_northstar.h index 4cbb34813..d43da2bfa 100644 --- a/src/xrt/drivers/north_star/distortion/utility_northstar.h +++ b/src/xrt/drivers/north_star/distortion/utility_northstar.h @@ -146,8 +146,7 @@ public: inline float static Dot(Vector3 const &lhs, Vector3 const &rhs) { - float result = - (lhs.x * rhs.x) + (lhs.y * rhs.y) + (lhs.z * rhs.z); + float result = (lhs.x * rhs.x) + (lhs.y * rhs.y) + (lhs.z * rhs.z); return result; } @@ -199,8 +198,7 @@ public: inline static Vector3 Reflect(Vector3 inDirection, Vector3 inNormal) { - return inNormal * -2.F * Dot(inNormal, inDirection) + - inDirection; + return inNormal * -2.F * Dot(inNormal, inDirection) + inDirection; } inline void @@ -484,53 +482,35 @@ public: const float c = fromDir.Dot(toDir); const float k = 1.0f / (1.0f + c); - return Matrix4x4(v.x * v.x * k + c, v.y * v.x * k - v.z, - v.z * v.x * k + v.y, 0.f, v.x * v.y * k + v.z, - v.y * v.y * k + c, v.z * v.y * k - v.x, 0.f, - v.x * v.z * k - v.y, v.y * v.z * k + v.x, + return Matrix4x4(v.x * v.x * k + c, v.y * v.x * k - v.z, v.z * v.x * k + v.y, 0.f, v.x * v.y * k + v.z, + v.y * v.y * k + c, v.z * v.y * k - v.x, 0.f, v.x * v.z * k - v.y, v.y * v.z * k + v.x, v.z * v.z * k + c, 0.f, 0.f, 0.f, 0.f, 1.f); } inline Matrix4x4 operator*(const Matrix4x4 &_in) { Matrix4x4 ret; - ret.m00 = (m00 * _in.m00) + (m01 * _in.m10) + (m02 * _in.m20) + - (m03 * _in.m30); - ret.m01 = (m00 * _in.m01) + (m01 * _in.m11) + (m02 * _in.m21) + - (m03 * _in.m31); - ret.m02 = (m00 * _in.m02) + (m01 * _in.m12) + (m02 * _in.m22) + - (m03 * _in.m32); - ret.m03 = (m00 * _in.m03) + (m01 * _in.m13) + (m02 * _in.m23) + - (m03 * _in.m33); - - - ret.m10 = (m10 * _in.m00) + (m11 * _in.m10) + (m12 * _in.m20) + - (m13 * _in.m30); - ret.m11 = (m10 * _in.m01) + (m11 * _in.m11) + (m12 * _in.m21) + - (m13 * _in.m31); - ret.m12 = (m10 * _in.m02) + (m11 * _in.m12) + (m12 * _in.m22) + - (m13 * _in.m32); - ret.m13 = (m10 * _in.m03) + (m11 * _in.m13) + (m12 * _in.m23) + - (m13 * _in.m33); - - - ret.m20 = (m20 * _in.m00) + (m21 * _in.m10) + (m22 * _in.m20) + - (m23 * _in.m30); - ret.m21 = (m20 * _in.m01) + (m21 * _in.m11) + (m22 * _in.m21) + - (m23 * _in.m31); - ret.m22 = (m20 * _in.m02) + (m21 * _in.m12) + (m22 * _in.m22) + - (m23 * _in.m32); - ret.m23 = (m20 * _in.m03) + (m21 * _in.m13) + (m22 * _in.m23) + - (m23 * _in.m33); - - ret.m30 = (m30 * _in.m00) + (m31 * _in.m10) + (m32 * _in.m20) + - (m33 * _in.m30); - ret.m31 = (m30 * _in.m01) + (m31 * _in.m11) + (m32 * _in.m21) + - (m33 * _in.m31); - ret.m32 = (m30 * _in.m02) + (m31 * _in.m12) + (m32 * _in.m22) + - (m33 * _in.m32); - ret.m33 = (m30 * _in.m03) + (m31 * _in.m13) + (m32 * _in.m23) + - (m33 * _in.m33); + ret.m00 = (m00 * _in.m00) + (m01 * _in.m10) + (m02 * _in.m20) + (m03 * _in.m30); + ret.m01 = (m00 * _in.m01) + (m01 * _in.m11) + (m02 * _in.m21) + (m03 * _in.m31); + ret.m02 = (m00 * _in.m02) + (m01 * _in.m12) + (m02 * _in.m22) + (m03 * _in.m32); + ret.m03 = (m00 * _in.m03) + (m01 * _in.m13) + (m02 * _in.m23) + (m03 * _in.m33); + + + ret.m10 = (m10 * _in.m00) + (m11 * _in.m10) + (m12 * _in.m20) + (m13 * _in.m30); + ret.m11 = (m10 * _in.m01) + (m11 * _in.m11) + (m12 * _in.m21) + (m13 * _in.m31); + ret.m12 = (m10 * _in.m02) + (m11 * _in.m12) + (m12 * _in.m22) + (m13 * _in.m32); + ret.m13 = (m10 * _in.m03) + (m11 * _in.m13) + (m12 * _in.m23) + (m13 * _in.m33); + + + ret.m20 = (m20 * _in.m00) + (m21 * _in.m10) + (m22 * _in.m20) + (m23 * _in.m30); + ret.m21 = (m20 * _in.m01) + (m21 * _in.m11) + (m22 * _in.m21) + (m23 * _in.m31); + ret.m22 = (m20 * _in.m02) + (m21 * _in.m12) + (m22 * _in.m22) + (m23 * _in.m32); + ret.m23 = (m20 * _in.m03) + (m21 * _in.m13) + (m22 * _in.m23) + (m23 * _in.m33); + + ret.m30 = (m30 * _in.m00) + (m31 * _in.m10) + (m32 * _in.m20) + (m33 * _in.m30); + ret.m31 = (m30 * _in.m01) + (m31 * _in.m11) + (m32 * _in.m21) + (m33 * _in.m31); + ret.m32 = (m30 * _in.m02) + (m31 * _in.m12) + (m32 * _in.m22) + (m33 * _in.m32); + ret.m33 = (m30 * _in.m03) + (m31 * _in.m13) + (m32 * _in.m23) + (m33 * _in.m33); return ret; } @@ -641,29 +621,20 @@ public: float A0113 = m10 * m31 - m11 * m30; float A0112 = m10 * m21 - m11 * m20; - float det = m00 * (m11 * A2323 - m12 * A1323 + m13 * A1223) - - m01 * (m10 * A2323 - m12 * A0323 + m13 * A0223) + - m02 * (m10 * A1323 - m11 * A0323 + m13 * A0123) - - m03 * (m10 * A1223 - m11 * A0223 + m12 * A0123); + float det = + m00 * (m11 * A2323 - m12 * A1323 + m13 * A1223) - m01 * (m10 * A2323 - m12 * A0323 + m13 * A0223) + + m02 * (m10 * A1323 - m11 * A0323 + m13 * A0123) - m03 * (m10 * A1223 - m11 * A0223 + m12 * A0123); det = 1 / det; return Matrix4x4( - det * (m11 * A2323 - m12 * A1323 + m13 * A1223), - det * -(m01 * A2323 - m02 * A1323 + m03 * A1223), - det * (m01 * A2313 - m02 * A1313 + m03 * A1213), - det * -(m01 * A2312 - m02 * A1312 + m03 * A1212), - det * -(m10 * A2323 - m12 * A0323 + m13 * A0223), - det * (m00 * A2323 - m02 * A0323 + m03 * A0223), - det * -(m00 * A2313 - m02 * A0313 + m03 * A0213), - det * (m00 * A2312 - m02 * A0312 + m03 * A0212), - det * (m10 * A1323 - m11 * A0323 + m13 * A0123), - det * -(m00 * A1323 - m01 * A0323 + m03 * A0123), - det * (m00 * A1313 - m01 * A0313 + m03 * A0113), - det * -(m00 * A1312 - m01 * A0312 + m03 * A0112), - det * -(m10 * A1223 - m11 * A0223 + m12 * A0123), - det * (m00 * A1223 - m01 * A0223 + m02 * A0123), - det * -(m00 * A1213 - m01 * A0213 + m02 * A0113), - det * (m00 * A1212 - m01 * A0212 + m02 * A0112)); + det * (m11 * A2323 - m12 * A1323 + m13 * A1223), det * -(m01 * A2323 - m02 * A1323 + m03 * A1223), + det * (m01 * A2313 - m02 * A1313 + m03 * A1213), det * -(m01 * A2312 - m02 * A1312 + m03 * A1212), + det * -(m10 * A2323 - m12 * A0323 + m13 * A0223), det * (m00 * A2323 - m02 * A0323 + m03 * A0223), + det * -(m00 * A2313 - m02 * A0313 + m03 * A0213), det * (m00 * A2312 - m02 * A0312 + m03 * A0212), + det * (m10 * A1323 - m11 * A0323 + m13 * A0123), det * -(m00 * A1323 - m01 * A0323 + m03 * A0123), + det * (m00 * A1313 - m01 * A0313 + m03 * A0113), det * -(m00 * A1312 - m01 * A0312 + m03 * A0112), + det * -(m10 * A1223 - m11 * A0223 + m12 * A0123), det * (m00 * A1223 - m01 * A0223 + m02 * A0123), + det * -(m00 * A1213 - m01 * A0213 + m02 * A0113), det * (m00 * A1212 - m01 * A0212 + m02 * A0112)); } float m00; @@ -909,14 +880,11 @@ public: euler.y = asinf(2.0f * (in.w * in.y - in.x * in.z)); if (PI_OVER_2 - fabs(euler.y) > EPSILON) { - euler.z = atan2f(2.0f * (in.x * in.y + in.w * in.z), - sqx - sqy - sqz + sqw); - euler.x = atan2f(2.0f * (in.w * in.x + in.y * in.z), - sqw - sqx - sqy + sqz); + euler.z = atan2f(2.0f * (in.x * in.y + in.w * in.z), sqx - sqy - sqz + sqw); + euler.x = atan2f(2.0f * (in.w * in.x + in.y * in.z), sqw - sqx - sqy + sqz); } else { // compute heading from local 'down' vector - euler.z = atan2f(2.f * in.y * in.z - 2.f * in.x * in.w, - 2.f * in.x * in.z + 2.f * in.y * in.w); + euler.z = atan2f(2.f * in.y * in.z - 2.f * in.x * in.w, 2.f * in.x * in.z + 2.f * in.y * in.w); euler.x = 0.0f; // If facing down, reverse yaw @@ -942,13 +910,9 @@ public: float num11 = w * num2; float num12 = w * num3; Vector3 result; - result.x = (1.f - (num5 + num6)) * vec.x + - (num7 - num12) * vec.y + (num8 + num11) * vec.z; - result.y = (num7 + num12) * vec.x + - (1.f - (num4 + num6)) * vec.y + - (num9 - num10) * vec.z; - result.z = (num8 - num11) * vec.x + (num9 + num10) * vec.y + - (1.f - (num4 + num5)) * vec.z; + result.x = (1.f - (num5 + num6)) * vec.x + (num7 - num12) * vec.y + (num8 + num11) * vec.z; + result.y = (num7 + num12) * vec.x + (1.f - (num4 + num6)) * vec.y + (num9 - num10) * vec.z; + result.z = (num8 - num11) * vec.x + (num9 + num10) * vec.y + (1.f - (num4 + num5)) * vec.z; return result; } @@ -980,31 +944,23 @@ public: float qy = y; float qz = z; - const float n = - 1.0f / sqrt(qx * qx + qy * qy + qz * qz + qw * qw); + const float n = 1.0f / sqrt(qx * qx + qy * qy + qz * qz + qw * qw); qx *= n; qy *= n; qz *= n; qw *= n; - return Matrix4x4(1.0f - 2.0f * qy * qy - 2.0f * qz * qz, - 2.0f * qx * qy - 2.0f * qz * qw, - 2.0f * qx * qz + 2.0f * qy * qw, 0.0f, - 2.0f * qx * qy + 2.0f * qz * qw, - 1.0f - 2.0f * qx * qx - 2.0f * qz * qz, - 2.0f * qy * qz - 2.0f * qx * qw, 0.0f, - 2.0f * qx * qz - 2.0f * qy * qw, - 2.0f * qy * qz + 2.0f * qx * qw, - 1.0f - 2.0f * qx * qx - 2.0f * qy * qy, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f); + return Matrix4x4(1.0f - 2.0f * qy * qy - 2.0f * qz * qz, 2.0f * qx * qy - 2.0f * qz * qw, + 2.0f * qx * qz + 2.0f * qy * qw, 0.0f, 2.0f * qx * qy + 2.0f * qz * qw, + 1.0f - 2.0f * qx * qx - 2.0f * qz * qz, 2.0f * qy * qz - 2.0f * qx * qw, 0.0f, + 2.0f * qx * qz - 2.0f * qy * qw, 2.0f * qy * qz + 2.0f * qx * qw, + 1.0f - 2.0f * qx * qx - 2.0f * qy * qy, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } inline Quaternion operator*(const Quaternion &q) const { - return Quaternion(y * q.z - z * q.y + x * q.w + w * q.x, - z * q.x - x * q.z + y * q.w + w * q.y, - x * q.y - y * q.x + z * q.w + w * q.z, - w * q.w - x * q.x - y * q.y - z * q.z); + return Quaternion(y * q.z - z * q.y + x * q.w + w * q.x, z * q.x - x * q.z + y * q.w + w * q.y, + x * q.y - y * q.x + z * q.w + w * q.z, w * q.w - x * q.x - y * q.y - z * q.z); } Quaternion @@ -1034,8 +990,7 @@ public: float dot = Vector3::Dot(Vector3::Forward(), forwardVector); if (fabs(dot - (-1.0f)) < 0.000001f) { - return Quaternion(Vector3::Up().x, Vector3::Up().y, - Vector3::Up().z, 3.1415926535897932f); + return Quaternion(Vector3::Up().x, Vector3::Up().y, Vector3::Up().z, 3.1415926535897932f); } if (fabs(dot - (1.0f)) < 0.000001f) { return Quaternion(); @@ -1265,8 +1220,7 @@ public: inline Pose operator*(Pose const &rhs) const { - return Pose(position + (rotation * rhs.position), - rotation * rhs.rotation); + return Pose(position + (rotation * rhs.position), rotation * rhs.rotation); } inline Pose operator*(Vector3 const &rhs) const @@ -1277,7 +1231,6 @@ public: inline static Pose FromMatrix(Matrix4x4 m) { - return Pose(Vector3(m.m03, m.m13, m.m23), - Quaternion::FromMatrix(m)); + return Pose(Vector3(m.m03, m.m13, m.m23), Quaternion::FromMatrix(m)); } }; diff --git a/src/xrt/drivers/north_star/ns_hmd.c b/src/xrt/drivers/north_star/ns_hmd.c index 91b426cf7..267839d4a 100644 --- a/src/xrt/drivers/north_star/ns_hmd.c +++ b/src/xrt/drivers/north_star/ns_hmd.c @@ -35,8 +35,7 @@ DEBUG_GET_ONCE_LOG_OPTION(ns_log, "NS_LOG", U_LOGGING_INFO) -struct xrt_pose t265_to_nose_bridge = {.orientation = {0, 0, 0, 1}, - .position = {0, 0, 0}}; +struct xrt_pose t265_to_nose_bridge = {.orientation = {0, 0, 0, 1}, .position = {0, 0, 0}}; /* * @@ -47,8 +46,7 @@ struct xrt_pose t265_to_nose_bridge = {.orientation = {0, 0, 0, 1}, static double map(double value, double fromLow, double fromHigh, double toLow, double toHigh) { - return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + - toLow; + return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow; } // Math copied from // https://www.arduino.cc/reference/en/language/functions/math/map/ // This is pure math so it is still under the Boost Software License. @@ -91,8 +89,7 @@ ns_hmd_get_tracked_pose(struct xrt_device *xdev, // If the tracking device is created use it. if (ns->tracker != NULL) { - xrt_device_get_tracked_pose(ns->tracker, name, at_timestamp_ns, - out_relation); + xrt_device_get_tracked_pose(ns->tracker, name, at_timestamp_ns, out_relation); return; } @@ -102,10 +99,9 @@ ns_hmd_get_tracked_pose(struct xrt_device *xdev, } out_relation->pose = ns->pose; - out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + out_relation->relation_flags = (enum xrt_space_relation_flags)(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_POSITION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); } static void @@ -126,11 +122,7 @@ ns_hmd_get_view_pose(struct xrt_device *xdev, */ static bool -ns_mesh_calc(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result) +ns_mesh_calc(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result) { struct ns_hmd *ns = ns_hmd(xdev); @@ -167,58 +159,34 @@ ns_leap_parse(struct ns_leap *leap, struct cJSON *leap_data) */ u_json_get_vec3( - cJSON_GetObjectItemCaseSensitive( - cJSON_GetObjectItemCaseSensitive(leap_data, "localPose"), - "position"), + cJSON_GetObjectItemCaseSensitive(cJSON_GetObjectItemCaseSensitive(leap_data, "localPose"), "position"), &leap->pose.position); u_json_get_quat( - cJSON_GetObjectItemCaseSensitive( - cJSON_GetObjectItemCaseSensitive(leap_data, "localPose"), - "rotation"), + cJSON_GetObjectItemCaseSensitive(cJSON_GetObjectItemCaseSensitive(leap_data, "localPose"), "rotation"), &leap->pose.orientation); } static void ns_eye_parse(struct ns_v1_eye *eye, struct cJSON *eye_data) { - u_json_get_float( - cJSON_GetObjectItemCaseSensitive(eye_data, "ellipseMinorAxis"), - &eye->ellipse_minor_axis); - u_json_get_float( - cJSON_GetObjectItemCaseSensitive(eye_data, "ellipseMajorAxis"), - &eye->ellipse_major_axis); - u_json_get_vec3( - cJSON_GetObjectItemCaseSensitive(eye_data, "screenForward"), - &eye->screen_forward); - u_json_get_vec3( - cJSON_GetObjectItemCaseSensitive(eye_data, "screenPosition"), - &eye->screen_position); - u_json_get_vec3( - cJSON_GetObjectItemCaseSensitive(eye_data, "eyePosition"), - &eye->eye_pose.position); - u_json_get_quat( - cJSON_GetObjectItemCaseSensitive(eye_data, "eyeRotation"), - &eye->eye_pose.orientation); - u_json_get_quat( - cJSON_GetObjectItemCaseSensitive(eye_data, "cameraProjection"), - &eye->camera_projection); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(eye_data, "ellipseMinorAxis"), &eye->ellipse_minor_axis); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(eye_data, "ellipseMajorAxis"), &eye->ellipse_major_axis); + u_json_get_vec3(cJSON_GetObjectItemCaseSensitive(eye_data, "screenForward"), &eye->screen_forward); + u_json_get_vec3(cJSON_GetObjectItemCaseSensitive(eye_data, "screenPosition"), &eye->screen_position); + u_json_get_vec3(cJSON_GetObjectItemCaseSensitive(eye_data, "eyePosition"), &eye->eye_pose.position); + u_json_get_quat(cJSON_GetObjectItemCaseSensitive(eye_data, "eyeRotation"), &eye->eye_pose.orientation); + u_json_get_quat(cJSON_GetObjectItemCaseSensitive(eye_data, "cameraProjection"), &eye->camera_projection); for (int x = 0; x < 4; ++x) { for (int y = 0; y < 4; ++y) { char key[4]; sprintf(key, "e%d%d", x, y); - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - cJSON_GetObjectItemCaseSensitive( - eye_data, "sphereToWorldSpace"), - key), - &eye->sphere_to_world_space.v[(x * 4) + y]); - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - cJSON_GetObjectItemCaseSensitive( - eye_data, "worldToScreenSpace"), - key), - &eye->world_to_screen_space.v[(x * 4) + y]); + u_json_get_float(cJSON_GetObjectItemCaseSensitive( + cJSON_GetObjectItemCaseSensitive(eye_data, "sphereToWorldSpace"), key), + &eye->sphere_to_world_space.v[(x * 4) + y]); + u_json_get_float(cJSON_GetObjectItemCaseSensitive( + cJSON_GetObjectItemCaseSensitive(eye_data, "worldToScreenSpace"), key), + &eye->world_to_screen_space.v[(x * 4) + y]); } } } @@ -229,14 +197,11 @@ ns_fov_calculate(struct xrt_fov *fov, struct xrt_quat projection) { // All of these are wrong - gets "hidden" by the simple_fov making it look // okay. Needs to be fixed. - fov->angle_up = projection.x; // atanf(fabsf(projection.x) / - // near_plane); - fov->angle_down = - projection.y; // atanf(fabsf(projection.y) / near_plane); - fov->angle_left = - projection.z; // atanf(fabsf(projection.z) / near_plane); - fov->angle_right = - projection.w; // atanf(fabsf(projection.w) / near_plane); + fov->angle_up = projection.x; // atanf(fabsf(projection.x) / + // near_plane); + fov->angle_down = projection.y; // atanf(fabsf(projection.y) / near_plane); + fov->angle_left = projection.z; // atanf(fabsf(projection.z) / near_plane); + fov->angle_right = projection.w; // atanf(fabsf(projection.w) / near_plane); } /* @@ -285,13 +250,10 @@ ns_v2_polyval2d(float X, float Y, float C[16]) float X3 = X2 * X; float Y2 = Y * Y; float Y3 = Y2 * Y; - return ( - ((C[0]) + (C[1] * Y) + (C[2] * Y2) + (C[3] * Y3)) + - ((C[4] * X) + (C[5] * X * Y) + (C[6] * X * Y2) + (C[7] * X * Y3)) + - ((C[8] * X2) + (C[9] * X2 * Y) + (C[10] * X2 * Y2) + - (C[11] * X2 * Y3)) + - ((C[12] * X3) + (C[13] * X3 * Y) + (C[14] * X3 * Y2) + - (C[15] * X3 * Y3))); + return (((C[0]) + (C[1] * Y) + (C[2] * Y2) + (C[3] * Y3)) + + ((C[4] * X) + (C[5] * X * Y) + (C[6] * X * Y2) + (C[7] * X * Y3)) + + ((C[8] * X2) + (C[9] * X2 * Y) + (C[10] * X2 * Y2) + (C[11] * X2 * Y3)) + + ((C[12] * X3) + (C[13] * X3 * Y) + (C[14] * X3 * Y2) + (C[15] * X3 * Y3))); } @@ -299,24 +261,16 @@ ns_v2_polyval2d(float X, float Y, float C[16]) static void ns_v2_fov_calculate(struct ns_hmd *ns, int eye_index) { - ns->base.hmd->views[eye_index].fov.angle_down = - ns->eye_configs_v2[eye_index].fov.angle_down; - ns->base.hmd->views[eye_index].fov.angle_up = - ns->eye_configs_v2[eye_index].fov.angle_up; - ns->base.hmd->views[eye_index].fov.angle_left = - ns->eye_configs_v2[eye_index].fov.angle_left; - ns->base.hmd->views[eye_index].fov.angle_right = - ns->eye_configs_v2[eye_index].fov.angle_right; + ns->base.hmd->views[eye_index].fov.angle_down = ns->eye_configs_v2[eye_index].fov.angle_down; + ns->base.hmd->views[eye_index].fov.angle_up = ns->eye_configs_v2[eye_index].fov.angle_up; + ns->base.hmd->views[eye_index].fov.angle_left = ns->eye_configs_v2[eye_index].fov.angle_left; + ns->base.hmd->views[eye_index].fov.angle_right = ns->eye_configs_v2[eye_index].fov.angle_right; } static bool -ns_v2_mesh_calc(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result) +ns_v2_mesh_calc(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result) { /*! @todo (Moses Turner) It should not be necessary to reverse the U and * V coords. I have no idea why it is like this. It shouldn't be like @@ -330,10 +284,8 @@ ns_v2_mesh_calc(struct xrt_device *xdev, struct ns_hmd *ns = ns_hmd(xdev); - float x_ray = - ns_v2_polyval2d(u, v, ns->eye_configs_v2[view].x_coefficients); - float y_ray = - ns_v2_polyval2d(u, v, ns->eye_configs_v2[view].y_coefficients); + float x_ray = ns_v2_polyval2d(u, v, ns->eye_configs_v2[view].x_coefficients); + float y_ray = ns_v2_polyval2d(u, v, ns->eye_configs_v2[view].y_coefficients); float left_ray_bound = tan(ns->eye_configs_v2[view].fov.angle_left); @@ -374,10 +326,7 @@ ns_config_load(struct ns_hmd *ns) // Open the JSON file and put its contents into a string FILE *config_file = fopen(ns->config_path, "r"); if (config_file == NULL) { - NS_ERROR( - ns, - "The configuration file at path \"%s\" was unable to load", - ns->config_path); + NS_ERROR(ns, "The configuration file at path \"%s\" was unable to load", ns->config_path); return false; } @@ -394,24 +343,19 @@ ns_config_load(struct ns_hmd *ns) config_json = cJSON_Parse(json); if (config_json == NULL) { const char *error_ptr = cJSON_GetErrorPtr(); - NS_ERROR(ns, "The JSON file at path \"%s\" was unable to parse", - ns->config_path); + NS_ERROR(ns, "The JSON file at path \"%s\" was unable to parse", ns->config_path); if (error_ptr != NULL) { - NS_ERROR(ns, "because of an error before %s", - error_ptr); + NS_ERROR(ns, "because of an error before %s", error_ptr); } return false; } if (cJSON_GetObjectItemCaseSensitive(config_json, "leftEye") == NULL && - cJSON_GetObjectItemCaseSensitive(config_json, - "left_uv_to_rect_x") != NULL) { + cJSON_GetObjectItemCaseSensitive(config_json, "left_uv_to_rect_x") != NULL) { // Bad hack to tell that we're v2. Error checking is not good // enough for public consumption - many cases where a malformed // config json results in cryptic errors. Should get fixed // whenever we have more than 5 people using this. - u_json_get_float( - cJSON_GetObjectItemCaseSensitive(config_json, "baseline"), - &ns->ipd); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "baseline"), &ns->ipd); ns->ipd = ns->ipd / 1000.0f; // converts from mm to m /*! @todo (Moses Turner) Next four u_json_get_float_array calls * don't make any sense. They put the X coefficients from the @@ -419,33 +363,21 @@ ns_config_load(struct ns_hmd *ns) * totally wrong, but the distortion looks totally wrong if we * don't do this. */ - u_json_get_float_array(cJSON_GetObjectItemCaseSensitive( - config_json, "left_uv_to_rect_x"), - ns->eye_configs_v2[0].y_coefficients, - 16); - u_json_get_float_array(cJSON_GetObjectItemCaseSensitive( - config_json, "left_uv_to_rect_y"), - ns->eye_configs_v2[0].x_coefficients, - 16); - u_json_get_float_array(cJSON_GetObjectItemCaseSensitive( - config_json, "right_uv_to_rect_x"), - ns->eye_configs_v2[1].y_coefficients, - 16); - u_json_get_float_array(cJSON_GetObjectItemCaseSensitive( - config_json, "right_uv_to_rect_y"), - ns->eye_configs_v2[1].x_coefficients, - 16); + u_json_get_float_array(cJSON_GetObjectItemCaseSensitive(config_json, "left_uv_to_rect_x"), + ns->eye_configs_v2[0].y_coefficients, 16); + u_json_get_float_array(cJSON_GetObjectItemCaseSensitive(config_json, "left_uv_to_rect_y"), + ns->eye_configs_v2[0].x_coefficients, 16); + u_json_get_float_array(cJSON_GetObjectItemCaseSensitive(config_json, "right_uv_to_rect_x"), + ns->eye_configs_v2[1].y_coefficients, 16); + u_json_get_float_array(cJSON_GetObjectItemCaseSensitive(config_json, "right_uv_to_rect_y"), + ns->eye_configs_v2[1].x_coefficients, 16); bool said_first_thing = false; - if (!u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - config_json, "left_fov_radians_left"), - &ns->eye_configs_v2[0] - .fov - .angle_left)) { // not putting this directly in - // (&ns->base.hmd->views[eye_index].fov - // because i smell a rat there - - // that value seems to unexpectedly - // change during init process. + if (!u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "left_fov_radians_left"), + &ns->eye_configs_v2[0].fov.angle_left)) { // not putting this directly in + // (&ns->base.hmd->views[eye_index].fov + // because i smell a rat there - + // that value seems to unexpectedly + // change during init process. NS_INFO(ns, "Just so you know, you can add tunable FoV " "parameters to your v2 json file. There's an " @@ -471,119 +403,82 @@ ns_config_load(struct ns_hmd *ns) * ns_v2_mesh_calc or this code, because when you have * uneven FOV bounds, the distortion looks totally * wrong.*/ - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - config_json, "left_fov_radians_left"), - &ns->eye_configs_v2[0].fov.angle_left); - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - config_json, "left_fov_radians_right"), - &ns->eye_configs_v2[0].fov.angle_right); - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - config_json, "left_fov_radians_up"), - &ns->eye_configs_v2[0].fov.angle_up); - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - config_json, "left_fov_radians_down"), - &ns->eye_configs_v2[0].fov.angle_down); - - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - config_json, "right_fov_radians_left"), - &ns->eye_configs_v2[1].fov.angle_left); - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - config_json, "right_fov_radians_right"), - &ns->eye_configs_v2[1].fov.angle_right); - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - config_json, "right_fov_radians_up"), - &ns->eye_configs_v2[1].fov.angle_up); - u_json_get_float( - cJSON_GetObjectItemCaseSensitive( - config_json, "right_fov_radians_down"), - &ns->eye_configs_v2[1].fov.angle_down); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "left_fov_radians_left"), + &ns->eye_configs_v2[0].fov.angle_left); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "left_fov_radians_right"), + &ns->eye_configs_v2[0].fov.angle_right); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "left_fov_radians_up"), + &ns->eye_configs_v2[0].fov.angle_up); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "left_fov_radians_down"), + &ns->eye_configs_v2[0].fov.angle_down); + + u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "right_fov_radians_left"), + &ns->eye_configs_v2[1].fov.angle_left); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "right_fov_radians_right"), + &ns->eye_configs_v2[1].fov.angle_right); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "right_fov_radians_up"), + &ns->eye_configs_v2[1].fov.angle_up); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(config_json, "right_fov_radians_down"), + &ns->eye_configs_v2[1].fov.angle_down); } - struct cJSON *offset = cJSON_GetObjectItemCaseSensitive( - config_json, "t265_to_nose_bridge"); + struct cJSON *offset = cJSON_GetObjectItemCaseSensitive(config_json, "t265_to_nose_bridge"); if (offset == NULL) { if (said_first_thing) { - NS_INFO( - ns, - "Also, you should put an offset parameter " - "into the json file to transform your head " - "pose from the realsense to your nose " - "bridge. There are some examples in " - "src/xrt/drivers/north_star/" - "example_configs/ .\n"); + NS_INFO(ns, + "Also, you should put an offset parameter " + "into the json file to transform your head " + "pose from the realsense to your nose " + "bridge. There are some examples in " + "src/xrt/drivers/north_star/" + "example_configs/ .\n"); } else { - NS_INFO( - ns, - "You should put an offset parameter into " - "the json file to transform your head pose " - "from the realsense to your nose bridge. " - "There are some examples in " - "src/xrt/drivers/north_star/" - "example_configs/ .\n"); + NS_INFO(ns, + "You should put an offset parameter into " + "the json file to transform your head pose " + "from the realsense to your nose bridge. " + "There are some examples in " + "src/xrt/drivers/north_star/" + "example_configs/ .\n"); } } else { struct cJSON *translation_meters = - cJSON_GetObjectItemCaseSensitive( - offset, "translation_meters"); - u_json_get_float(cJSON_GetObjectItemCaseSensitive( - translation_meters, "x"), + cJSON_GetObjectItemCaseSensitive(offset, "translation_meters"); + u_json_get_float(cJSON_GetObjectItemCaseSensitive(translation_meters, "x"), &t265_to_nose_bridge.position.x); - u_json_get_float(cJSON_GetObjectItemCaseSensitive( - translation_meters, "y"), + u_json_get_float(cJSON_GetObjectItemCaseSensitive(translation_meters, "y"), &t265_to_nose_bridge.position.y); - u_json_get_float(cJSON_GetObjectItemCaseSensitive( - translation_meters, "z"), + u_json_get_float(cJSON_GetObjectItemCaseSensitive(translation_meters, "z"), &t265_to_nose_bridge.position.z); struct cJSON *rotation_quaternion = - cJSON_GetObjectItemCaseSensitive( - offset, "rotation_quaternion"); + cJSON_GetObjectItemCaseSensitive(offset, "rotation_quaternion"); - u_json_get_float(cJSON_GetObjectItemCaseSensitive( - rotation_quaternion, "x"), + u_json_get_float(cJSON_GetObjectItemCaseSensitive(rotation_quaternion, "x"), &t265_to_nose_bridge.orientation.x); - u_json_get_float(cJSON_GetObjectItemCaseSensitive( - rotation_quaternion, "y"), + u_json_get_float(cJSON_GetObjectItemCaseSensitive(rotation_quaternion, "y"), &t265_to_nose_bridge.orientation.y); - u_json_get_float(cJSON_GetObjectItemCaseSensitive( - rotation_quaternion, "z"), + u_json_get_float(cJSON_GetObjectItemCaseSensitive(rotation_quaternion, "z"), &t265_to_nose_bridge.orientation.z); - u_json_get_float(cJSON_GetObjectItemCaseSensitive( - rotation_quaternion, "w"), + u_json_get_float(cJSON_GetObjectItemCaseSensitive(rotation_quaternion, "w"), &t265_to_nose_bridge.orientation.w); } ns->is_v2 = true; - } else if (cJSON_GetObjectItemCaseSensitive(config_json, "leftEye") != - NULL && - cJSON_GetObjectItemCaseSensitive( - config_json, "left_uv_to_rect_x") == NULL) { - ns_eye_parse( - &ns->eye_configs_v1[0], - cJSON_GetObjectItemCaseSensitive(config_json, "leftEye")); - - ns_eye_parse( - &ns->eye_configs_v1[1], - cJSON_GetObjectItemCaseSensitive(config_json, "rightEye")); - ns_leap_parse(&ns->leap_config, - cJSON_GetObjectItemCaseSensitive(config_json, - "leapTracker")); + } else if (cJSON_GetObjectItemCaseSensitive(config_json, "leftEye") != NULL && + cJSON_GetObjectItemCaseSensitive(config_json, "left_uv_to_rect_x") == NULL) { + ns_eye_parse(&ns->eye_configs_v1[0], cJSON_GetObjectItemCaseSensitive(config_json, "leftEye")); + + ns_eye_parse(&ns->eye_configs_v1[1], cJSON_GetObjectItemCaseSensitive(config_json, "rightEye")); + ns_leap_parse(&ns->leap_config, cJSON_GetObjectItemCaseSensitive(config_json, "leapTracker")); ns->is_v2 = false; } else { - NS_ERROR( - ns, - "Bad config file. There are examples of v1 and v2 files in " - "src/xrt/drivers/north_star - if those don't work, " - "something's really wrong."); + NS_ERROR(ns, + "Bad config file. There are examples of v1 and v2 files in " + "src/xrt/drivers/north_star - if those don't work, " + "something's really wrong."); } cJSON_Delete(config_json); @@ -600,8 +495,8 @@ ns_config_load(struct ns_hmd *ns) struct xrt_device * ns_hmd_create(const char *config_path) { - enum u_device_alloc_flags flags = (enum u_device_alloc_flags)( - U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); + enum u_device_alloc_flags flags = + (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); struct ns_hmd *ns = U_DEVICE_ALLOCATE(struct ns_hmd, flags, 1, 0); @@ -650,23 +545,18 @@ ns_hmd_create(const char *config_path) ns_v2_fov_calculate(ns, 1); ns->base.hmd->distortion.models = XRT_DISTORTION_MODEL_COMPUTE; - ns->base.hmd->distortion.preferred = - XRT_DISTORTION_MODEL_COMPUTE; + ns->base.hmd->distortion.preferred = XRT_DISTORTION_MODEL_COMPUTE; ns->base.compute_distortion = ns_v2_mesh_calc; } else { // V1 ns->base.get_view_pose = ns_hmd_get_view_pose; - ns_fov_calculate(&ns->base.hmd->views[0].fov, - ns->eye_configs_v1[0].camera_projection); - ns_fov_calculate(&ns->base.hmd->views[1].fov, - ns->eye_configs_v1[1].camera_projection); + ns_fov_calculate(&ns->base.hmd->views[0].fov, ns->eye_configs_v1[0].camera_projection); + ns_fov_calculate(&ns->base.hmd->views[1].fov, ns->eye_configs_v1[1].camera_projection); // Create the optical systems - ns->eye_configs_v1[0].optical_system = - ns_create_optical_system(&ns->eye_configs_v1[0]); - ns->eye_configs_v1[1].optical_system = - ns_create_optical_system(&ns->eye_configs_v1[1]); + ns->eye_configs_v1[0].optical_system = ns_create_optical_system(&ns->eye_configs_v1[0]); + ns->eye_configs_v1[1].optical_system = ns_create_optical_system(&ns->eye_configs_v1[1]); // Setup the north star basic info if (!u_device_setup_split_side_by_side(&ns->base, &info)) { @@ -675,8 +565,7 @@ ns_hmd_create(const char *config_path) } ns->base.hmd->distortion.models = XRT_DISTORTION_MODEL_COMPUTE; - ns->base.hmd->distortion.preferred = - XRT_DISTORTION_MODEL_COMPUTE; + ns->base.hmd->distortion.preferred = XRT_DISTORTION_MODEL_COMPUTE; ns->base.compute_distortion = ns_mesh_calc; } @@ -695,8 +584,7 @@ ns_hmd_create(const char *config_path) ns->base.orientation_tracking_supported = true; ns->base.position_tracking_supported = ns->tracker != NULL; if (ns->tracker) { - ns->base.tracking_origin->type = - ns->tracker->tracking_origin->type; + ns->base.tracking_origin->type = ns->tracker->tracking_origin->type; } ns->base.device_type = XRT_DEVICE_TYPE_HMD; diff --git a/src/xrt/drivers/north_star/ns_hmd.h b/src/xrt/drivers/north_star/ns_hmd.h index 6ea18f5e8..4fe42da68 100644 --- a/src/xrt/drivers/north_star/ns_hmd.h +++ b/src/xrt/drivers/north_star/ns_hmd.h @@ -151,9 +151,7 @@ ns_hmd(struct xrt_device *xdev) * @ingroup drv_ns */ void -ns_display_uv_to_render_uv(struct ns_uv in, - struct ns_uv *out, - struct ns_v1_eye *eye); +ns_display_uv_to_render_uv(struct ns_uv in, struct ns_uv *out, struct ns_v1_eye *eye); struct ns_optical_system * ns_create_optical_system(struct ns_v1_eye *eye); diff --git a/src/xrt/drivers/north_star/ns_prober.c b/src/xrt/drivers/north_star/ns_prober.c index d54d59332..ff380f31b 100644 --- a/src/xrt/drivers/north_star/ns_prober.c +++ b/src/xrt/drivers/north_star/ns_prober.c @@ -49,10 +49,7 @@ ns_prober_destroy(struct xrt_auto_prober *p) //! @public @memberof ns_prober static struct xrt_device * -ns_prober_autoprobe(struct xrt_auto_prober *xap, - cJSON *attached_data, - bool no_hmds, - struct xrt_prober *xp) +ns_prober_autoprobe(struct xrt_auto_prober *xap, cJSON *attached_data, bool no_hmds, struct xrt_prober *xp) { struct ns_prober *nsp = ns_prober(xap); diff --git a/src/xrt/drivers/ohmd/oh_device.c b/src/xrt/drivers/ohmd/oh_device.c index 07d7ec7c0..683f295a5 100644 --- a/src/xrt/drivers/ohmd/oh_device.c +++ b/src/xrt/drivers/ohmd/oh_device.c @@ -129,24 +129,21 @@ oh_device_get_tracked_pose(struct xrt_device *xdev, out_relation->pose.orientation = quat; out_relation->pose.position = pos; //! @todo assuming that orientation is actually currently tracked - out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | - XRT_SPACE_RELATION_POSITION_VALID_BIT); + out_relation->relation_flags = (enum xrt_space_relation_flags)(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | + XRT_SPACE_RELATION_POSITION_VALID_BIT); // we assume the position is tracked if and only if it is not zero if (pos.x != 0.0 || pos.y != 0.0 || pos.z != 0.0) { - out_relation->relation_flags = (enum xrt_space_relation_flags)( - out_relation->relation_flags | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT); + out_relation->relation_flags = (enum xrt_space_relation_flags)(out_relation->relation_flags | + XRT_SPACE_RELATION_POSITION_TRACKED_BIT); } bool have_ang_vel = false; struct xrt_vec3 ang_vel; #ifdef OHMD_HAVE_ANG_VEL if (!ohd->skip_ang_vel) { - if (0 == ohmd_device_getf(ohd->dev, OHMD_ANGULAR_VELOCITY, - &ang_vel.x)) { + if (0 == ohmd_device_getf(ohd->dev, OHMD_ANGULAR_VELOCITY, &ang_vel.x)) { have_ang_vel = true; } else { // we now know this device doesn't return angular @@ -185,8 +182,7 @@ oh_device_get_tracked_pose(struct xrt_device *xdev, // last report was not long ago but not // instantaneously (at least half a millisecond), // so approximately safe to do this. - math_quat_finite_difference(&old_quat, &quat, dt, - &ang_vel); + math_quat_finite_difference(&old_quat, &quat, dt, &ang_vel); have_ang_vel = true; } } @@ -194,16 +190,12 @@ oh_device_get_tracked_pose(struct xrt_device *xdev, if (have_ang_vel) { out_relation->angular_velocity = ang_vel; out_relation->relation_flags = (enum xrt_space_relation_flags)( - out_relation->relation_flags | - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT); + out_relation->relation_flags | XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT); - OHMD_TRACE(ohd, - "GET_TRACKED_POSE (%f, %f, %f, %f) (%f, %f, %f)", - quat.x, quat.y, quat.z, quat.w, ang_vel.x, ang_vel.y, - ang_vel.z); + OHMD_TRACE(ohd, "GET_TRACKED_POSE (%f, %f, %f, %f) (%f, %f, %f)", quat.x, quat.y, quat.z, quat.w, + ang_vel.x, ang_vel.y, ang_vel.z); } else { - OHMD_TRACE(ohd, "GET_TRACKED_POSE (%f, %f, %f, %f)", quat.x, - quat.y, quat.z, quat.w); + OHMD_TRACE(ohd, "GET_TRACKED_POSE (%f, %f, %f, %f)", quat.x, quat.y, quat.z, quat.w); } // Update state within driver @@ -443,10 +435,7 @@ get_info(struct oh_device *ohd, const char *prod) // slightly different to u_compute_distortion_panotools in u_distortion_mesh static bool -u_compute_distortion_openhmd(struct openhmd_values *values, - float u, - float v, - struct xrt_uv_triplet *result) +u_compute_distortion_openhmd(struct openhmd_values *values, float u, float v, struct xrt_uv_triplet *result) { struct openhmd_values val = *values; @@ -483,27 +472,17 @@ u_compute_distortion_openhmd(struct openhmd_values *values, } static bool -compute_distortion_openhmd(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result) +compute_distortion_openhmd(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result) { struct oh_device *ohd = oh_device(xdev); - return u_compute_distortion_openhmd(&ohd->distortion.openhmd[view], u, - v, result); + return u_compute_distortion_openhmd(&ohd->distortion.openhmd[view], u, v, result); } static bool -compute_distortion_vive(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result) +compute_distortion_vive(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result) { struct oh_device *ohd = oh_device(xdev); - return u_compute_distortion_vive(&ohd->distortion.vive[view], u, v, - result); + return u_compute_distortion_vive(&ohd->distortion.vive[view], u, v, result); } static inline void @@ -517,10 +496,9 @@ swap(int *a, int *b) struct xrt_device * oh_device_create(ohmd_context *ctx, ohmd_device *dev, const char *prod) { - enum u_device_alloc_flags flags = (enum u_device_alloc_flags)( - U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); - struct oh_device *ohd = - U_DEVICE_ALLOCATE(struct oh_device, flags, 1, 0); + enum u_device_alloc_flags flags = + (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); + struct oh_device *ohd = U_DEVICE_ALLOCATE(struct oh_device, flags, 1, 0); ohd->base.update_inputs = oh_device_update_inputs; ohd->base.get_tracked_pose = oh_device_get_tracked_pose; ohd->base.get_view_pose = oh_device_get_view_pose; @@ -530,8 +508,7 @@ oh_device_create(ohmd_context *ctx, ohmd_device *dev, const char *prod) ohd->ctx = ctx; ohd->dev = dev; ohd->ll = debug_get_log_option_ohmd_log(); - ohd->enable_finite_difference = - debug_get_bool_option_ohmd_finite_diff(); + ohd->enable_finite_difference = debug_get_bool_option_ohmd_finite_diff(); snprintf(ohd->base.str, XRT_DEVICE_NAME_LEN, "%s (OpenHMD)", prod); @@ -539,30 +516,21 @@ oh_device_create(ohmd_context *ctx, ohmd_device *dev, const char *prod) { /* right eye */ - if (!math_compute_fovs(info.views[1].display.w_meters, - info.views[1].lens_center_x_meters, - info.views[1].fov, - info.views[1].display.h_meters, - info.views[1].lens_center_y_meters, 0, - &ohd->base.hmd->views[1].fov)) { - OHMD_ERROR( - ohd, - "Failed to compute the partial fields of view."); + if (!math_compute_fovs(info.views[1].display.w_meters, info.views[1].lens_center_x_meters, + info.views[1].fov, info.views[1].display.h_meters, + info.views[1].lens_center_y_meters, 0, &ohd->base.hmd->views[1].fov)) { + OHMD_ERROR(ohd, "Failed to compute the partial fields of view."); free(ohd); return NULL; } } { /* left eye - just mirroring right eye now */ - ohd->base.hmd->views[0].fov.angle_up = - ohd->base.hmd->views[1].fov.angle_up; - ohd->base.hmd->views[0].fov.angle_down = - ohd->base.hmd->views[1].fov.angle_down; - - ohd->base.hmd->views[0].fov.angle_left = - -ohd->base.hmd->views[1].fov.angle_right; - ohd->base.hmd->views[0].fov.angle_right = - -ohd->base.hmd->views[1].fov.angle_left; + ohd->base.hmd->views[0].fov.angle_up = ohd->base.hmd->views[1].fov.angle_up; + ohd->base.hmd->views[0].fov.angle_down = ohd->base.hmd->views[1].fov.angle_down; + + ohd->base.hmd->views[0].fov.angle_left = -ohd->base.hmd->views[1].fov.angle_right; + ohd->base.hmd->views[0].fov.angle_right = -ohd->base.hmd->views[1].fov.angle_left; } // clang-format off @@ -634,8 +602,8 @@ oh_device_create(ohmd_context *ctx, ohmd_device *dev, const char *prod) // Which blend modes does the device support. ohd->base.hmd->blend_mode = XRT_BLEND_MODE_OPAQUE; if (info.quirks.video_see_through) { - ohd->base.hmd->blend_mode = (enum xrt_blend_mode)( - ohd->base.hmd->blend_mode | XRT_BLEND_MODE_ALPHA_BLEND); + ohd->base.hmd->blend_mode = + (enum xrt_blend_mode)(ohd->base.hmd->blend_mode | XRT_BLEND_MODE_ALPHA_BLEND); } if (info.quirks.video_distortion_vive) { @@ -694,8 +662,7 @@ oh_device_create(ohmd_context *ctx, ohmd_device *dev, const char *prod) if (info.quirks.left_center_pano_scale) { for (int view = 0; view < 2; view++) { - ohd->distortion.openhmd[view].warp_scale = - info.views[0].lens_center_x_meters; + ohd->distortion.openhmd[view].warp_scale = info.views[0].lens_center_x_meters; } } @@ -703,8 +670,7 @@ oh_device_create(ohmd_context *ctx, ohmd_device *dev, const char *prod) OHMD_DEBUG(ohd, "Displays rotated right"); // openhmd display dimensions are *after* all rotations - swap(&ohd->base.hmd->screens->w_pixels, - &ohd->base.hmd->screens->h_pixels); + swap(&ohd->base.hmd->screens->w_pixels, &ohd->base.hmd->screens->h_pixels); // display dimensions are *after* all rotations int w0 = info.views[0].display.w_pixels; @@ -730,8 +696,7 @@ oh_device_create(ohmd_context *ctx, ohmd_device *dev, const char *prod) OHMD_DEBUG(ohd, "Displays rotated left"); // openhmd display dimensions are *after* all rotations - swap(&ohd->base.hmd->screens->w_pixels, - &ohd->base.hmd->screens->h_pixels); + swap(&ohd->base.hmd->screens->w_pixels, &ohd->base.hmd->screens->h_pixels); // display dimensions are *after* all rotations int w0 = info.views[0].display.w_pixels; @@ -779,18 +744,12 @@ oh_device_create(ohmd_context *ctx, ohmd_device *dev, const char *prod) OHMD_DEBUG(ohd, "Display/viewport/offset after rotation %dx%d/%dx%d/%dx%d, " "%dx%d/%dx%d/%dx%d", - ohd->base.hmd->views[0].display.w_pixels, - ohd->base.hmd->views[0].display.h_pixels, - ohd->base.hmd->views[0].viewport.w_pixels, - ohd->base.hmd->views[0].viewport.h_pixels, - ohd->base.hmd->views[0].viewport.x_pixels, - ohd->base.hmd->views[0].viewport.y_pixels, - ohd->base.hmd->views[1].display.w_pixels, - ohd->base.hmd->views[1].display.h_pixels, - ohd->base.hmd->views[1].viewport.w_pixels, - ohd->base.hmd->views[1].viewport.h_pixels, - ohd->base.hmd->views[0].viewport.x_pixels, - ohd->base.hmd->views[0].viewport.y_pixels); + ohd->base.hmd->views[0].display.w_pixels, ohd->base.hmd->views[0].display.h_pixels, + ohd->base.hmd->views[0].viewport.w_pixels, ohd->base.hmd->views[0].viewport.h_pixels, + ohd->base.hmd->views[0].viewport.x_pixels, ohd->base.hmd->views[0].viewport.y_pixels, + ohd->base.hmd->views[1].display.w_pixels, ohd->base.hmd->views[1].display.h_pixels, + ohd->base.hmd->views[1].viewport.w_pixels, ohd->base.hmd->views[1].viewport.h_pixels, + ohd->base.hmd->views[0].viewport.x_pixels, ohd->base.hmd->views[0].viewport.y_pixels); if (info.quirks.delay_after_initialization) { diff --git a/src/xrt/drivers/ohmd/oh_prober.c b/src/xrt/drivers/ohmd/oh_prober.c index 48b330e50..3f0cfd878 100644 --- a/src/xrt/drivers/ohmd/oh_prober.c +++ b/src/xrt/drivers/ohmd/oh_prober.c @@ -54,10 +54,7 @@ oh_prober_destroy(struct xrt_auto_prober *p) //! @public @memberof oh_prober static struct xrt_device * -oh_prober_autoprobe(struct xrt_auto_prober *xap, - cJSON *attached_data, - bool no_hmds, - struct xrt_prober *xp) +oh_prober_autoprobe(struct xrt_auto_prober *xap, cJSON *attached_data, bool no_hmds, struct xrt_prober *xp) { struct oh_prober *ohp = oh_prober(xap); @@ -87,27 +84,21 @@ oh_prober_autoprobe(struct xrt_auto_prober *xap, } if (device_flags & OHMD_DEVICE_FLAGS_NULL_DEVICE) { - U_LOG_D("Rejecting device idx %i, is a NULL device.", - i); + U_LOG_D("Rejecting device idx %i, is a NULL device.", i); continue; } prod = ohmd_list_gets(ohp->ctx, i, OHMD_PRODUCT); - if (strcmp(prod, "External Device") == 0 && - !debug_get_bool_option_ohmd_external()) { - U_LOG_D( - "Rejecting device idx %i, is a External device.", - i); + if (strcmp(prod, "External Device") == 0 && !debug_get_bool_option_ohmd_external()) { + U_LOG_D("Rejecting device idx %i, is a External device.", i); continue; } U_LOG_D("Selecting device idx %i", i); device_idx = i; - orientation_tracking_supported = - (device_flags & OHMD_DEVICE_FLAGS_ROTATIONAL_TRACKING) != 0; - position_tracking_supported = - (device_flags & OHMD_DEVICE_FLAGS_POSITIONAL_TRACKING) != 0; + orientation_tracking_supported = (device_flags & OHMD_DEVICE_FLAGS_ROTATIONAL_TRACKING) != 0; + position_tracking_supported = (device_flags & OHMD_DEVICE_FLAGS_POSITIONAL_TRACKING) != 0; break; } diff --git a/src/xrt/drivers/psmv/psmv_driver.c b/src/xrt/drivers/psmv/psmv_driver.c index b93fb7a8a..96098dda3 100644 --- a/src/xrt/drivers/psmv/psmv_driver.c +++ b/src/xrt/drivers/psmv/psmv_driver.c @@ -521,9 +521,7 @@ static int psmv_get_calibration(struct psmv_device *psmv); static int -psmv_parse_input(struct psmv_device *psmv, - void *data, - struct psmv_parsed_input *input); +psmv_parse_input(struct psmv_device *psmv, void *data, struct psmv_parsed_input *input); /* @@ -567,14 +565,10 @@ psmv_clamp_zero_to_one_float_to_u8(float v) } static void -psmv_update_input_click(struct psmv_device *psmv, - int index, - int64_t when_ns, - uint32_t bit) +psmv_update_input_click(struct psmv_device *psmv, int index, int64_t when_ns, uint32_t bit) { psmv->base.inputs[index].timestamp = when_ns; - psmv->base.inputs[index].value.boolean = - (psmv->last.buttons & bit) != 0; + psmv->base.inputs[index].value.boolean = (psmv->last.buttons & bit) != 0; } static void @@ -595,11 +589,8 @@ psmv_update_trigger_value(struct psmv_device *psmv, int index, int64_t when_ns) * Does the actual sending of the led control package to the device. */ static int -psmv_send_led_control_locked(volatile struct psmv_device *psmv, - uint8_t red, - uint8_t green, - uint8_t blue, - uint8_t rumble) +psmv_send_led_control_locked( + volatile struct psmv_device *psmv, uint8_t red, uint8_t green, uint8_t blue, uint8_t rumble) { struct psmv_set_led msg; U_ZERO(&msg); @@ -613,14 +604,11 @@ psmv_send_led_control_locked(volatile struct psmv_device *psmv, } static void -psmv_led_and_trigger_update_locked(volatile struct psmv_device *psmv, - int64_t time) +psmv_led_and_trigger_update_locked(volatile struct psmv_device *psmv, int64_t time) { // Need to keep sending led control packets to keep the leds on. - if (psmv->wants.resend_time > time && - psmv->state.led.r == psmv->wants.led.r && - psmv->state.led.g == psmv->wants.led.g && - psmv->state.led.b == psmv->wants.led.b && + if (psmv->wants.resend_time > time && psmv->state.led.r == psmv->wants.led.r && + psmv->state.led.g == psmv->wants.led.g && psmv->state.led.b == psmv->wants.led.b && psmv->state.rumble == psmv->wants.rumble) { return; } @@ -631,8 +619,7 @@ psmv_led_and_trigger_update_locked(volatile struct psmv_device *psmv, psmv->state.rumble = psmv->wants.rumble; psmv->wants.resend_time = time + 1000000000; - psmv_send_led_control_locked(psmv, psmv->state.led.r, psmv->state.led.g, - psmv->state.led.b, psmv->state.rumble); + psmv_send_led_control_locked(psmv, psmv->state.led.r, psmv->state.led.g, psmv->state.led.b, psmv->state.rumble); } static void @@ -657,8 +644,7 @@ update_fusion(struct psmv_device *psmv, struct xrt_vec3_i32 *ra = &sample->accel; struct xrt_vec3_i32 *rg = &sample->gyro; - m_imu_pre_filter_data(&psmv->calibration.prefilter, ra, rg, - &psmv->read.accel, &psmv->read.gyro); + m_imu_pre_filter_data(&psmv->calibration.prefilter, ra, rg, &psmv->read.accel, &psmv->read.gyro); if (psmv->ball != NULL) { // We have positional tracking @@ -675,15 +661,11 @@ update_fusion(struct psmv_device *psmv, math_quat_integrate_velocity( &psmv->fusion.rot, &psmv->read.gyro, dt, &psmv->fusion.rot); #else - imu_fusion_incorporate_gyros_and_accelerometer( - psmv->fusion.fusion, timestamp_ns, &psmv->read.gyro, - &psmv->fusion.variance.gyro, &psmv->read.accel, - &psmv->fusion.variance.accel, NULL); - imu_fusion_get_prediction(psmv->fusion.fusion, timestamp_ns, - &psmv->fusion.rot, - &psmv->fusion.angvel); - imu_fusion_get_prediction_rotation_vec( - psmv->fusion.fusion, timestamp_ns, &psmv->fusion.rotvec); + imu_fusion_incorporate_gyros_and_accelerometer(psmv->fusion.fusion, timestamp_ns, &psmv->read.gyro, + &psmv->fusion.variance.gyro, &psmv->read.accel, + &psmv->fusion.variance.accel, NULL); + imu_fusion_get_prediction(psmv->fusion.fusion, timestamp_ns, &psmv->fusion.rot, &psmv->fusion.angvel); + imu_fusion_get_prediction_rotation_vec(psmv->fusion.fusion, timestamp_ns, &psmv->fusion.rotvec); #endif } } @@ -765,11 +747,8 @@ psmv_run_thread(void *ptr) // Process the parsed data. if (num == 2) { // ZCM1 - update_fusion(psmv, &input.samples[0], - now_ns - (delta_ns / 2.0), - (delta_ns / 2.0)); - update_fusion(psmv, &input.samples[1], now_ns, - (delta_ns / 2.0)); + update_fusion(psmv, &input.samples[0], now_ns - (delta_ns / 2.0), (delta_ns / 2.0)); + update_fusion(psmv, &input.samples[1], now_ns, (delta_ns / 2.0)); psmv->last_timestamp_ns = now_ns; } else if (num == 1) { // ZCM2 @@ -804,15 +783,12 @@ psmv_get_fusion_pose(struct psmv_device *psmv, * device orientation is enough to get it into the right space, angular * velocity is a derivative so needs a special rotation. */ - math_quat_rotate_derivative(&psmv->fusion.rot, &psmv->fusion.angvel, - &out_relation->angular_velocity); + math_quat_rotate_derivative(&psmv->fusion.rot, &psmv->fusion.angvel, &out_relation->angular_velocity); //! @todo assuming that orientation is actually currently tracked. out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT | - XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT); + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | + XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT | XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT); } static void @@ -823,8 +799,7 @@ psmv_add_pose_offset(enum xrt_input_name name, struct xrt_space_graph *xsg) * body center pose, while the aim pose needs to rotated and translated * to the tip of the ball. */ - if (name != XRT_INPUT_PSMV_AIM_POSE && - name != XRT_INPUT_PSMV_GRIP_POSE) { + if (name != XRT_INPUT_PSMV_AIM_POSE && name != XRT_INPUT_PSMV_GRIP_POSE) { return; } @@ -920,8 +895,7 @@ psmv_device_get_space_graph(struct xrt_device *xdev, struct xrt_space_relation *rel = m_space_graph_reserve(xgs); if (psmv->ball != NULL) { - xrt_tracked_psmv_get_tracked_pose(psmv->ball, name, - at_timestamp_ns, rel); + xrt_tracked_psmv_get_tracked_pose(psmv->ball, name, at_timestamp_ns, rel); } else { psmv_get_fusion_pose(psmv, name, at_timestamp_ns, rel); } @@ -957,9 +931,7 @@ amp_scale(struct psmv_device *psmv, float amp) } static void -psmv_device_set_output(struct xrt_device *xdev, - enum xrt_output_name name, - union xrt_output_value *value) +psmv_device_set_output(struct xrt_device *xdev, enum xrt_output_name name, union xrt_output_value *value) { struct psmv_device *psmv = psmv_device(xdev); @@ -1018,8 +990,7 @@ static struct xrt_binding_profile binding_profiles[1] = { * */ -#define SET_INPUT(NAME) \ - (psmv->base.inputs[PSMV_INDEX_##NAME].name = XRT_INPUT_PSMV_##NAME) +#define SET_INPUT(NAME) (psmv->base.inputs[PSMV_INDEX_##NAME].name = XRT_INPUT_PSMV_##NAME) int psmv_found(struct xrt_prober *xp, @@ -1050,8 +1021,7 @@ psmv_found(struct xrt_prober *xp, } enum u_device_alloc_flags flags = U_DEVICE_ALLOC_TRACKING_NONE; - struct psmv_device *psmv = - U_DEVICE_ALLOCATE(struct psmv_device, flags, 13, 1); + struct psmv_device *psmv = U_DEVICE_ALLOCATE(struct psmv_device, flags, 13, 1); psmv->base.destroy = psmv_device_destroy; psmv->base.update_inputs = psmv_device_update_inputs; psmv->base.get_tracked_pose = psmv_device_get_tracked_pose; @@ -1064,8 +1034,7 @@ psmv_found(struct xrt_prober *xp, psmv->log_level = debug_get_log_option_psmv_log(); psmv->pid = devices[index]->product_id; psmv->hid = hid; - snprintf(psmv->base.str, XRT_DEVICE_NAME_LEN, "%s", - "PS Move Controller"); + snprintf(psmv->base.str, XRT_DEVICE_NAME_LEN, "%s", "PS Move Controller"); m_imu_pre_filter_init(&psmv->calibration.prefilter, 1.f, 1.f); @@ -1141,8 +1110,7 @@ psmv_found(struct xrt_prober *xp, float diameter = PSMV_BALL_DIAMETER_M; (void)diameter; if (xp->tracking != NULL) { - xp->tracking->create_tracked_psmv(xp->tracking, &psmv->base, - &psmv->ball); + xp->tracking->create_tracked_psmv(xp->tracking, &psmv->base, &psmv->ball); } #endif @@ -1152,12 +1120,9 @@ psmv_found(struct xrt_prober *xp, // We got a tracked ball, use it. psmv->base.tracking_origin = psmv->ball->origin; - psmv->wants.led.r = - psmv_clamp_zero_to_one_float_to_u8(psmv->ball->colour.r); - psmv->wants.led.g = - psmv_clamp_zero_to_one_float_to_u8(psmv->ball->colour.g); - psmv->wants.led.b = - psmv_clamp_zero_to_one_float_to_u8(psmv->ball->colour.b); + psmv->wants.led.r = psmv_clamp_zero_to_one_float_to_u8(psmv->ball->colour.r); + psmv->wants.led.g = psmv_clamp_zero_to_one_float_to_u8(psmv->ball->colour.g); + psmv->wants.led.b = psmv_clamp_zero_to_one_float_to_u8(psmv->ball->colour.b); } else { // Failed to create a tracking ball. @@ -1270,8 +1235,7 @@ psmv_i32_from_i16_wire(int32_t *to, const struct psmv_i16_wire *from) } static void -psmv_from_vec3_u16_wire(struct xrt_vec3_i32 *to, - const struct psmv_vec3_u16_wire *from) +psmv_from_vec3_u16_wire(struct xrt_vec3_i32 *to, const struct psmv_vec3_u16_wire *from) { psmv_i32_from_u16_wire(&to->x, &from->x); psmv_i32_from_u16_wire(&to->y, &from->y); @@ -1279,8 +1243,7 @@ psmv_from_vec3_u16_wire(struct xrt_vec3_i32 *to, } static void -psmv_from_vec3_i16_wire(struct xrt_vec3_i32 *to, - const struct psmv_vec3_i16_wire *from) +psmv_from_vec3_i16_wire(struct xrt_vec3_i32 *to, const struct psmv_vec3_i16_wire *from) { psmv_i32_from_i16_wire(&to->x, &from->x); psmv_i32_from_i16_wire(&to->y, &from->y); @@ -1295,14 +1258,12 @@ psmv_f32_from_wire(float *to, const struct psmv_f32_wire *from) float f32; } safe_copy; - safe_copy.wire = (from->val[0] << 0) | (from->val[1] << 8) | - (from->val[2] << 16) | (from->val[3] << 24); + safe_copy.wire = (from->val[0] << 0) | (from->val[1] << 8) | (from->val[2] << 16) | (from->val[3] << 24); *to = safe_copy.f32; } static void -psmv_from_vec3_f32_wire(struct xrt_vec3 *to, - const struct psmv_vec3_f32_wire *from) +psmv_from_vec3_f32_wire(struct xrt_vec3 *to, const struct psmv_vec3_f32_wire *from) { psmv_f32_from_wire(&to->x, &from->x); psmv_f32_from_wire(&to->y, &from->y); @@ -1338,8 +1299,7 @@ psmv_get_calibration_zcm1(struct psmv_device *psmv) } if (ret != (int)sizeof(part)) { - PSMV_ERROR(psmv, "Size wrong: %i != %i", ret, - (int)sizeof(part)); + PSMV_ERROR(psmv, "Size wrong: %i != %i", ret, (int)sizeof(part)); return -1; } @@ -1356,13 +1316,10 @@ psmv_get_calibration_zcm1(struct psmv_device *psmv) src_offset = 2; dst_offset = sizeof(part) * 2 - 2; break; - default: - PSMV_ERROR(psmv, "Unexpected part id! %i", part.which); - return -1; + default: PSMV_ERROR(psmv, "Unexpected part id! %i", part.which); return -1; } - memcpy(dst + dst_offset, src + src_offset, - sizeof(part) - src_offset); + memcpy(dst + dst_offset, src + src_offset, sizeof(part) - src_offset); } psmv_from_vec3_u16_wire(&zcm1->accel_min_x, &data.accel_min_x); @@ -1395,45 +1352,33 @@ psmv_get_calibration_zcm1(struct psmv_device *psmv) */ psmv->calibration.prefilter.accel.gain.x = - MATH_GRAVITY_M_S2 / - ((zcm1->accel_max_x.x - zcm1->accel_min_x.x) / 2.0); + MATH_GRAVITY_M_S2 / ((zcm1->accel_max_x.x - zcm1->accel_min_x.x) / 2.0); psmv->calibration.prefilter.accel.gain.y = - MATH_GRAVITY_M_S2 / - ((zcm1->accel_max_y.y - zcm1->accel_min_y.y) / 2.0); + MATH_GRAVITY_M_S2 / ((zcm1->accel_max_y.y - zcm1->accel_min_y.y) / 2.0); psmv->calibration.prefilter.accel.gain.z = - MATH_GRAVITY_M_S2 / - ((zcm1->accel_max_z.z - zcm1->accel_min_z.z) / 2.0); - - psmv->calibration.prefilter.accel.bias.x = - (zcm1->accel_min_x.x + zcm1->accel_max_x.x + zcm1->accel_min_y.x + - zcm1->accel_max_y.x + zcm1->accel_min_z.x + zcm1->accel_max_z.x) / - 6.0; - psmv->calibration.prefilter.accel.bias.y = - (zcm1->accel_min_x.y + zcm1->accel_max_x.y + zcm1->accel_min_y.y + - zcm1->accel_max_y.y + zcm1->accel_min_z.y + zcm1->accel_max_z.y) / - 6.0; - psmv->calibration.prefilter.accel.bias.z = - (zcm1->accel_min_x.z + zcm1->accel_max_x.z + zcm1->accel_min_y.z + - zcm1->accel_max_y.z + zcm1->accel_min_z.z + zcm1->accel_max_z.z) / - 6.0; + MATH_GRAVITY_M_S2 / ((zcm1->accel_max_z.z - zcm1->accel_min_z.z) / 2.0); + + psmv->calibration.prefilter.accel.bias.x = (zcm1->accel_min_x.x + zcm1->accel_max_x.x + zcm1->accel_min_y.x + + zcm1->accel_max_y.x + zcm1->accel_min_z.x + zcm1->accel_max_z.x) / + 6.0; + psmv->calibration.prefilter.accel.bias.y = (zcm1->accel_min_x.y + zcm1->accel_max_x.y + zcm1->accel_min_y.y + + zcm1->accel_max_y.y + zcm1->accel_min_z.y + zcm1->accel_max_z.y) / + 6.0; + psmv->calibration.prefilter.accel.bias.z = (zcm1->accel_min_x.z + zcm1->accel_max_x.z + zcm1->accel_min_y.z + + zcm1->accel_max_y.z + zcm1->accel_min_z.z + zcm1->accel_max_z.z) / + 6.0; /* * Gyro */ - double gx = - (zcm1->gyro_rot_x.x - (zcm1->gyro_bias_0.x * zcm1->gyro_fact.x)); - double gy = - (zcm1->gyro_rot_y.y - (zcm1->gyro_bias_0.y * zcm1->gyro_fact.y)); - double gz = - (zcm1->gyro_rot_z.z - (zcm1->gyro_bias_0.z * zcm1->gyro_fact.z)); - - psmv->calibration.prefilter.gyro.gain.x = - (2.0 * M_PI * 80.0) / (60.0 * gx); - psmv->calibration.prefilter.gyro.gain.y = - (2.0 * M_PI * 80.0) / (60.0 * gy); - psmv->calibration.prefilter.gyro.gain.z = - (2.0 * M_PI * 80.0) / (60.0 * gz); + double gx = (zcm1->gyro_rot_x.x - (zcm1->gyro_bias_0.x * zcm1->gyro_fact.x)); + double gy = (zcm1->gyro_rot_y.y - (zcm1->gyro_bias_0.y * zcm1->gyro_fact.y)); + double gz = (zcm1->gyro_rot_z.z - (zcm1->gyro_bias_0.z * zcm1->gyro_fact.z)); + + psmv->calibration.prefilter.gyro.gain.x = (2.0 * M_PI * 80.0) / (60.0 * gx); + psmv->calibration.prefilter.gyro.gain.y = (2.0 * M_PI * 80.0) / (60.0 * gy); + psmv->calibration.prefilter.gyro.gain.z = (2.0 * M_PI * 80.0) / (60.0 * gz); psmv->calibration.prefilter.gyro.bias.x = 0.0; psmv->calibration.prefilter.gyro.bias.y = 0.0; psmv->calibration.prefilter.gyro.bias.z = 0.0; @@ -1467,40 +1412,26 @@ psmv_get_calibration_zcm1(struct psmv_device *psmv) "\t\taccel.bias: %f %f %f\n" "\t\tgyro.gain: %f %f %f\n" "\t\tgyro.bias: %f %f %f\n", - zcm1->accel_min_x.x, zcm1->accel_min_x.y, zcm1->accel_min_x.z, - zcm1->accel_max_x.x, zcm1->accel_max_x.y, zcm1->accel_max_x.z, - zcm1->accel_min_y.x, zcm1->accel_min_y.y, zcm1->accel_min_y.z, - zcm1->accel_max_y.x, zcm1->accel_max_y.y, zcm1->accel_max_y.z, - zcm1->accel_min_z.x, zcm1->accel_min_z.y, zcm1->accel_min_z.z, - zcm1->accel_max_z.x, zcm1->accel_max_z.y, zcm1->accel_max_z.z, - zcm1->gyro_rot_x.x, zcm1->gyro_rot_x.y, zcm1->gyro_rot_x.z, - zcm1->gyro_rot_y.x, zcm1->gyro_rot_y.y, zcm1->gyro_rot_y.z, - zcm1->gyro_rot_z.x, zcm1->gyro_rot_z.y, zcm1->gyro_rot_z.z, - zcm1->gyro_bias_0.x, zcm1->gyro_bias_0.y, zcm1->gyro_bias_0.z, - zcm1->gyro_bias_1.x, zcm1->gyro_bias_1.y, zcm1->gyro_bias_1.z, - zcm1->gyro_fact.x, zcm1->gyro_fact.y, zcm1->gyro_fact.z, - zcm1->unknown_vec3.x, zcm1->unknown_vec3.y, zcm1->unknown_vec3.z, - zcm1->unknown_float_0, zcm1->unknown_float_1, - psmv->calibration.prefilter.accel.gain.x, - psmv->calibration.prefilter.accel.gain.y, - psmv->calibration.prefilter.accel.gain.z, - psmv->calibration.prefilter.accel.bias.x, - psmv->calibration.prefilter.accel.bias.y, - psmv->calibration.prefilter.accel.bias.z, - psmv->calibration.prefilter.gyro.gain.x, - psmv->calibration.prefilter.gyro.gain.y, - psmv->calibration.prefilter.gyro.gain.z, - psmv->calibration.prefilter.gyro.bias.x, - psmv->calibration.prefilter.gyro.bias.y, - psmv->calibration.prefilter.gyro.bias.z); + zcm1->accel_min_x.x, zcm1->accel_min_x.y, zcm1->accel_min_x.z, zcm1->accel_max_x.x, zcm1->accel_max_x.y, + zcm1->accel_max_x.z, zcm1->accel_min_y.x, zcm1->accel_min_y.y, zcm1->accel_min_y.z, zcm1->accel_max_y.x, + zcm1->accel_max_y.y, zcm1->accel_max_y.z, zcm1->accel_min_z.x, zcm1->accel_min_z.y, zcm1->accel_min_z.z, + zcm1->accel_max_z.x, zcm1->accel_max_z.y, zcm1->accel_max_z.z, zcm1->gyro_rot_x.x, zcm1->gyro_rot_x.y, + zcm1->gyro_rot_x.z, zcm1->gyro_rot_y.x, zcm1->gyro_rot_y.y, zcm1->gyro_rot_y.z, zcm1->gyro_rot_z.x, + zcm1->gyro_rot_z.y, zcm1->gyro_rot_z.z, zcm1->gyro_bias_0.x, zcm1->gyro_bias_0.y, zcm1->gyro_bias_0.z, + zcm1->gyro_bias_1.x, zcm1->gyro_bias_1.y, zcm1->gyro_bias_1.z, zcm1->gyro_fact.x, zcm1->gyro_fact.y, + zcm1->gyro_fact.z, zcm1->unknown_vec3.x, zcm1->unknown_vec3.y, zcm1->unknown_vec3.z, zcm1->unknown_float_0, + zcm1->unknown_float_1, psmv->calibration.prefilter.accel.gain.x, psmv->calibration.prefilter.accel.gain.y, + psmv->calibration.prefilter.accel.gain.z, psmv->calibration.prefilter.accel.bias.x, + psmv->calibration.prefilter.accel.bias.y, psmv->calibration.prefilter.accel.bias.z, + psmv->calibration.prefilter.gyro.gain.x, psmv->calibration.prefilter.gyro.gain.y, + psmv->calibration.prefilter.gyro.gain.z, psmv->calibration.prefilter.gyro.bias.x, + psmv->calibration.prefilter.gyro.bias.y, psmv->calibration.prefilter.gyro.bias.z); return 0; } static int -psmv_parse_input_zcm1(struct psmv_device *psmv, - struct psmv_input_zcm1 *data, - struct psmv_parsed_input *input) +psmv_parse_input_zcm1(struct psmv_device *psmv, struct psmv_input_zcm1 *data, struct psmv_parsed_input *input) { input->battery = data->battery; input->seq_no = data->buttons[3] & 0x0f; @@ -1523,8 +1454,7 @@ psmv_parse_input_zcm1(struct psmv_device *psmv, psmv_from_vec3_u16_wire(&input->samples[1].accel, &data->accel_f2); psmv_from_vec3_u16_wire(&input->samples[1].gyro, &data->gyro_f2); - uint32_t diff = psmv_calc_delta_and_handle_rollover( - input->timestamp, psmv->last.timestamp); + uint32_t diff = psmv_calc_delta_and_handle_rollover(input->timestamp, psmv->last.timestamp); bool missed = input->seq_no != ((psmv->last.seq_no + 1) & 0x0f); @@ -1546,15 +1476,12 @@ psmv_parse_input_zcm1(struct psmv_device *psmv, "timestamp: %i\n\t" "diff: %i\n\t" "seq_no: %x\n", - missed ? "yes" : "no", input->buttons, input->battery, - input->samples[0].accel.x, input->samples[0].accel.y, - input->samples[0].accel.z, input->samples[1].accel.x, - input->samples[1].accel.y, input->samples[1].accel.z, - input->samples[0].gyro.x, input->samples[0].gyro.y, - input->samples[0].gyro.z, input->samples[1].gyro.x, - input->samples[1].gyro.y, input->samples[1].gyro.z, - input->trigger_values[0], input->trigger_values[1], - input->timestamp, diff, input->seq_no); + missed ? "yes" : "no", input->buttons, input->battery, input->samples[0].accel.x, + input->samples[0].accel.y, input->samples[0].accel.z, input->samples[1].accel.x, + input->samples[1].accel.y, input->samples[1].accel.z, input->samples[0].gyro.x, + input->samples[0].gyro.y, input->samples[0].gyro.z, input->samples[1].gyro.x, + input->samples[1].gyro.y, input->samples[1].gyro.z, input->trigger_values[0], + input->trigger_values[1], input->timestamp, diff, input->seq_no); return 2; } @@ -1588,8 +1515,7 @@ psmv_get_calibration_zcm2(struct psmv_device *psmv) } if (ret != (int)sizeof(part)) { - PSMV_ERROR(psmv, "Size wrong: %i != %i", ret, - (int)sizeof(part)); + PSMV_ERROR(psmv, "Size wrong: %i != %i", ret, (int)sizeof(part)); return -1; } @@ -1602,13 +1528,10 @@ psmv_get_calibration_zcm2(struct psmv_device *psmv) src_offset = 2; dst_offset = sizeof(part); break; - default: - PSMV_ERROR(psmv, "Unexpected part id! %i", part.which); - return -1; + default: PSMV_ERROR(psmv, "Unexpected part id! %i", part.which); return -1; } - memcpy(dst + dst_offset, src + src_offset, - sizeof(part) - src_offset); + memcpy(dst + dst_offset, src + src_offset, sizeof(part) - src_offset); } psmv_from_vec3_i16_wire(&zcm2->accel_min_x, &data.accel_min_x); @@ -1632,27 +1555,21 @@ psmv_get_calibration_zcm2(struct psmv_device *psmv) */ psmv->calibration.prefilter.accel.gain.x = - MATH_GRAVITY_M_S2 / - ((zcm2->accel_max_x.x - zcm2->accel_min_x.x) / 2.0); + MATH_GRAVITY_M_S2 / ((zcm2->accel_max_x.x - zcm2->accel_min_x.x) / 2.0); psmv->calibration.prefilter.accel.gain.y = - MATH_GRAVITY_M_S2 / - ((zcm2->accel_max_y.y - zcm2->accel_min_y.y) / 2.0); + MATH_GRAVITY_M_S2 / ((zcm2->accel_max_y.y - zcm2->accel_min_y.y) / 2.0); psmv->calibration.prefilter.accel.gain.z = - MATH_GRAVITY_M_S2 / - ((zcm2->accel_max_z.z - zcm2->accel_min_z.z) / 2.0); - - psmv->calibration.prefilter.accel.bias.x = - (zcm2->accel_min_x.x + zcm2->accel_max_x.x + zcm2->accel_min_y.x + - zcm2->accel_max_y.x + zcm2->accel_min_z.x + zcm2->accel_max_z.x) / - 6.0; - psmv->calibration.prefilter.accel.bias.y = - (zcm2->accel_min_x.y + zcm2->accel_max_x.y + zcm2->accel_min_y.y + - zcm2->accel_max_y.y + zcm2->accel_min_z.y + zcm2->accel_max_z.y) / - 6.0; - psmv->calibration.prefilter.accel.bias.z = - (zcm2->accel_min_x.z + zcm2->accel_max_x.z + zcm2->accel_min_y.z + - zcm2->accel_max_y.z + zcm2->accel_min_z.z + zcm2->accel_max_z.z) / - 6.0; + MATH_GRAVITY_M_S2 / ((zcm2->accel_max_z.z - zcm2->accel_min_z.z) / 2.0); + + psmv->calibration.prefilter.accel.bias.x = (zcm2->accel_min_x.x + zcm2->accel_max_x.x + zcm2->accel_min_y.x + + zcm2->accel_max_y.x + zcm2->accel_min_z.x + zcm2->accel_max_z.x) / + 6.0; + psmv->calibration.prefilter.accel.bias.y = (zcm2->accel_min_x.y + zcm2->accel_max_x.y + zcm2->accel_min_y.y + + zcm2->accel_max_y.y + zcm2->accel_min_z.y + zcm2->accel_max_z.y) / + 6.0; + psmv->calibration.prefilter.accel.bias.z = (zcm2->accel_min_x.z + zcm2->accel_max_x.z + zcm2->accel_min_y.z + + zcm2->accel_max_y.z + zcm2->accel_min_z.z + zcm2->accel_max_z.z) / + 6.0; /* @@ -1663,12 +1580,9 @@ psmv_get_calibration_zcm2(struct psmv_device *psmv) double gy = (zcm2->gyro_pos_y.y - zcm2->gyro_neg_y.y) / 2.0; double gz = (zcm2->gyro_pos_z.z - zcm2->gyro_neg_z.z) / 2.0; - psmv->calibration.prefilter.gyro.gain.x = - (2.0 * M_PI * 90.0) / (60.0 * gx); - psmv->calibration.prefilter.gyro.gain.y = - (2.0 * M_PI * 90.0) / (60.0 * gy); - psmv->calibration.prefilter.gyro.gain.z = - (2.0 * M_PI * 90.0) / (60.0 * gz); + psmv->calibration.prefilter.gyro.gain.x = (2.0 * M_PI * 90.0) / (60.0 * gx); + psmv->calibration.prefilter.gyro.gain.y = (2.0 * M_PI * 90.0) / (60.0 * gy); + psmv->calibration.prefilter.gyro.gain.z = (2.0 * M_PI * 90.0) / (60.0 * gz); #if 0 psmv->calibration.prefilter.gyro.bias.x = @@ -1694,61 +1608,48 @@ psmv_get_calibration_zcm2(struct psmv_device *psmv) * Print */ - PSMV_DEBUG( - psmv, - "\n" - "\tCalibration:\n" - "\t\taccel_min_x: %6i %6i %6i\n" - "\t\taccel_max_x: %6i %6i %6i\n" - "\t\taccel_min_y: %6i %6i %6i\n" - "\t\taccel_max_y: %6i %6i %6i\n" - "\t\taccel_min_z: %6i %6i %6i\n" - "\t\taccel_max_z: %6i %6i %6i\n" - "\t\tgyro_neg_x: %6i %6i %6i\n" - "\t\tgyro_pos_x: %6i %6i %6i\n" - "\t\tgyro_neg_y: %6i %6i %6i\n" - "\t\tgyro_pos_y: %6i %6i %6i\n" - "\t\tgyro_neg_z: %6i %6i %6i\n" - "\t\tgyro_pos_z: %6i %6i %6i\n" - "\t\tgyro_bias: %6i %6i %6i\n" - "\tCalculated:\n" - "\t\taccel.gain: %f %f %f\n" - "\t\taccel.bias: %f %f %f\n" - "\t\tgyro.gain: %f %f %f\n" - "\t\tgyro.bias: %f %f %f\n", - zcm2->accel_min_x.x, zcm2->accel_min_x.y, zcm2->accel_min_x.z, - zcm2->accel_max_x.x, zcm2->accel_max_x.y, zcm2->accel_max_x.z, - zcm2->accel_min_y.x, zcm2->accel_min_y.y, zcm2->accel_min_y.z, - zcm2->accel_max_y.x, zcm2->accel_max_y.y, zcm2->accel_max_y.z, - zcm2->accel_min_z.x, zcm2->accel_min_z.y, zcm2->accel_min_z.z, - zcm2->accel_max_z.x, zcm2->accel_max_z.y, zcm2->accel_max_z.z, - zcm2->gyro_neg_x.x, zcm2->gyro_neg_x.y, zcm2->gyro_neg_x.z, - zcm2->gyro_pos_x.x, zcm2->gyro_pos_x.y, zcm2->gyro_pos_x.z, - zcm2->gyro_neg_y.x, zcm2->gyro_neg_y.y, zcm2->gyro_neg_y.z, - zcm2->gyro_pos_y.x, zcm2->gyro_pos_y.y, zcm2->gyro_pos_y.z, - zcm2->gyro_neg_z.x, zcm2->gyro_neg_z.y, zcm2->gyro_neg_z.z, - zcm2->gyro_pos_z.x, zcm2->gyro_pos_z.y, zcm2->gyro_pos_z.z, - zcm2->gyro_bias.x, zcm2->gyro_bias.y, zcm2->gyro_bias.z, - psmv->calibration.prefilter.accel.gain.x, - psmv->calibration.prefilter.accel.gain.y, - psmv->calibration.prefilter.accel.gain.z, - psmv->calibration.prefilter.accel.bias.x, - psmv->calibration.prefilter.accel.bias.y, - psmv->calibration.prefilter.accel.bias.z, - psmv->calibration.prefilter.gyro.gain.x, - psmv->calibration.prefilter.gyro.gain.y, - psmv->calibration.prefilter.gyro.gain.z, - psmv->calibration.prefilter.gyro.bias.x, - psmv->calibration.prefilter.gyro.bias.y, - psmv->calibration.prefilter.gyro.bias.z); + PSMV_DEBUG(psmv, + "\n" + "\tCalibration:\n" + "\t\taccel_min_x: %6i %6i %6i\n" + "\t\taccel_max_x: %6i %6i %6i\n" + "\t\taccel_min_y: %6i %6i %6i\n" + "\t\taccel_max_y: %6i %6i %6i\n" + "\t\taccel_min_z: %6i %6i %6i\n" + "\t\taccel_max_z: %6i %6i %6i\n" + "\t\tgyro_neg_x: %6i %6i %6i\n" + "\t\tgyro_pos_x: %6i %6i %6i\n" + "\t\tgyro_neg_y: %6i %6i %6i\n" + "\t\tgyro_pos_y: %6i %6i %6i\n" + "\t\tgyro_neg_z: %6i %6i %6i\n" + "\t\tgyro_pos_z: %6i %6i %6i\n" + "\t\tgyro_bias: %6i %6i %6i\n" + "\tCalculated:\n" + "\t\taccel.gain: %f %f %f\n" + "\t\taccel.bias: %f %f %f\n" + "\t\tgyro.gain: %f %f %f\n" + "\t\tgyro.bias: %f %f %f\n", + zcm2->accel_min_x.x, zcm2->accel_min_x.y, zcm2->accel_min_x.z, zcm2->accel_max_x.x, + zcm2->accel_max_x.y, zcm2->accel_max_x.z, zcm2->accel_min_y.x, zcm2->accel_min_y.y, + zcm2->accel_min_y.z, zcm2->accel_max_y.x, zcm2->accel_max_y.y, zcm2->accel_max_y.z, + zcm2->accel_min_z.x, zcm2->accel_min_z.y, zcm2->accel_min_z.z, zcm2->accel_max_z.x, + zcm2->accel_max_z.y, zcm2->accel_max_z.z, zcm2->gyro_neg_x.x, zcm2->gyro_neg_x.y, zcm2->gyro_neg_x.z, + zcm2->gyro_pos_x.x, zcm2->gyro_pos_x.y, zcm2->gyro_pos_x.z, zcm2->gyro_neg_y.x, zcm2->gyro_neg_y.y, + zcm2->gyro_neg_y.z, zcm2->gyro_pos_y.x, zcm2->gyro_pos_y.y, zcm2->gyro_pos_y.z, zcm2->gyro_neg_z.x, + zcm2->gyro_neg_z.y, zcm2->gyro_neg_z.z, zcm2->gyro_pos_z.x, zcm2->gyro_pos_z.y, zcm2->gyro_pos_z.z, + zcm2->gyro_bias.x, zcm2->gyro_bias.y, zcm2->gyro_bias.z, psmv->calibration.prefilter.accel.gain.x, + psmv->calibration.prefilter.accel.gain.y, psmv->calibration.prefilter.accel.gain.z, + psmv->calibration.prefilter.accel.bias.x, psmv->calibration.prefilter.accel.bias.y, + psmv->calibration.prefilter.accel.bias.z, psmv->calibration.prefilter.gyro.gain.x, + psmv->calibration.prefilter.gyro.gain.y, psmv->calibration.prefilter.gyro.gain.z, + psmv->calibration.prefilter.gyro.bias.x, psmv->calibration.prefilter.gyro.bias.y, + psmv->calibration.prefilter.gyro.bias.z); return 0; } static int -psmv_parse_input_zcm2(struct psmv_device *psmv, - struct psmv_input_zcm2 *data, - struct psmv_parsed_input *input) +psmv_parse_input_zcm2(struct psmv_device *psmv, struct psmv_input_zcm2 *data, struct psmv_parsed_input *input) { input->battery = data->battery; input->seq_no = data->buttons[3] & 0x0f; @@ -1773,8 +1674,7 @@ psmv_parse_input_zcm2(struct psmv_device *psmv, psmv_from_vec3_i16_wire(&input->sample_copy.accel, &data->accel_copy); psmv_from_vec3_i16_wire(&input->sample_copy.gyro, &data->gyro_copy); - uint32_t diff = psmv_calc_delta_and_handle_rollover( - input->timestamp, psmv->last.timestamp); + uint32_t diff = psmv_calc_delta_and_handle_rollover(input->timestamp, psmv->last.timestamp); bool missed = input->seq_no != ((psmv->last.seq_no + 1) & 0x0f); @@ -1797,15 +1697,12 @@ psmv_parse_input_zcm2(struct psmv_device *psmv, "timestamp_copy: %04x\n\t" "diff: %i\n\t" "seq_no: %x\n", - missed ? "yes" : "no", input->buttons, input->battery, - input->samples[0].accel.x, input->samples[0].accel.y, - input->samples[0].accel.z, input->samples[1].accel.x, - input->samples[1].accel.y, input->samples[1].accel.z, - input->samples[0].gyro.x, input->samples[0].gyro.y, - input->samples[0].gyro.z, input->samples[1].gyro.x, - input->samples[1].gyro.y, input->samples[1].gyro.z, - input->trigger_low_pass, input->trigger, input->timestamp, - input->timestamp_copy, diff, input->seq_no); + missed ? "yes" : "no", input->buttons, input->battery, input->samples[0].accel.x, + input->samples[0].accel.y, input->samples[0].accel.z, input->samples[1].accel.x, + input->samples[1].accel.y, input->samples[1].accel.z, input->samples[0].gyro.x, + input->samples[0].gyro.y, input->samples[0].gyro.z, input->samples[1].gyro.x, + input->samples[1].gyro.y, input->samples[1].gyro.z, input->trigger_low_pass, input->trigger, + input->timestamp, input->timestamp_copy, diff, input->seq_no); return 1; } @@ -1830,19 +1727,13 @@ psmv_get_calibration(struct psmv_device *psmv) } static int -psmv_parse_input(struct psmv_device *psmv, - void *data, - struct psmv_parsed_input *input) +psmv_parse_input(struct psmv_device *psmv, void *data, struct psmv_parsed_input *input) { U_ZERO(input); switch (psmv->pid) { - case PSMV_PID_ZCM1: - return psmv_parse_input_zcm1( - psmv, (struct psmv_input_zcm1 *)data, input); - case PSMV_PID_ZCM2: - return psmv_parse_input_zcm2( - psmv, (struct psmv_input_zcm2 *)data, input); + case PSMV_PID_ZCM1: return psmv_parse_input_zcm1(psmv, (struct psmv_input_zcm1 *)data, input); + case PSMV_PID_ZCM2: return psmv_parse_input_zcm2(psmv, (struct psmv_input_zcm2 *)data, input); default: return 0; } } diff --git a/src/xrt/drivers/psvr/psvr_device.c b/src/xrt/drivers/psvr/psvr_device.c index da003cd02..6918b4aaa 100644 --- a/src/xrt/drivers/psvr/psvr_device.c +++ b/src/xrt/drivers/psvr/psvr_device.c @@ -172,8 +172,7 @@ enum psvr_leds PSVR_LED_H = (1 << 7), PSVR_LED_I = (1 << 8), - PSVR_LED_FRONT = PSVR_LED_A | PSVR_LED_B | PSVR_LED_C | PSVR_LED_D | - PSVR_LED_E | PSVR_LED_F | PSVR_LED_G, + PSVR_LED_FRONT = PSVR_LED_A | PSVR_LED_B | PSVR_LED_C | PSVR_LED_D | PSVR_LED_E | PSVR_LED_F | PSVR_LED_G, PSVR_LED_BACK = PSVR_LED_H | PSVR_LED_I, @@ -194,9 +193,7 @@ psvr_device(struct xrt_device *p) } static int -open_hid(struct psvr_device *p, - struct hid_device_info *dev_info, - hid_device **out_dev) +open_hid(struct psvr_device *p, struct hid_device_info *dev_info, hid_device **out_dev) { hid_device *dev = NULL; int ret; @@ -269,22 +266,13 @@ read_sample_and_apply_calibration(struct psvr_device *psvr, raw_gyro.z * 0.00105f, }; - float ax = 2.0 / (psvr->calibration.accel_pos_x.x - - psvr->calibration.accel_neg_x.x); - float ay = 2.0 / (psvr->calibration.accel_pos_y.y - - psvr->calibration.accel_neg_y.y); - float az = 2.0 / (psvr->calibration.accel_pos_z.z - - psvr->calibration.accel_neg_z.z); - - float ox = (psvr->calibration.accel_pos_x.x + - psvr->calibration.accel_neg_x.x) / - 2.0; - float oy = (psvr->calibration.accel_pos_y.y + - psvr->calibration.accel_neg_y.y) / - 2.0; - float oz = (psvr->calibration.accel_pos_z.z + - psvr->calibration.accel_neg_z.z) / - 2.0; + float ax = 2.0 / (psvr->calibration.accel_pos_x.x - psvr->calibration.accel_neg_x.x); + float ay = 2.0 / (psvr->calibration.accel_pos_y.y - psvr->calibration.accel_neg_y.y); + float az = 2.0 / (psvr->calibration.accel_pos_z.z - psvr->calibration.accel_neg_z.z); + + float ox = (psvr->calibration.accel_pos_x.x + psvr->calibration.accel_neg_x.x) / 2.0; + float oy = (psvr->calibration.accel_pos_y.y + psvr->calibration.accel_neg_y.y) / 2.0; + float oz = (psvr->calibration.accel_pos_z.z + psvr->calibration.accel_neg_z.z) / 2.0; accel.x -= ox; accel.y -= oy; @@ -316,8 +304,7 @@ update_fusion(struct psvr_device *psvr, struct xrt_vec3 mag = {0.0f, 0.0f, 0.0f}; (void)mag; - read_sample_and_apply_calibration(psvr, sample, &psvr->read.accel, - &psvr->read.gyro); + read_sample_and_apply_calibration(psvr, sample, &psvr->read.accel, &psvr->read.gyro); if (psvr->tracker != NULL) { struct xrt_tracking_sample sample; @@ -328,14 +315,11 @@ update_fusion(struct psvr_device *psvr, } else { #if 1 timepoint_ns now = os_monotonic_get_ns(); - m_imu_3dof_update(&psvr->fusion, now, &psvr->read.accel, - &psvr->read.gyro); + m_imu_3dof_update(&psvr->fusion, now, &psvr->read.accel, &psvr->read.gyro); #else float delta_secs = tick_delta / PSVR_TICKS_PER_SECOND; - math_quat_integrate_velocity(&psvr->fusion.rot, - &psvr->read.gyro, delta_secs, - &psvr->fusion.rot); + math_quat_integrate_velocity(&psvr->fusion.rot, &psvr->read.gyro, delta_secs, &psvr->fusion.rot); #endif } } @@ -355,9 +339,7 @@ calc_delta_and_handle_rollover(uint32_t next, uint32_t last) } static void -handle_tracker_sensor_msg(struct psvr_device *psvr, - unsigned char *buffer, - int size) +handle_tracker_sensor_msg(struct psvr_device *psvr, unsigned char *buffer, int size) { timepoint_ns now = os_monotonic_get_ns(); uint32_t last_sample_tick = psvr->last.samples[1].tick; @@ -375,8 +357,7 @@ handle_tracker_sensor_msg(struct psvr_device *psvr, // Startup correction, ignore last_sample_tick if zero. if (last_sample_tick > 0) { - tick_delta = calc_delta_and_handle_rollover(s->samples[0].tick, - last_sample_tick); + tick_delta = calc_delta_and_handle_rollover(s->samples[0].tick, last_sample_tick); // The PSVR device can buffer sensor data from previous // sessions which we can get at the start of new sessions. @@ -388,14 +369,11 @@ handle_tracker_sensor_msg(struct psvr_device *psvr, } } // New delta between the two samples. - uint32_t tick_delta2 = calc_delta_and_handle_rollover( - s->samples[1].tick, s->samples[0].tick); + uint32_t tick_delta2 = calc_delta_and_handle_rollover(s->samples[1].tick, s->samples[0].tick); - time_duration_ns inter_sample_duration_ns = - tick_delta2 * PSVR_NS_PER_TICK; + time_duration_ns inter_sample_duration_ns = tick_delta2 * PSVR_NS_PER_TICK; // Update the fusion with first sample. - update_fusion(psvr, &s->samples[0], tick_delta, - now - inter_sample_duration_ns); + update_fusion(psvr, &s->samples[0], tick_delta, now - inter_sample_duration_ns); // Update the fusion with second sample. update_fusion(psvr, &s->samples[1], tick_delta2, now); @@ -403,9 +381,7 @@ handle_tracker_sensor_msg(struct psvr_device *psvr, } static void -handle_control_status_msg(struct psvr_device *psvr, - unsigned char *buffer, - int size) +handle_control_status_msg(struct psvr_device *psvr, unsigned char *buffer, int size) { struct psvr_parsed_status status = {0}; @@ -420,14 +396,12 @@ handle_control_status_msg(struct psvr_device *psvr, if (status.status & PSVR_STATUS_BIT_POWER) { if (!psvr->powered_on) { - PSVR_DEBUG(psvr, "Device powered on! '%02x'", - status.status); + PSVR_DEBUG(psvr, "Device powered on! '%02x'", status.status); } psvr->powered_on = true; } else { if (psvr->powered_on) { - PSVR_DEBUG(psvr, "Device powered off! '%02x'", - status.status); + PSVR_DEBUG(psvr, "Device powered off! '%02x'", status.status); } psvr->powered_on = false; } @@ -439,14 +413,12 @@ handle_control_status_msg(struct psvr_device *psvr, if (status.vr_mode == PSVR_STATUS_VR_MODE_OFF) { if (psvr->in_vr_mode) { - PSVR_DEBUG(psvr, "Device not in vr-mode! '%02x'", - status.vr_mode); + PSVR_DEBUG(psvr, "Device not in vr-mode! '%02x'", status.vr_mode); } psvr->in_vr_mode = false; } else if (status.vr_mode == PSVR_STATUS_VR_MODE_ON) { if (!psvr->in_vr_mode) { - PSVR_DEBUG(psvr, "Device in vr-mode! '%02x'", - status.vr_mode); + PSVR_DEBUG(psvr, "Device in vr-mode! '%02x'", status.vr_mode); } psvr->in_vr_mode = true; } else { @@ -455,17 +427,13 @@ handle_control_status_msg(struct psvr_device *psvr, } static void -handle_device_name_msg(struct psvr_device *psvr, - unsigned char *buffer, - int size) +handle_device_name_msg(struct psvr_device *psvr, unsigned char *buffer, int size) { //! @todo Get the name here. } static void -handle_calibration_msg(struct psvr_device *psvr, - const unsigned char *buffer, - size_t size) +handle_calibration_msg(struct psvr_device *psvr, const unsigned char *buffer, size_t size) { const size_t data_start = 6; const size_t data_length = 58; @@ -493,8 +461,7 @@ handle_control_0x82(struct psvr_device *psvr, unsigned char *buffer, int size) } if (size < (int)sizeof(float) * 6) { - PSVR_DEBUG(psvr, "%02x %02x %02x %02x", buffer[0], buffer[1], - buffer[2], buffer[3]); + PSVR_DEBUG(psvr, "%02x %02x %02x %02x", buffer[0], buffer[1], buffer[2], buffer[3]); } float *f = (float *)buffer; @@ -505,9 +472,8 @@ handle_control_0x82(struct psvr_device *psvr, unsigned char *buffer, int size) "%+f %+f %+f %+f %+f\n" "0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n" "% 10i % 10i % 10i % 10i % 10i", - buffer[0], buffer[1], buffer[2], buffer[3], f[1], f[2], f[3], - f[4], f[5], i[1], i[2], i[3], i[4], i[5], i[1], i[2], i[3], - i[4], i[5]); + buffer[0], buffer[1], buffer[2], buffer[3], f[1], f[2], f[3], f[4], f[5], i[1], i[2], i[3], i[4], + i[5], i[1], i[2], i[3], i[4], i[5]); } static void @@ -517,8 +483,7 @@ handle_control_0xA0(struct psvr_device *psvr, unsigned char *buffer, int size) return; } - PSVR_DEBUG(psvr, "%02x %02x %02x %02x", buffer[0], buffer[1], buffer[2], - buffer[3]); + PSVR_DEBUG(psvr, "%02x %02x %02x %02x", buffer[0], buffer[1], buffer[2], buffer[3]); } static int @@ -619,23 +584,19 @@ read_calibration_data(struct psvr_device *psvr) return -1; } - PSVR_DEBUG( - psvr, - "calibration.accel_pos_x: %f %f %f\n" - "calibration.accel_neg_x: %f %f %f\n" - "calibration.accel_pos_y: %f %f %f\n" - "calibration.accel_neg_y: %f %f %f\n" - "calibration.accel_pos_z: %f %f %f\n" - "calibration.accel_neg_z: %f %f %f\n", - psvr->calibration.accel_pos_x.x, psvr->calibration.accel_pos_x.y, - psvr->calibration.accel_pos_x.z, psvr->calibration.accel_neg_x.x, - psvr->calibration.accel_neg_x.y, psvr->calibration.accel_neg_x.z, - psvr->calibration.accel_pos_y.x, psvr->calibration.accel_pos_y.y, - psvr->calibration.accel_pos_y.z, psvr->calibration.accel_neg_y.x, - psvr->calibration.accel_neg_y.y, psvr->calibration.accel_neg_y.z, - psvr->calibration.accel_pos_z.x, psvr->calibration.accel_pos_z.y, - psvr->calibration.accel_pos_z.z, psvr->calibration.accel_neg_z.x, - psvr->calibration.accel_neg_z.y, psvr->calibration.accel_neg_z.z); + PSVR_DEBUG(psvr, + "calibration.accel_pos_x: %f %f %f\n" + "calibration.accel_neg_x: %f %f %f\n" + "calibration.accel_pos_y: %f %f %f\n" + "calibration.accel_neg_y: %f %f %f\n" + "calibration.accel_pos_z: %f %f %f\n" + "calibration.accel_neg_z: %f %f %f\n", + psvr->calibration.accel_pos_x.x, psvr->calibration.accel_pos_x.y, psvr->calibration.accel_pos_x.z, + psvr->calibration.accel_neg_x.x, psvr->calibration.accel_neg_x.y, psvr->calibration.accel_neg_x.z, + psvr->calibration.accel_pos_y.x, psvr->calibration.accel_pos_y.y, psvr->calibration.accel_pos_y.z, + psvr->calibration.accel_neg_y.x, psvr->calibration.accel_neg_y.y, psvr->calibration.accel_neg_y.z, + psvr->calibration.accel_pos_z.x, psvr->calibration.accel_pos_z.y, psvr->calibration.accel_pos_z.z, + psvr->calibration.accel_neg_z.x, psvr->calibration.accel_neg_z.y, psvr->calibration.accel_neg_z.z); #if 0 for (size_t i = 0; i < sizeof(psvr->calibration.data); i++) { @@ -706,14 +667,12 @@ control_power_and_wait(struct psvr_device *psvr, bool on) int ret = send_to_control(psvr, data, sizeof(data)); if (ret < 0) { - PSVR_ERROR(psvr, "Failed to switch %s the headset! '%i'", - status, ret); + PSVR_ERROR(psvr, "Failed to switch %s the headset! '%i'", status, ret); } ret = wait_for_power(psvr, on); if (ret < 0) { - PSVR_ERROR(psvr, "Failed to wait for headset power %s! '%i'", - status, ret); + PSVR_ERROR(psvr, "Failed to wait for headset power %s! '%i'", status, ret); return ret; } @@ -730,8 +689,7 @@ control_vrmode_and_wait(struct psvr_device *psvr, bool on) ret = send_to_control(psvr, data, sizeof(data)); if (ret < 0) { - PSVR_ERROR(psvr, "Failed %s vr-mode the headset! '%i'", - on ? "enable" : "disable", ret); + PSVR_ERROR(psvr, "Failed %s vr-mode the headset! '%i'", on ? "enable" : "disable", ret); return ret; } @@ -747,8 +705,7 @@ control_vrmode_and_wait(struct psvr_device *psvr, bool on) static int update_leds_if_changed(struct psvr_device *psvr) { - if (memcmp(psvr->wants.leds, psvr->state.leds, - sizeof(psvr->state.leds)) == 0) { + if (memcmp(psvr->wants.leds, psvr->state.leds, sizeof(psvr->state.leds)) == 0) { return 0; } @@ -792,10 +749,7 @@ update_leds_if_changed(struct psvr_device *psvr) * @ingroup drv_psvr */ static int -control_leds(struct psvr_device *psvr, - enum psvr_leds adjust, - uint8_t power, - enum psvr_leds off) +control_leds(struct psvr_device *psvr, enum psvr_leds adjust, uint8_t power, enum psvr_leds off) { // Get the leds we should control and remove any extra bits. enum psvr_leds all = (enum psvr_leds)((adjust | off) & PSVR_LED_ALL); @@ -847,8 +801,7 @@ disco_leds(struct psvr_device *psvr) }; for (size_t i = 0; i < ARRAY_SIZE(leds); i++) { - int ret = control_leds(psvr, (enum psvr_leds)leds[i], - PSVR_LED_POWER_MAX, PSVR_LED_ALL); + int ret = control_leds(psvr, (enum psvr_leds)leds[i], PSVR_LED_POWER_MAX, PSVR_LED_ALL); if (ret < 0) { return ret; } @@ -883,8 +836,7 @@ teardown(struct psvr_device *psvr) if (psvr->hid_control != NULL) { // Turn off VR-mode and power down headset. - if (control_vrmode_and_wait(psvr, false) < 0 || - control_power_and_wait(psvr, false) < 0) { + if (control_vrmode_and_wait(psvr, false) < 0 || control_power_and_wait(psvr, false) < 0) { PSVR_ERROR(psvr, "Failed to shut down the headset!"); } @@ -946,11 +898,9 @@ psvr_device_get_tracked_pose(struct xrt_device *xdev, out_relation->pose.orientation = psvr->fusion.rot; out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); } else { - xrt_tracked_psvr_get_tracked_pose( - psvr->tracker, at_timestamp_ns, out_relation); + xrt_tracked_psvr_get_tracked_pose(psvr->tracker, at_timestamp_ns, out_relation); } os_mutex_unlock(&psvr->device_mutex); @@ -997,11 +947,7 @@ psvr_device_destroy(struct xrt_device *xdev) } static bool -psvr_compute_distortion(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result) +psvr_compute_distortion(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result) { struct psvr_device *psvr = psvr_device(xdev); @@ -1021,10 +967,9 @@ psvr_device_create(struct hid_device_info *sensor_hid_info, struct xrt_prober *xp, enum u_logging_level log_level) { - enum u_device_alloc_flags flags = (enum u_device_alloc_flags)( - U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); - struct psvr_device *psvr = - U_DEVICE_ALLOCATE(struct psvr_device, flags, 1, 0); + enum u_device_alloc_flags flags = + (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); + struct psvr_device *psvr = U_DEVICE_ALLOCATE(struct psvr_device, flags, 1, 0); int ret; psvr->log_level = log_level; @@ -1078,8 +1023,7 @@ psvr_device_create(struct hid_device_info *sensor_hid_info, goto cleanup; } - if (control_power_and_wait(psvr, true) < 0 || - control_vrmode_and_wait(psvr, true) < 0) { + if (control_power_and_wait(psvr, true) < 0 || control_vrmode_and_wait(psvr, true) < 0) { goto cleanup; } @@ -1092,8 +1036,7 @@ psvr_device_create(struct hid_device_info *sensor_hid_info, if (debug_get_bool_option_psvr_disco()) { ret = disco_leds(psvr); } else { - ret = control_leds(psvr, PSVR_LED_FRONT, PSVR_LED_POWER_MAX, - (enum psvr_leds)0); + ret = control_leds(psvr, PSVR_LED_FRONT, PSVR_LED_POWER_MAX, (enum psvr_leds)0); } if (ret < 0) { PSVR_ERROR(psvr, "Failed to control leds '%i'", ret); @@ -1156,8 +1099,7 @@ psvr_device_create(struct hid_device_info *sensor_hid_info, // If there is a tracking factory use it. if (xp->tracking != NULL) { - xp->tracking->create_tracked_psvr(xp->tracking, &psvr->base, - &psvr->tracker); + xp->tracking->create_tracked_psvr(xp->tracking, &psvr->base, &psvr->tracker); } // Use the new origin if we got a tracking system. diff --git a/src/xrt/drivers/psvr/psvr_device.h b/src/xrt/drivers/psvr/psvr_device.h index 0ac3694d1..d56f38ed4 100644 --- a/src/xrt/drivers/psvr/psvr_device.h +++ b/src/xrt/drivers/psvr/psvr_device.h @@ -130,14 +130,10 @@ psvr_device_create(struct hid_device_info *sensor_hid_info, enum u_logging_level log_level); bool -psvr_parse_sensor_packet(struct psvr_parsed_sensor *sensor, - const uint8_t *buffer, - int size); +psvr_parse_sensor_packet(struct psvr_parsed_sensor *sensor, const uint8_t *buffer, int size); bool -psvr_parse_status_packet(struct psvr_parsed_status *status, - const uint8_t *buffer, - int size); +psvr_parse_status_packet(struct psvr_parsed_status *status, const uint8_t *buffer, int size); #ifdef __cplusplus diff --git a/src/xrt/drivers/psvr/psvr_packet.c b/src/xrt/drivers/psvr/psvr_packet.c index aacd46652..63f387281 100644 --- a/src/xrt/drivers/psvr/psvr_packet.c +++ b/src/xrt/drivers/psvr/psvr_packet.c @@ -99,9 +99,7 @@ read_sample(const uint8_t **buffer, struct psvr_parsed_sample *sample) */ bool -psvr_parse_sensor_packet(struct psvr_parsed_sensor *sensor, - const uint8_t *buffer, - int size) +psvr_parse_sensor_packet(struct psvr_parsed_sensor *sensor, const uint8_t *buffer, int size) { const uint8_t *start = buffer; @@ -150,9 +148,7 @@ psvr_parse_sensor_packet(struct psvr_parsed_sensor *sensor, } bool -psvr_parse_status_packet(struct psvr_parsed_status *status, - const uint8_t *buffer, - int size) +psvr_parse_status_packet(struct psvr_parsed_status *status, const uint8_t *buffer, int size) { const uint8_t *start = buffer; diff --git a/src/xrt/drivers/psvr/psvr_prober.c b/src/xrt/drivers/psvr/psvr_prober.c index d635e1ca9..d61959afe 100644 --- a/src/xrt/drivers/psvr/psvr_prober.c +++ b/src/xrt/drivers/psvr/psvr_prober.c @@ -75,10 +75,7 @@ psvr_prober_destroy(struct xrt_auto_prober *p) //! @public @memberof psvr_prober static struct xrt_device * -psvr_prober_autoprobe(struct xrt_auto_prober *xap, - cJSON *attached_data, - bool no_hmds, - struct xrt_prober *xp) +psvr_prober_autoprobe(struct xrt_auto_prober *xap, cJSON *attached_data, bool no_hmds, struct xrt_prober *xp) { struct psvr_prober *ppsvr = psvr_prober(xap); struct hid_device_info *info_control = NULL; @@ -105,11 +102,9 @@ psvr_prober_autoprobe(struct xrt_auto_prober *xap, if (info_control != NULL && info_handle != NULL) { if (ppsvr->enabled) { - dev = psvr_device_create(info_handle, info_control, xp, - ppsvr->log_level); + dev = psvr_device_create(info_handle, info_control, xp, ppsvr->log_level); } else { - PSVR_DEBUG(ppsvr, - "Found a PSVR hmd but driver is disabled"); + PSVR_DEBUG(ppsvr, "Found a PSVR hmd but driver is disabled"); } } diff --git a/src/xrt/drivers/realsense/rs_6dof.c b/src/xrt/drivers/realsense/rs_6dof.c index bbba830cc..67d5265fe 100644 --- a/src/xrt/drivers/realsense/rs_6dof.c +++ b/src/xrt/drivers/realsense/rs_6dof.c @@ -36,9 +36,8 @@ /*! * Stupid convenience macro to print out a pose, only used for debugging */ -#define print_pose(msg, pose) \ - U_LOG_E(msg " %f %f %f %f %f %f %f", pose.position.x, \ - pose.position.y, pose.position.z, pose.orientation.x, \ +#define print_pose(msg, pose) \ + U_LOG_E(msg " %f %f %f %f %f %f %f", pose.position.x, pose.position.y, pose.position.z, pose.orientation.x, \ pose.orientation.y, pose.orientation.z, pose.orientation.w) /*! @@ -82,8 +81,7 @@ check_error(struct rs_6dof *rs, rs2_error *e) return 0; } - U_LOG_E("rs_error was raised when calling %s(%s):", - rs2_get_failed_function(e), rs2_get_failed_args(e)); + U_LOG_E("rs_error was raised when calling %s(%s):", rs2_get_failed_function(e), rs2_get_failed_args(e)); U_LOG_E("%s", rs2_get_error_message(e)); return 1; @@ -210,8 +208,7 @@ process_frame(struct rs_6dof *rs, rs2_frame *frame) // Close enough uint64_t now_real_ns = os_realtime_get_ns(); uint64_t now_monotonic_ns = os_monotonic_get_ns(); - uint64_t timestamp_ns = - (uint64_t)(timestamp_miliseconds * 1000.0 * 1000.0); + uint64_t timestamp_ns = (uint64_t)(timestamp_miliseconds * 1000.0 * 1000.0); // How far in the past is it? uint64_t diff_ns = now_real_ns - timestamp_ns; @@ -266,8 +263,7 @@ update(struct rs_6dof *rs) rs2_frame *frames; rs2_error *e = NULL; - frames = - rs2_pipeline_wait_for_frames(rs->pipe, RS2_DEFAULT_TIMEOUT, &e); + frames = rs2_pipeline_wait_for_frames(rs->pipe, RS2_DEFAULT_TIMEOUT, &e); if (check_error(rs, e) != 0) { return 1; } @@ -375,8 +371,7 @@ rs_6dof_destroy(struct xrt_device *xdev) struct xrt_device * rs_6dof_create(void) { - struct rs_6dof *rs = U_DEVICE_ALLOCATE( - struct rs_6dof, U_DEVICE_ALLOC_TRACKING_NONE, 1, 0); + struct rs_6dof *rs = U_DEVICE_ALLOCATE(struct rs_6dof, U_DEVICE_ALLOC_TRACKING_NONE, 1, 0); int ret = 0; rs->base.update_inputs = rs_6dof_update_inputs; diff --git a/src/xrt/drivers/remote/r_device.c b/src/xrt/drivers/remote/r_device.c index da0707bae..4dc89c223 100644 --- a/src/xrt/drivers/remote/r_device.c +++ b/src/xrt/drivers/remote/r_device.c @@ -53,8 +53,7 @@ r_device_update_inputs(struct xrt_device *xdev) struct r_hub *r = rd->r; uint64_t now = os_monotonic_get_ns(); - struct r_remote_controller_data *latest = - rd->is_left ? &r->latest.left : &r->latest.right; + struct r_remote_controller_data *latest = rd->is_left ? &r->latest.left : &r->latest.right; if (!latest->active) { xdev->inputs[0].active = false; @@ -88,33 +87,27 @@ r_device_get_tracked_pose(struct xrt_device *xdev, struct r_device *rd = r_device(xdev); struct r_hub *r = rd->r; - if (name != XRT_INPUT_SIMPLE_AIM_POSE && - name != XRT_INPUT_SIMPLE_GRIP_POSE) { + if (name != XRT_INPUT_SIMPLE_AIM_POSE && name != XRT_INPUT_SIMPLE_GRIP_POSE) { U_LOG_E("Unknown input name"); return; } - struct r_remote_controller_data *latest = - rd->is_left ? &r->latest.left : &r->latest.right; + struct r_remote_controller_data *latest = rd->is_left ? &r->latest.left : &r->latest.right; /* * It's easier to reason about angular velocity if it's controlled in * body space, but the angular velocity returned in the relation is in * the base space. */ - math_quat_rotate_derivative(&latest->pose.orientation, - &latest->angular_velocity, + math_quat_rotate_derivative(&latest->pose.orientation, &latest->angular_velocity, &out_relation->angular_velocity); out_relation->pose = latest->pose; out_relation->linear_velocity = latest->linear_velocity; out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT | - XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT | - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT); + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_POSITION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT | + XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT | XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT); } static void @@ -127,14 +120,12 @@ r_device_get_hand_tracking(struct xrt_device *xdev, struct r_hub *r = rd->r; - if (name != XRT_INPUT_GENERIC_HAND_TRACKING_LEFT && - name != XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT) { + if (name != XRT_INPUT_GENERIC_HAND_TRACKING_LEFT && name != XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT) { U_LOG_E("Unknown input name for hand tracker"); return; } - struct r_remote_controller_data *latest = - rd->is_left ? &r->latest.left : &r->latest.right; + struct r_remote_controller_data *latest = rd->is_left ? &r->latest.left : &r->latest.right; struct u_hand_tracking_curl_values values = { .little = latest->hand_curl[0], @@ -145,8 +136,7 @@ r_device_get_hand_tracking(struct xrt_device *xdev, }; enum xrt_hand hand = rd->is_left ? XRT_HAND_LEFT : XRT_HAND_RIGHT; - u_hand_joints_update_curl(&rd->hand_tracking, hand, at_timestamp_ns, - &values); + u_hand_joints_update_curl(&rd->hand_tracking, hand, at_timestamp_ns, &values); struct xrt_pose hand_on_handle_pose = { {0, 0, 0, 1}, @@ -154,11 +144,9 @@ r_device_get_hand_tracking(struct xrt_device *xdev, }; struct xrt_space_relation relation; - xrt_device_get_tracked_pose(xdev, XRT_INPUT_SIMPLE_GRIP_POSE, - at_timestamp_ns, &relation); + xrt_device_get_tracked_pose(xdev, XRT_INPUT_SIMPLE_GRIP_POSE, at_timestamp_ns, &relation); - u_hand_joints_set_out_data(&rd->hand_tracking, hand, &relation, - &hand_on_handle_pose, out_value); + u_hand_joints_set_out_data(&rd->hand_tracking, hand, &relation, &hand_on_handle_pose, out_value); } static void @@ -171,9 +159,7 @@ r_device_get_view_pose(struct xrt_device *xdev, } static void -r_device_set_output(struct xrt_device *xdev, - enum xrt_output_name name, - union xrt_output_value *value) +r_device_set_output(struct xrt_device *xdev, enum xrt_output_name name, union xrt_output_value *value) { struct r_device *rd = r_device(xdev); (void)rd; @@ -208,8 +194,7 @@ r_device_create(struct r_hub *r, bool is_left) rd->is_left = is_left; // Print name. - snprintf(rd->base.str, sizeof(rd->base.str), "Remote %s Controller", - is_left ? "Left" : "Right"); + snprintf(rd->base.str, sizeof(rd->base.str), "Remote %s Controller", is_left ? "Left" : "Right"); // Inputs and outputs. rd->base.inputs[0].name = XRT_INPUT_SIMPLE_SELECT_CLICK; @@ -230,9 +215,7 @@ r_device_create(struct r_hub *r, bool is_left) } enum xrt_hand hand = rd->is_left ? XRT_HAND_LEFT : XRT_HAND_RIGHT; - u_hand_joints_init_default_set(&rd->hand_tracking, hand, - XRT_HAND_TRACKING_MODEL_FINGERL_CURL, - 1.0); + u_hand_joints_init_default_set(&rd->hand_tracking, hand, XRT_HAND_TRACKING_MODEL_FINGERL_CURL, 1.0); // Setup variable tracker. u_var_add_root(rd, rd->base.str, true); diff --git a/src/xrt/drivers/remote/r_hmd.c b/src/xrt/drivers/remote/r_hmd.c index e182d2504..cc5202a83 100644 --- a/src/xrt/drivers/remote/r_hmd.c +++ b/src/xrt/drivers/remote/r_hmd.c @@ -69,10 +69,8 @@ r_hmd_get_tracked_pose(struct xrt_device *xdev, out_relation->pose = rh->r->latest.hmd.pose; out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT); + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_POSITION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT); } static void @@ -113,9 +111,7 @@ r_hmd_get_view_pose(struct xrt_device *xdev, } static void -r_hmd_set_output(struct xrt_device *xdev, - enum xrt_output_name name, - union xrt_output_value *value) +r_hmd_set_output(struct xrt_device *xdev, enum xrt_output_name name, union xrt_output_value *value) { // Empty } diff --git a/src/xrt/drivers/remote/r_hub.c b/src/xrt/drivers/remote/r_hub.c index 06dc86bb2..ab0517c90 100644 --- a/src/xrt/drivers/remote/r_hub.c +++ b/src/xrt/drivers/remote/r_hub.c @@ -52,8 +52,7 @@ setup_accept_fd(struct r_hub *r) r->accept_fd = ret; int flag = 1; - ret = setsockopt(r->accept_fd, SOL_SOCKET, SO_REUSEADDR, &flag, - sizeof(flag)); + ret = setsockopt(r->accept_fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)); if (ret < 0) { U_LOG_E("setsockopt failed: %i", ret); close(r->accept_fd); @@ -65,8 +64,7 @@ setup_accept_fd(struct r_hub *r) server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(r->port); - ret = bind(r->accept_fd, (struct sockaddr *)&server_address, - sizeof(server_address)); + ret = bind(r->accept_fd, (struct sockaddr *)&server_address, sizeof(server_address)); if (ret < 0) { U_LOG_E("bind failed: %i", ret); close(r->accept_fd); @@ -95,8 +93,7 @@ do_accept(struct r_hub *r) conn_fd = ret; int flags = 1; - ret = setsockopt(conn_fd, SOL_TCP, TCP_NODELAY, (void *)&flags, - sizeof(flags)); + ret = setsockopt(conn_fd, SOL_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); if (ret < 0) { U_LOG_E("setsockopt failed: %i", ret); close(conn_fd); @@ -227,9 +224,7 @@ r_create_devices(uint16_t port, } int -r_remote_connection_init(struct r_remote_connection *rc, - const char *ip_addr, - uint16_t port) +r_remote_connection_init(struct r_remote_connection *rc, const char *ip_addr, uint16_t port) { struct sockaddr_in addr = {0}; int conn_fd; @@ -260,8 +255,7 @@ r_remote_connection_init(struct r_remote_connection *rc, } int flags = 1; - ret = setsockopt(conn_fd, SOL_TCP, TCP_NODELAY, (void *)&flags, - sizeof(flags)); + ret = setsockopt(conn_fd, SOL_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); if (ret < 0) { U_LOG_E("setsockopt failed: %i", ret); close(conn_fd); @@ -274,8 +268,7 @@ r_remote_connection_init(struct r_remote_connection *rc, } int -r_remote_connection_read_one(struct r_remote_connection *rc, - struct r_remote_data *data) +r_remote_connection_read_one(struct r_remote_connection *rc, struct r_remote_data *data) { const size_t size = sizeof(*data); size_t current = 0; @@ -298,8 +291,7 @@ r_remote_connection_read_one(struct r_remote_connection *rc, } int -r_remote_connection_write_one(struct r_remote_connection *rc, - const struct r_remote_data *data) +r_remote_connection_write_one(struct r_remote_connection *rc, const struct r_remote_data *data) { const size_t size = sizeof(*data); size_t current = 0; diff --git a/src/xrt/drivers/remote/r_interface.h b/src/xrt/drivers/remote/r_interface.h index 9b9e56af3..456d626b3 100644 --- a/src/xrt/drivers/remote/r_interface.h +++ b/src/xrt/drivers/remote/r_interface.h @@ -99,17 +99,13 @@ r_create_devices(uint16_t port, * @ingroup drv_remote */ int -r_remote_connection_init(struct r_remote_connection *rc, - const char *addr, - uint16_t port); +r_remote_connection_init(struct r_remote_connection *rc, const char *addr, uint16_t port); int -r_remote_connection_read_one(struct r_remote_connection *rc, - struct r_remote_data *data); +r_remote_connection_read_one(struct r_remote_connection *rc, struct r_remote_data *data); int -r_remote_connection_write_one(struct r_remote_connection *rc, - const struct r_remote_data *data); +r_remote_connection_write_one(struct r_remote_connection *rc, const struct r_remote_data *data); #ifdef __cplusplus diff --git a/src/xrt/drivers/survive/survive_driver.c b/src/xrt/drivers/survive/survive_driver.c index eb2a86b96..5a131c40c 100644 --- a/src/xrt/drivers/survive/survive_driver.c +++ b/src/xrt/drivers/survive/survive_driver.c @@ -52,14 +52,11 @@ #define DEFAULT_HAPTIC_FREQ 150.0f #define MIN_HAPTIC_DURATION 0.05f -#define SURVIVE_TRACE(d, ...) \ - U_LOG_XDEV_IFL_T(&d->base, d->sys->ll, __VA_ARGS__) -#define SURVIVE_DEBUG(d, ...) \ - U_LOG_XDEV_IFL_D(&d->base, d->sys->ll, __VA_ARGS__) +#define SURVIVE_TRACE(d, ...) U_LOG_XDEV_IFL_T(&d->base, d->sys->ll, __VA_ARGS__) +#define SURVIVE_DEBUG(d, ...) U_LOG_XDEV_IFL_D(&d->base, d->sys->ll, __VA_ARGS__) #define SURVIVE_INFO(d, ...) U_LOG_XDEV_IFL_I(&d->base, d->sys->ll, __VA_ARGS__) #define SURVIVE_WARN(d, ...) U_LOG_XDEV_IFL_W(&d->base, d->sys->ll, __VA_ARGS__) -#define SURVIVE_ERROR(d, ...) \ - U_LOG_XDEV_IFL_E(&d->base, d->sys->ll, __VA_ARGS__) +#define SURVIVE_ERROR(d, ...) U_LOG_XDEV_IFL_E(&d->base, d->sys->ll, __VA_ARGS__) struct survive_system; @@ -182,8 +179,7 @@ survive_device_destroy(struct xrt_device *xdev) if (survive == survive->sys->controllers[SURVIVE_RIGHT_CONTROLLER]) survive->sys->controllers[SURVIVE_RIGHT_CONTROLLER] = NULL; - if (survive->sys->hmd == NULL && - survive->sys->controllers[SURVIVE_LEFT_CONTROLLER] == NULL && + if (survive->sys->hmd == NULL && survive->sys->controllers[SURVIVE_LEFT_CONTROLLER] == NULL && survive->sys->controllers[SURVIVE_RIGHT_CONTROLLER] == NULL) { U_LOG_D("Tearing down libsurvive context"); survive_simple_close(survive->sys->ctx); @@ -205,18 +201,14 @@ survive_timecode_now_s() } static void -_get_survive_pose(struct survive_device *survive, - uint64_t at_timestamp_ns, - struct xrt_space_relation *out_relation) +_get_survive_pose(struct survive_device *survive, uint64_t at_timestamp_ns, struct xrt_space_relation *out_relation) { const SurviveSimpleObject *survive_object = survive->survive_obj; out_relation->relation_flags = XRT_SPACE_RELATION_BITMASK_NONE; - if (survive_simple_object_get_type(survive_object) != - SurviveSimpleObject_OBJECT && - survive_simple_object_get_type(survive_object) != - SurviveSimpleObject_HMD) { + if (survive_simple_object_get_type(survive_object) != SurviveSimpleObject_OBJECT && + survive_simple_object_get_type(survive_object) != SurviveSimpleObject_HMD) { return; } @@ -226,11 +218,9 @@ _get_survive_pose(struct survive_device *survive, SurviveVelocity vel; // "device time" in seconds - double timecode_s = - survive_simple_object_get_latest_pose(survive_object, &pose); + double timecode_s = survive_simple_object_get_latest_pose(survive_object, &pose); - double vel_timecode_s = - survive_simple_object_get_latest_velocity(survive_object, &vel); + double vel_timecode_s = survive_simple_object_get_latest_velocity(survive_object, &vel); (void)vel_timecode_s; // do calculations in ns due to large numbers @@ -250,14 +240,10 @@ _get_survive_pose(struct survive_device *survive, "dev %s At %ldns: Pose requested for +%ldns (%ldns). " "Libsurvive Pose Timecode: %ldns, Pose gotten at -%ldns " "from now (%ldns), predicting %ldns", - survive->base.str, monotonic_now_ns, remaining_ns, - at_timestamp_ns, timecode_ns, survive_pose_age_ns, - survive_now_ns, prediction_ns); + survive->base.str, monotonic_now_ns, remaining_ns, at_timestamp_ns, timecode_ns, + survive_pose_age_ns, survive_now_ns, prediction_ns); - struct xrt_quat out_rot = {.x = pose.Rot[1], - .y = pose.Rot[2], - .z = pose.Rot[3], - .w = pose.Rot[0]}; + struct xrt_quat out_rot = {.x = pose.Rot[1], .y = pose.Rot[2], .z = pose.Rot[3], .w = pose.Rot[0]}; /* libsurvive looks down when it should be looking forward, so * rotate the quat. @@ -284,42 +270,34 @@ _get_survive_pose(struct survive_device *survive, out_relation->pose.position.y = pose.Pos[2]; out_relation->pose.position.z = -pose.Pos[1]; - struct xrt_vec3 linear_vel = { - .x = vel.Pos[0], .y = vel.Pos[2], .z = -vel.Pos[1]}; + struct xrt_vec3 linear_vel = {.x = vel.Pos[0], .y = vel.Pos[2], .z = -vel.Pos[1]}; - struct xrt_vec3 angular_vel = {.x = vel.AxisAngleRot[0], - .y = vel.AxisAngleRot[2], - .z = -vel.AxisAngleRot[1]}; + struct xrt_vec3 angular_vel = {.x = vel.AxisAngleRot[0], .y = vel.AxisAngleRot[2], .z = -vel.AxisAngleRot[1]}; if (math_quat_validate(&out_rot)) { out_relation->relation_flags |= - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT; + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT; // everything else is invalid if orientation is not valid if (math_vec3_validate(&out_relation->pose.position)) { out_relation->relation_flags |= - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT; + XRT_SPACE_RELATION_POSITION_VALID_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT; } out_relation->linear_velocity = linear_vel; if (math_vec3_validate(&out_relation->linear_velocity)) { - out_relation->relation_flags |= - XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT; + out_relation->relation_flags |= XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT; } out_relation->angular_velocity = angular_vel; if (math_vec3_validate(&out_relation->angular_velocity)) { - out_relation->relation_flags |= - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT; + out_relation->relation_flags |= XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT; } } - SURVIVE_TRACE(survive, "Predicting %fs for %s", prediction_s, - survive->base.str); + SURVIVE_TRACE(survive, "Predicting %fs for %s", prediction_s, survive->base.str); struct xrt_space_relation rel = *out_relation; m_predict_relation(&rel, prediction_s, out_relation); @@ -377,14 +355,10 @@ survive_device_get_tracked_pose(struct xrt_device *xdev, struct xrt_space_relation *out_relation) { struct survive_device *survive = (struct survive_device *)xdev; - if ((survive == survive->sys->hmd && - name != XRT_INPUT_GENERIC_HEAD_POSE) || - ((survive == survive->sys->controllers[0] || - survive == survive->sys->controllers[1]) && - (name != XRT_INPUT_INDEX_AIM_POSE && - name != XRT_INPUT_INDEX_GRIP_POSE) && - (name != XRT_INPUT_VIVE_AIM_POSE && - name != XRT_INPUT_VIVE_GRIP_POSE))) { + if ((survive == survive->sys->hmd && name != XRT_INPUT_GENERIC_HEAD_POSE) || + ((survive == survive->sys->controllers[0] || survive == survive->sys->controllers[1]) && + (name != XRT_INPUT_INDEX_AIM_POSE && name != XRT_INPUT_INDEX_GRIP_POSE) && + (name != XRT_INPUT_VIVE_AIM_POSE && name != XRT_INPUT_VIVE_GRIP_POSE))) { SURVIVE_ERROR(survive, "unknown input name"); return; @@ -402,21 +376,16 @@ survive_device_get_tracked_pose(struct xrt_device *xdev, survive->last_relation = *out_relation; struct xrt_pose *p = &out_relation->pose; - SURVIVE_TRACE( - survive, "GET_POSITION (%f %f %f) GET_ORIENTATION (%f, %f, %f, %f)", - p->position.x, p->position.y, p->position.z, p->orientation.x, - p->orientation.y, p->orientation.z, p->orientation.w); + SURVIVE_TRACE(survive, "GET_POSITION (%f %f %f) GET_ORIENTATION (%f, %f, %f, %f)", p->position.x, p->position.y, + p->position.z, p->orientation.x, p->orientation.y, p->orientation.z, p->orientation.w); } static int -survive_controller_haptic_pulse(struct survive_device *survive, - union xrt_output_value *value) +survive_controller_haptic_pulse(struct survive_device *survive, union xrt_output_value *value) { float duration_seconds; if (value->vibration.duration == XRT_MIN_HAPTIC_DURATION) { - SURVIVE_TRACE(survive, - "Haptic pulse duration: using %f minimum", - MIN_HAPTIC_DURATION); + SURVIVE_TRACE(survive, "Haptic pulse duration: using %f minimum", MIN_HAPTIC_DURATION); duration_seconds = MIN_HAPTIC_DURATION; } else { duration_seconds = time_ns_to_s(value->vibration.duration); @@ -425,35 +394,26 @@ survive_controller_haptic_pulse(struct survive_device *survive, float frequency = value->vibration.frequency; if (frequency == XRT_FREQUENCY_UNSPECIFIED) { - SURVIVE_TRACE( - survive, - "Haptic pulse frequency unspecified, setting to %fHz", - DEFAULT_HAPTIC_FREQ); + SURVIVE_TRACE(survive, "Haptic pulse frequency unspecified, setting to %fHz", DEFAULT_HAPTIC_FREQ); frequency = DEFAULT_HAPTIC_FREQ; } float amplitude = value->vibration.amplitude; - SURVIVE_TRACE(survive, "Got Haptic pulse amp %f, %fHz, %" PRId64 "ns", - value->vibration.amplitude, value->vibration.frequency, - value->vibration.duration); - SURVIVE_TRACE(survive, "Doing Haptic pulse amp %f, %fHz, %fs", - amplitude, frequency, duration_seconds); + SURVIVE_TRACE(survive, "Got Haptic pulse amp %f, %fHz, %" PRId64 "ns", value->vibration.amplitude, + value->vibration.frequency, value->vibration.duration); + SURVIVE_TRACE(survive, "Doing Haptic pulse amp %f, %fHz, %fs", amplitude, frequency, duration_seconds); - return survive_simple_object_haptic( - (struct SurviveSimpleObject *)survive->survive_obj, frequency, - amplitude, duration_seconds); + return survive_simple_object_haptic((struct SurviveSimpleObject *)survive->survive_obj, frequency, amplitude, + duration_seconds); } static void -survive_controller_device_set_output(struct xrt_device *xdev, - enum xrt_output_name name, - union xrt_output_value *value) +survive_controller_device_set_output(struct xrt_device *xdev, enum xrt_output_name name, union xrt_output_value *value) { struct survive_device *survive = (struct survive_device *)xdev; - if (name != XRT_OUTPUT_NAME_VIVE_HAPTIC && - name != XRT_OUTPUT_NAME_INDEX_HAPTIC) { + if (name != XRT_OUTPUT_NAME_VIVE_HAPTIC && name != XRT_OUTPUT_NAME_INDEX_HAPTIC) { SURVIVE_ERROR(survive, "Unknown output"); return; } @@ -481,50 +441,42 @@ survive_controller_get_hand_tracking(struct xrt_device *xdev, { struct survive_device *survive = (struct survive_device *)xdev; - if (name != XRT_INPUT_GENERIC_HAND_TRACKING_LEFT && - name != XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT) { + if (name != XRT_INPUT_GENERIC_HAND_TRACKING_LEFT && name != XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT) { SURVIVE_ERROR(survive, "unknown input name for hand tracker"); return; } - bool left = - survive->variant == VIVE_VARIANT_VALVE_INDEX_LEFT_CONTROLLER; + bool left = survive->variant == VIVE_VARIANT_VALVE_INDEX_LEFT_CONTROLLER; enum xrt_hand hand = left ? XRT_HAND_LEFT : XRT_HAND_RIGHT; float thumb_curl = 0.0f; //! @todo place thumb preciely on the button that is touched/pressed if (survive->base.inputs[VIVE_CONTROLLER_A_TOUCH].value.boolean || survive->base.inputs[VIVE_CONTROLLER_B_TOUCH].value.boolean || - survive->base.inputs[VIVE_CONTROLLER_THUMBSTICK_TOUCH] - .value.boolean || - survive->base.inputs[VIVE_CONTROLLER_TRACKPAD_TOUCH] - .value.boolean) { + survive->base.inputs[VIVE_CONTROLLER_THUMBSTICK_TOUCH].value.boolean || + survive->base.inputs[VIVE_CONTROLLER_TRACKPAD_TOUCH].value.boolean) { thumb_curl = 1.0; } - struct u_hand_tracking_curl_values values = { - .little = survive->ctrl.curl[XRT_FINGER_LITTLE], - .ring = survive->ctrl.curl[XRT_FINGER_RING], - .middle = survive->ctrl.curl[XRT_FINGER_MIDDLE], - .index = survive->ctrl.curl[XRT_FINGER_INDEX], - .thumb = thumb_curl}; + struct u_hand_tracking_curl_values values = {.little = survive->ctrl.curl[XRT_FINGER_LITTLE], + .ring = survive->ctrl.curl[XRT_FINGER_RING], + .middle = survive->ctrl.curl[XRT_FINGER_MIDDLE], + .index = survive->ctrl.curl[XRT_FINGER_INDEX], + .thumb = thumb_curl}; /* The tracked controller position is at the very -z end of the * controller. Move the hand back offset_z meter to the handle center. */ struct xrt_vec3 static_offset = {.x = 0, .y = 0, .z = 0.11}; - u_hand_joints_update_curl(&survive->ctrl.hand_tracking, hand, - at_timestamp_ns, &values); + u_hand_joints_update_curl(&survive->ctrl.hand_tracking, hand, at_timestamp_ns, &values); struct xrt_pose hand_on_handle_pose; - u_hand_joints_offset_valve_index_controller(hand, &static_offset, - &hand_on_handle_pose); + u_hand_joints_offset_valve_index_controller(hand, &static_offset, &hand_on_handle_pose); - u_hand_joints_set_out_data(&survive->ctrl.hand_tracking, hand, - &survive->last_relation, - &hand_on_handle_pose, out_value); + u_hand_joints_set_out_data(&survive->ctrl.hand_tracking, hand, &survive->last_relation, &hand_on_handle_pose, + out_value); } static void @@ -608,11 +560,7 @@ struct Axis axes[255] = { }; static bool -update_axis(struct survive_device *survive, - struct Axis *axis, - const SurviveSimpleButtonEvent *e, - int i, - uint64_t now) +update_axis(struct survive_device *survive, struct Axis *axis, const SurviveSimpleButtonEvent *e, int i, uint64_t now) { if (axis->input == 0) { return false; @@ -642,19 +590,15 @@ struct Button }; struct Button buttons[255] = { - [SURVIVE_BUTTON_A] = {.click = VIVE_CONTROLLER_A_CLICK, - .touch = VIVE_CONTROLLER_A_TOUCH}, - [SURVIVE_BUTTON_B] = {.click = VIVE_CONTROLLER_B_CLICK, - .touch = VIVE_CONTROLLER_B_TOUCH}, + [SURVIVE_BUTTON_A] = {.click = VIVE_CONTROLLER_A_CLICK, .touch = VIVE_CONTROLLER_A_TOUCH}, + [SURVIVE_BUTTON_B] = {.click = VIVE_CONTROLLER_B_CLICK, .touch = VIVE_CONTROLLER_B_TOUCH}, - [SURVIVE_BUTTON_TRACKPAD] = {.click = VIVE_CONTROLLER_TRACKPAD_CLICK, - .touch = VIVE_CONTROLLER_TRACKPAD_TOUCH}, + [SURVIVE_BUTTON_TRACKPAD] = {.click = VIVE_CONTROLLER_TRACKPAD_CLICK, .touch = VIVE_CONTROLLER_TRACKPAD_TOUCH}, [SURVIVE_BUTTON_THUMBSTICK] = {.click = VIVE_CONTROLLER_THUMBSTICK_CLICK, .touch = VIVE_CONTROLLER_THUMBSTICK_TOUCH}, - [SURVIVE_BUTTON_SYSTEM] = {.click = VIVE_CONTROLLER_SYSTEM_CLICK, - .touch = VIVE_CONTROLLER_SYSTEM_TOUCH}, + [SURVIVE_BUTTON_SYSTEM] = {.click = VIVE_CONTROLLER_SYSTEM_CLICK, .touch = VIVE_CONTROLLER_SYSTEM_TOUCH}, [SURVIVE_BUTTON_MENU] = {.click = VIVE_CONTROLLER_MENU_CLICK, // only on vive wand without touch @@ -664,14 +608,11 @@ struct Button buttons[255] = { // only on vive wand without touch .touch = 0}, - [SURVIVE_BUTTON_TRIGGER] = {.click = VIVE_CONTROLLER_TRIGGER_CLICK, - .touch = VIVE_CONTROLLER_TRIGGER_TOUCH}, + [SURVIVE_BUTTON_TRIGGER] = {.click = VIVE_CONTROLLER_TRIGGER_CLICK, .touch = VIVE_CONTROLLER_TRIGGER_TOUCH}, }; static bool -update_button(struct survive_device *survive, - const struct SurviveSimpleButtonEvent *e, - uint64_t now) +update_button(struct survive_device *survive, const struct SurviveSimpleButtonEvent *e, uint64_t now) { if (e->event_type == SURVIVE_INPUT_EVENT_NONE) { return true; @@ -718,9 +659,7 @@ _calculate_squeeze_value(struct survive_device *survive) } static void -_process_button_event(struct survive_device *survive, - const struct SurviveSimpleButtonEvent *e, - int64_t now) +_process_button_event(struct survive_device *survive, const struct SurviveSimpleButtonEvent *e, int64_t now) { if (e->event_type == SURVIVE_INPUT_EVENT_AXIS_CHANGED) { for (int i = 0; i < e->axis_count; i++) { @@ -731,29 +670,23 @@ _process_button_event(struct survive_device *survive, if (update_axis(survive, axis, e, i, now)) { - } else if (e->axis_ids[i] == - SURVIVE_AXIS_TRIGGER_FINGER_PROXIMITY) { + } else if (e->axis_ids[i] == SURVIVE_AXIS_TRIGGER_FINGER_PROXIMITY) { survive->ctrl.curl[XRT_FINGER_INDEX] = val; survive->ctrl.curl_ts[XRT_FINGER_INDEX] = now; - } else if (e->axis_ids[i] == - SURVIVE_AXIS_MIDDLE_FINGER_PROXIMITY) { + } else if (e->axis_ids[i] == SURVIVE_AXIS_MIDDLE_FINGER_PROXIMITY) { survive->ctrl.curl[XRT_FINGER_MIDDLE] = val; survive->ctrl.curl_ts[XRT_FINGER_MIDDLE] = now; - } else if (e->axis_ids[i] == - SURVIVE_AXIS_RING_FINGER_PROXIMITY) { + } else if (e->axis_ids[i] == SURVIVE_AXIS_RING_FINGER_PROXIMITY) { survive->ctrl.curl[XRT_FINGER_RING] = val; survive->ctrl.curl_ts[XRT_FINGER_RING] = now; - } else if (e->axis_ids[i] == - SURVIVE_AXIS_PINKY_FINGER_PROXIMITY) { + } else if (e->axis_ids[i] == SURVIVE_AXIS_PINKY_FINGER_PROXIMITY) { survive->ctrl.curl[XRT_FINGER_LITTLE] = val; survive->ctrl.curl_ts[XRT_FINGER_LITTLE] = now; } else { - SURVIVE_DEBUG(survive, "axis id: %d val %f", - e->axis_ids[i], e->axis_val[i]); + SURVIVE_DEBUG(survive, "axis id: %d val %f", e->axis_ids[i], e->axis_val[i]); } } - struct xrt_input *squeeze_value_in = - &survive->base.inputs[VIVE_CONTROLLER_SQUEEZE_VALUE]; + struct xrt_input *squeeze_value_in = &survive->base.inputs[VIVE_CONTROLLER_SQUEEZE_VALUE]; float prev_squeeze_value = squeeze_value_in->value.vec1.x; float squeeze_value = _calculate_squeeze_value(survive); if (prev_squeeze_value != squeeze_value) { @@ -766,9 +699,7 @@ _process_button_event(struct survive_device *survive, } static void -_process_hmd_button_event(struct survive_device *survive, - const struct SurviveSimpleButtonEvent *e, - int64_t now) +_process_hmd_button_event(struct survive_device *survive, const struct SurviveSimpleButtonEvent *e, int64_t now) { if (e->event_type == SURVIVE_INPUT_EVENT_AXIS_CHANGED) { for (int i = 0; i < e->axis_count; i++) { @@ -782,8 +713,7 @@ _process_hmd_button_event(struct survive_device *survive, survive->hmd.ipd = ipd; // SURVIVE_DEBUG(survive, "ipd: %f meter", ipd); - } else if (e->axis_ids[i] == - SURVIVE_AXIS_FACE_PROXIMITY) { + } else if (e->axis_ids[i] == SURVIVE_AXIS_FACE_PROXIMITY) { // Valve Index: // >0.003 not wearing hmd // 0.03-0.035 wearing hmd @@ -797,10 +727,8 @@ _process_hmd_button_event(struct survive_device *survive, } float curr = survive->hmd.proximity; - bool engagement = (curr <= threshold && - proximity > threshold) || - (curr >= threshold && - proximity < threshold); + bool engagement = (curr <= threshold && proximity > threshold) || + (curr >= threshold && proximity < threshold); if (engagement) { //! @todo engagement changed @@ -810,16 +738,14 @@ _process_hmd_button_event(struct survive_device *survive, survive->hmd.proximity = proximity; } else { - SURVIVE_DEBUG(survive, "axis id: %d val %f", - e->axis_ids[i], e->axis_val[i]); + SURVIVE_DEBUG(survive, "axis id: %d val %f", e->axis_ids[i], e->axis_val[i]); } } } } static struct survive_device * -get_device_by_object(struct survive_system *sys, - const SurviveSimpleObject *object) +get_device_by_object(struct survive_system *sys, const SurviveSimpleObject *object) { if (sys->hmd->survive_obj == object) { return sys->hmd; @@ -838,25 +764,20 @@ get_device_by_object(struct survive_system *sys, } static void -_process_event(struct survive_device *survive, - struct SurviveSimpleEvent *event, - int64_t now) +_process_event(struct survive_device *survive, struct SurviveSimpleEvent *event, int64_t now) { switch (event->event_type) { case SurviveSimpleEventType_ButtonEvent: { - const struct SurviveSimpleButtonEvent *e = - survive_simple_get_button_event(event); + const struct SurviveSimpleButtonEvent *e = survive_simple_get_button_event(event); struct survive_device *event_device = survive; if (e->object != survive->survive_obj) { - event_device = - get_device_by_object(survive->sys, e->object); + event_device = get_device_by_object(survive->sys, e->object); } if (event_device == NULL) { - SURVIVE_ERROR(survive, - "Event for unknown object not handled"); + SURVIVE_ERROR(survive, "Event for unknown object not handled"); return; } @@ -886,8 +807,7 @@ survive_device_update_inputs(struct xrt_device *xdev) devices, not just this survive device. */ struct SurviveSimpleEvent event = {0}; - while (survive_simple_next_event(survive->sys->ctx, &event) != - SurviveSimpleEventType_None) { + while (survive_simple_next_event(survive->sys->ctx, &event) != SurviveSimpleEventType_None) { _process_event(survive, &event, now); } } @@ -914,8 +834,7 @@ wait_for_device_config(const struct SurviveSimpleObject *sso) void print_vec3(const char *title, struct xrt_vec3 *vec) { - U_LOG_D("%s = %f %f %f", title, (double)vec->x, (double)vec->y, - (double)vec->z); + U_LOG_D("%s = %f %f %f", title, (double)vec->x, (double)vec->y, (double)vec->z); } static long long @@ -929,9 +848,7 @@ _json_to_int(const cJSON *item) } static bool -_json_get_matrix_3x3(const cJSON *json, - const char *name, - struct xrt_matrix_3x3 *result) +_json_get_matrix_3x3(const cJSON *json, const char *name, struct xrt_matrix_3x3 *result) { const cJSON *vec3_arr = cJSON_GetObjectItemCaseSensitive(json, name); @@ -976,10 +893,7 @@ _json_get_int(const cJSON *json, const char *name) } static void -_get_color_coeffs(struct u_vive_values *values, - const cJSON *coeffs, - uint8_t eye, - uint8_t channel) +_get_color_coeffs(struct u_vive_values *values, const cJSON *coeffs, uint8_t eye, uint8_t channel) { // this is 4 on index, all values populated // assert(coeffs->length == 8); @@ -997,20 +911,15 @@ _get_color_coeffs(struct u_vive_values *values, } static void -_get_color_coeffs_lookup(struct u_vive_values *values, - const cJSON *eye_json, - const char *name, - uint8_t eye, - uint8_t channel) +_get_color_coeffs_lookup( + struct u_vive_values *values, const cJSON *eye_json, const char *name, uint8_t eye, uint8_t channel) { - const cJSON *distortion = - cJSON_GetObjectItemCaseSensitive(eye_json, name); + const cJSON *distortion = cJSON_GetObjectItemCaseSensitive(eye_json, name); if (distortion == NULL) { return; } - const cJSON *coeffs = - cJSON_GetObjectItemCaseSensitive(distortion, "coeffs"); + const cJSON *coeffs = cJSON_GetObjectItemCaseSensitive(distortion, "coeffs"); if (coeffs == NULL) { return; } @@ -1019,9 +928,7 @@ _get_color_coeffs_lookup(struct u_vive_values *values, } static void -get_distortion_properties(struct survive_device *d, - const cJSON *eye_transform_json, - uint8_t eye) +get_distortion_properties(struct survive_device *d, const cJSON *eye_transform_json, uint8_t eye) { const cJSON *eye_json = cJSON_GetArrayItem(eye_transform_json, eye); if (eye_json == NULL) { @@ -1039,8 +946,7 @@ get_distortion_properties(struct survive_device *d, d->distortion[eye].undistort_r2_cutoff = _json_get_float(eye_json, "undistort_r2_cutoff"); // clang-format on - const cJSON *distortion = - cJSON_GetObjectItemCaseSensitive(eye_json, "distortion"); + const cJSON *distortion = cJSON_GetObjectItemCaseSensitive(eye_json, "distortion"); if (distortion != NULL) { // TODO: store center per color // clang-format off @@ -1049,42 +955,31 @@ get_distortion_properties(struct survive_device *d, // clang-format on // green - const cJSON *coeffs = - cJSON_GetObjectItemCaseSensitive(distortion, "coeffs"); + const cJSON *coeffs = cJSON_GetObjectItemCaseSensitive(distortion, "coeffs"); if (coeffs != NULL) { _get_color_coeffs(&d->distortion[eye], coeffs, eye, 1); } } - _get_color_coeffs_lookup(&d->distortion[eye], eye_json, - "distortion_red", eye, 0); - _get_color_coeffs_lookup(&d->distortion[eye], eye_json, - "distortion_blue", eye, 2); + _get_color_coeffs_lookup(&d->distortion[eye], eye_json, "distortion_red", eye, 0); + _get_color_coeffs_lookup(&d->distortion[eye], eye_json, "distortion_blue", eye, 2); } static bool -compute_distortion(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result) +compute_distortion(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result) { struct survive_device *d = (struct survive_device *)xdev; return u_compute_distortion_vive(&d->distortion[view], u, v, result); } static bool -_create_hmd_device(struct survive_system *sys, - enum VIVE_VARIANT variant, - const SurviveSimpleObject *sso) +_create_hmd_device(struct survive_system *sys, enum VIVE_VARIANT variant, const SurviveSimpleObject *sso) { - enum u_device_alloc_flags flags = - (enum u_device_alloc_flags)U_DEVICE_ALLOC_HMD; + enum u_device_alloc_flags flags = (enum u_device_alloc_flags)U_DEVICE_ALLOC_HMD; int inputs = 1; int outputs = 0; - struct survive_device *survive = - U_DEVICE_ALLOCATE(struct survive_device, flags, inputs, outputs); + struct survive_device *survive = U_DEVICE_ALLOCATE(struct survive_device, flags, inputs, outputs); sys->hmd = survive; survive->sys = sys; survive->survive_obj = sso; @@ -1123,12 +1018,10 @@ _create_hmd_device(struct survive_system *sys, } - double fov = 2 * atan2(w_meters - lens_horizontal_separation / 2.0, - eye_to_screen_distance); + double fov = 2 * atan2(w_meters - lens_horizontal_separation / 2.0, eye_to_screen_distance); for (int view = 0; view < 2; view++) { - survive->distortion[view].aspect_x_over_y = - 0.89999997615814209f; + survive->distortion[view].aspect_x_over_y = 0.89999997615814209f; survive->distortion[view].grow_for_undistort = 0.5f; survive->distortion[view].undistort_r2_cutoff = 1.0f; } @@ -1142,38 +1035,30 @@ _create_hmd_device(struct survive_system *sys, uint16_t w_pixels = 1080; uint16_t h_pixels = 1200; - const cJSON *device_json = - cJSON_GetObjectItemCaseSensitive(json, "device"); + const cJSON *device_json = cJSON_GetObjectItemCaseSensitive(json, "device"); if (device_json) { if (survive->variant != VIVE_VARIANT_VALVE_INDEX) { survive->distortion[0].aspect_x_over_y = - _json_get_float(device_json, - "physical_aspect_x_over_y"); - survive->distortion[1].aspect_x_over_y = - survive->distortion[0].aspect_x_over_y; + _json_get_float(device_json, "physical_aspect_x_over_y"); + survive->distortion[1].aspect_x_over_y = survive->distortion[0].aspect_x_over_y; //! @todo: fov calculation needs to be fixed, only works //! with hardcoded value // lens_horizontal_separation = _json_get_double(json, // "lens_separation"); } - h_pixels = (uint16_t)_json_get_int( - device_json, "eye_target_height_in_pixels"); - w_pixels = (uint16_t)_json_get_int( - device_json, "eye_target_width_in_pixels"); + h_pixels = (uint16_t)_json_get_int(device_json, "eye_target_height_in_pixels"); + w_pixels = (uint16_t)_json_get_int(device_json, "eye_target_width_in_pixels"); } - const cJSON *eye_transform_json = - cJSON_GetObjectItemCaseSensitive(json, "tracking_to_eye_transform"); + const cJSON *eye_transform_json = cJSON_GetObjectItemCaseSensitive(json, "tracking_to_eye_transform"); if (eye_transform_json) { for (uint8_t eye = 0; eye < 2; eye++) { - get_distortion_properties(survive, eye_transform_json, - eye); + get_distortion_properties(survive, eye_transform_json, eye); } } - SURVIVE_INFO(survive, "Survive eye resolution %dx%d", w_pixels, - h_pixels); + SURVIVE_INFO(survive, "Survive eye resolution %dx%d", w_pixels, h_pixels); cJSON_Delete(json); @@ -1182,11 +1067,9 @@ _create_hmd_device(struct survive_system *sys, survive->base.hmd->screens[0].h_pixels = (int)h_pixels; if (survive->variant == VIVE_VARIANT_VALVE_INDEX) - survive->base.hmd->screens[0].nominal_frame_interval_ns = - (uint64_t)time_s_to_ns(1.0f / 144.0f); + survive->base.hmd->screens[0].nominal_frame_interval_ns = (uint64_t)time_s_to_ns(1.0f / 144.0f); else - survive->base.hmd->screens[0].nominal_frame_interval_ns = - (uint64_t)time_s_to_ns(1.0f / 90.0f); + survive->base.hmd->screens[0].nominal_frame_interval_ns = (uint64_t)time_s_to_ns(1.0f / 90.0f); struct xrt_vec2 lens_center[2]; @@ -1212,13 +1095,9 @@ _create_hmd_device(struct survive_system *sys, survive->base.hmd->views[1].viewport.x_pixels = w_pixels; for (uint8_t eye = 0; eye < 2; eye++) { - if (!math_compute_fovs(w_meters, (double)lens_center[eye].x, - fov, h_meters, - (double)lens_center[eye].y, 0, - &survive->base.hmd->views[eye].fov)) { - SURVIVE_ERROR( - survive, - "Failed to compute the partial fields of view."); + if (!math_compute_fovs(w_meters, (double)lens_center[eye].x, fov, h_meters, (double)lens_center[eye].y, + 0, &survive->base.hmd->views[eye].fov)) { + SURVIVE_ERROR(survive, "Failed to compute the partial fields of view."); free(survive); return NULL; } @@ -1285,30 +1164,25 @@ static struct xrt_binding_profile binding_profiles_vive[1] = { }, }; -#define SET_WAND_INPUT(NAME, NAME2) \ - do { \ - (survive->base.inputs[VIVE_CONTROLLER_##NAME].name = \ - XRT_INPUT_VIVE_##NAME2); \ +#define SET_WAND_INPUT(NAME, NAME2) \ + do { \ + (survive->base.inputs[VIVE_CONTROLLER_##NAME].name = XRT_INPUT_VIVE_##NAME2); \ } while (0) -#define SET_INDEX_INPUT(NAME, NAME2) \ - do { \ - (survive->base.inputs[VIVE_CONTROLLER_##NAME].name = \ - XRT_INPUT_INDEX_##NAME2); \ +#define SET_INDEX_INPUT(NAME, NAME2) \ + do { \ + (survive->base.inputs[VIVE_CONTROLLER_##NAME].name = XRT_INPUT_INDEX_##NAME2); \ } while (0) static bool -_create_controller_device(struct survive_system *sys, - const SurviveSimpleObject *sso, - enum VIVE_VARIANT variant) +_create_controller_device(struct survive_system *sys, const SurviveSimpleObject *sso, enum VIVE_VARIANT variant) { enum u_device_alloc_flags flags = 0; int inputs = VIVE_CONTROLLER_MAX_INDEX; int outputs = 1; - struct survive_device *survive = - U_DEVICE_ALLOCATE(struct survive_device, flags, inputs, outputs); + struct survive_device *survive = U_DEVICE_ALLOCATE(struct survive_device, flags, inputs, outputs); int idx = -1; if (variant == VIVE_VARIANT_HTC_VIVE_CONTROLLER) { @@ -1324,16 +1198,14 @@ _create_controller_device(struct survive_system *sys, if (sys->controllers[SURVIVE_LEFT_CONTROLLER] == NULL) { idx = SURVIVE_LEFT_CONTROLLER; } else { - SURVIVE_ERROR(survive, - "Only creating 1 left controller!"); + SURVIVE_ERROR(survive, "Only creating 1 left controller!"); return false; } } else if (variant == VIVE_VARIANT_VALVE_INDEX_RIGHT_CONTROLLER) { if (sys->controllers[SURVIVE_RIGHT_CONTROLLER] == NULL) { idx = SURVIVE_RIGHT_CONTROLLER; } else { - SURVIVE_ERROR(survive, - "Only creating 1 right controller!"); + SURVIVE_ERROR(survive, "Only creating 1 right controller!"); return false; } } @@ -1355,8 +1227,7 @@ _create_controller_device(struct survive_system *sys, if (variant == VIVE_VARIANT_VALVE_INDEX_LEFT_CONTROLLER || variant == VIVE_VARIANT_VALVE_INDEX_RIGHT_CONTROLLER) { survive->base.name = XRT_DEVICE_INDEX_CONTROLLER; - snprintf(survive->base.str, XRT_DEVICE_NAME_LEN, - "Survive Valve Index Controller %d", idx); + snprintf(survive->base.str, XRT_DEVICE_NAME_LEN, "Survive Valve Index Controller %d", idx); SET_INDEX_INPUT(SYSTEM_CLICK, SYSTEM_CLICK); SET_INDEX_INPUT(A_CLICK, A_CLICK); @@ -1381,43 +1252,32 @@ _create_controller_device(struct survive_system *sys, SET_INDEX_INPUT(GRIP_POSE, GRIP_POSE); if (variant == VIVE_VARIANT_VALVE_INDEX_LEFT_CONTROLLER) { - survive->base.device_type = - XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER; - survive->base.inputs[VIVE_CONTROLLER_HAND_TRACKING] - .name = XRT_INPUT_GENERIC_HAND_TRACKING_LEFT; - } else if (variant == - VIVE_VARIANT_VALVE_INDEX_RIGHT_CONTROLLER) { - survive->base.device_type = - XRT_DEVICE_TYPE_RIGHT_HAND_CONTROLLER; - survive->base.inputs[VIVE_CONTROLLER_HAND_TRACKING] - .name = XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT; + survive->base.device_type = XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER; + survive->base.inputs[VIVE_CONTROLLER_HAND_TRACKING].name = XRT_INPUT_GENERIC_HAND_TRACKING_LEFT; + } else if (variant == VIVE_VARIANT_VALVE_INDEX_RIGHT_CONTROLLER) { + survive->base.device_type = XRT_DEVICE_TYPE_RIGHT_HAND_CONTROLLER; + survive->base.inputs[VIVE_CONTROLLER_HAND_TRACKING].name = + XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT; } else { - survive->base.device_type = - XRT_DEVICE_TYPE_ANY_HAND_CONTROLLER; + survive->base.device_type = XRT_DEVICE_TYPE_ANY_HAND_CONTROLLER; } - survive->base.get_hand_tracking = - survive_controller_get_hand_tracking; + survive->base.get_hand_tracking = survive_controller_get_hand_tracking; - enum xrt_hand hand = idx == SURVIVE_LEFT_CONTROLLER - ? XRT_HAND_LEFT - : XRT_HAND_RIGHT; - u_hand_joints_init_default_set( - &survive->ctrl.hand_tracking, hand, - XRT_HAND_TRACKING_MODEL_FINGERL_CURL, 1.0); + enum xrt_hand hand = idx == SURVIVE_LEFT_CONTROLLER ? XRT_HAND_LEFT : XRT_HAND_RIGHT; + u_hand_joints_init_default_set(&survive->ctrl.hand_tracking, hand, XRT_HAND_TRACKING_MODEL_FINGERL_CURL, + 1.0); survive->base.outputs[0].name = XRT_OUTPUT_NAME_INDEX_HAPTIC; survive->base.binding_profiles = binding_profiles_index; - survive->base.num_binding_profiles = - ARRAY_SIZE(binding_profiles_index); + survive->base.num_binding_profiles = ARRAY_SIZE(binding_profiles_index); survive->base.hand_tracking_supported = true; } else if (survive->variant == VIVE_VARIANT_HTC_VIVE_CONTROLLER) { survive->base.name = XRT_DEVICE_VIVE_WAND; - snprintf(survive->base.str, XRT_DEVICE_NAME_LEN, - "Survive Vive Wand Controller %d", idx); + snprintf(survive->base.str, XRT_DEVICE_NAME_LEN, "Survive Vive Wand Controller %d", idx); SET_WAND_INPUT(SYSTEM_CLICK, SYSTEM_CLICK); SET_WAND_INPUT(SQUEEZE_CLICK, SQUEEZE_CLICK); @@ -1434,8 +1294,7 @@ _create_controller_device(struct survive_system *sys, survive->base.outputs[0].name = XRT_OUTPUT_NAME_VIVE_HAPTIC; survive->base.binding_profiles = binding_profiles_vive; - survive->base.num_binding_profiles = - ARRAY_SIZE(binding_profiles_vive); + survive->base.num_binding_profiles = ARRAY_SIZE(binding_profiles_vive); survive->base.device_type = XRT_DEVICE_TYPE_ANY_HAND_CONTROLLER; } @@ -1457,14 +1316,11 @@ _product_to_variant(uint16_t product_id) case VIVE_PID: return VIVE_VARIANT_VIVE; case VIVE_PRO_MAINBOARD_PID: return VIVE_VARIANT_PRO; case VIVE_PRO_LHR_PID: return VIVE_VARIANT_VALVE_INDEX; - default: - U_LOG_W("No product ids matched %.4x", product_id); - return VIVE_UNKNOWN; + default: U_LOG_W("No product ids matched %.4x", product_id); return VIVE_UNKNOWN; } } -#define JSON_STRING(a, b, c) \ - u_json_get_string_into_array(u_json_get(a, b), c, sizeof(c)) +#define JSON_STRING(a, b, c) u_json_get_string_into_array(u_json_get(a, b), c, sizeof(c)) static enum VIVE_VARIANT get_variant_from_json(struct survive_system *ss, cJSON *json) @@ -1526,8 +1382,7 @@ survive_found(struct xrt_prober *xp, //"--use-imu", "0", //"--use-kalman", "0" }; - actx = survive_simple_init( - sizeof(survive_args) / sizeof(survive_args[0]), survive_args); + actx = survive_simple_init(sizeof(survive_args) / sizeof(survive_args[0]), survive_args); #else actx = survive_simple_init(0, 0); #endif @@ -1545,8 +1400,7 @@ survive_found(struct xrt_prober *xp, ss->ctx = actx; ss->base.type = XRT_TRACKING_TYPE_LIGHTHOUSE; - snprintf(ss->base.name, XRT_TRACKING_NAME_LEN, "%s", - "Libsurvive Tracking"); + snprintf(ss->base.name, XRT_TRACKING_NAME_LEN, "%s", "Libsurvive Tracking"); ss->base.offset.position.x = 0.0f; ss->base.offset.position.y = 0.0f; ss->base.offset.position.z = 0.0f; @@ -1557,38 +1411,32 @@ survive_found(struct xrt_prober *xp, /* iterate over all devices, if SurviveSimpleObject_OBJECT parse config * and if controller, add it with variant from config. */ - for (const SurviveSimpleObject *it = - survive_simple_get_first_object(ss->ctx); - it != 0; it = survive_simple_get_next_object(ss->ctx, it)) { + for (const SurviveSimpleObject *it = survive_simple_get_first_object(ss->ctx); it != 0; + it = survive_simple_get_next_object(ss->ctx, it)) { if (!wait_for_device_config(it)) { - U_LOG_IFL_E(ss->ll, - "Failed to get device config from survive"); + U_LOG_IFL_E(ss->ll, "Failed to get device config from survive"); continue; } U_LOG_IFL_D(ss->ll, "Got device config from survive"); - enum SurviveSimpleObject_type type = - survive_simple_object_get_type(it); + enum SurviveSimpleObject_type type = survive_simple_object_get_type(it); if (type == SurviveSimpleObject_HMD) { - enum VIVE_VARIANT variant = - _product_to_variant(dev->product_id); + enum VIVE_VARIANT variant = _product_to_variant(dev->product_id); U_LOG_I("survive HMD: Assuming variant %d", variant); _create_hmd_device(ss, variant, it); } else if (type == SurviveSimpleObject_OBJECT) { char *json_string = survive_get_json_config(it); cJSON *json = cJSON_Parse(json_string); if (!cJSON_IsObject(json)) { - U_LOG_IFL_E(ss->ll, - "Could not parse JSON data."); + U_LOG_IFL_E(ss->ll, "Could not parse JSON data."); cJSON_Delete(json); continue; } - enum VIVE_VARIANT variant = - get_variant_from_json(ss, json); + enum VIVE_VARIANT variant = get_variant_from_json(ss, json); switch (variant) { case VIVE_VARIANT_HTC_VIVE_CONTROLLER: @@ -1613,8 +1461,7 @@ survive_found(struct xrt_prober *xp, if (ss->ll <= U_LOGGING_DEBUG) { if (ss->hmd) { - u_device_dump_config(&ss->hmd->base, __func__, - "libsurvive"); + u_device_dump_config(&ss->hmd->base, __func__, "libsurvive"); } } @@ -1623,12 +1470,10 @@ survive_found(struct xrt_prober *xp, out_xdevs[out_idx++] = &ss->hmd->base; } if (&ss->controllers[SURVIVE_LEFT_CONTROLLER]) { - out_xdevs[out_idx++] = - &ss->controllers[SURVIVE_LEFT_CONTROLLER]->base; + out_xdevs[out_idx++] = &ss->controllers[SURVIVE_LEFT_CONTROLLER]->base; } if (&ss->controllers[SURVIVE_LEFT_CONTROLLER]) { - out_xdevs[out_idx++] = - &ss->controllers[SURVIVE_RIGHT_CONTROLLER]->base; + out_xdevs[out_idx++] = &ss->controllers[SURVIVE_RIGHT_CONTROLLER]->base; } survive_already_initialized = true; diff --git a/src/xrt/drivers/v4l2/v4l2_driver.c b/src/xrt/drivers/v4l2/v4l2_driver.c index fb388129a..691231ea4 100644 --- a/src/xrt/drivers/v4l2/v4l2_driver.c +++ b/src/xrt/drivers/v4l2/v4l2_driver.c @@ -48,21 +48,21 @@ #define V4L2_WARN(d, ...) U_LOG_IFL_W(d->ll, __VA_ARGS__) #define V4L2_ERROR(d, ...) U_LOG_IFL_E(d->ll, __VA_ARGS__) -#define V_CONTROL_GET(VID, CONTROL) \ - do { \ - int _value = 0; \ - if (v4l2_control_get(VID, V4L2_CID_##CONTROL, &_value) != 0) { \ - V4L2_ERROR(VID, "failed to get V4L2_CID_" #CONTROL); \ - } else { \ - V4L2_DEBUG(VID, "V4L2_CID_" #CONTROL " = %i", _value); \ - } \ +#define V_CONTROL_GET(VID, CONTROL) \ + do { \ + int _value = 0; \ + if (v4l2_control_get(VID, V4L2_CID_##CONTROL, &_value) != 0) { \ + V4L2_ERROR(VID, "failed to get V4L2_CID_" #CONTROL); \ + } else { \ + V4L2_DEBUG(VID, "V4L2_CID_" #CONTROL " = %i", _value); \ + } \ } while (false); -#define V_CONTROL_SET(VID, CONTROL, VALUE) \ - do { \ - if (v4l2_control_set(VID, V4L2_CID_##CONTROL, VALUE) != 0) { \ - V4L2_ERROR(VID, "failed to set V4L2_CID_" #CONTROL); \ - } \ +#define V_CONTROL_SET(VID, CONTROL, VALUE) \ + do { \ + if (v4l2_control_set(VID, V4L2_CID_##CONTROL, VALUE) != 0) { \ + V4L2_ERROR(VID, "failed to set V4L2_CID_" #CONTROL); \ + } \ } while (false); DEBUG_GET_ONCE_LOG_OPTION(v4l2_log, "V4L2_LOG", U_LOGGING_WARN) @@ -250,11 +250,7 @@ v4l2_control_set(struct v4l2_fs *vid, uint32_t id, int value) } static void -v4l2_add_control_state(struct v4l2_fs *vid, - int control, - struct v4l2_state_want want[2], - int force, - const char *name) +v4l2_add_control_state(struct v4l2_fs *vid, int control, struct v4l2_state_want want[2], int force, const char *name) { struct v4l2_control_state *state = &vid->states[vid->num_states++]; @@ -327,15 +323,12 @@ v4l2_query_cap_and_validate(struct v4l2_fs *vid) /* * Find quirks */ - vid->quirks.ps4_cam = - strcmp(card, "USB Camera-OV580: USB Camera-OV") == 0; - -#define ADD(CONTROL, WANT1, WANT2, WANT3, WANT4, NAME) \ - do { \ - struct v4l2_state_want want[2] = {{WANT1, WANT2}, \ - {WANT3, WANT4}}; \ - v4l2_add_control_state(vid, V4L2_CID_##CONTROL, want, 2, \ - NAME); \ + vid->quirks.ps4_cam = strcmp(card, "USB Camera-OV580: USB Camera-OV") == 0; + +#define ADD(CONTROL, WANT1, WANT2, WANT3, WANT4, NAME) \ + do { \ + struct v4l2_state_want want[2] = {{WANT1, WANT2}, {WANT3, WANT4}}; \ + v4l2_add_control_state(vid, V4L2_CID_##CONTROL, want, 2, NAME); \ } while (false) if (vid->quirks.ps4_cam) { @@ -405,12 +398,9 @@ v4l2_try_mmap(struct v4l2_fs *vid, struct v4l2_requestbuffers *v_bufrequest) } static int -v4l2_setup_mmap_buffer(struct v4l2_fs *vid, - struct v4l2_frame *vf, - struct v4l2_buffer *v_buf) +v4l2_setup_mmap_buffer(struct v4l2_fs *vid, struct v4l2_frame *vf, struct v4l2_buffer *v_buf) { - void *ptr = mmap(0, v_buf->length, PROT_READ, MAP_SHARED, vid->fd, - v_buf->m.offset); + void *ptr = mmap(0, v_buf->length, PROT_READ, MAP_SHARED, vid->fd, v_buf->m.offset); if (ptr == MAP_FAILED) { V4L2_ERROR(vid, "error: Call to mmap failed!"); return -1; @@ -422,9 +412,7 @@ v4l2_setup_mmap_buffer(struct v4l2_fs *vid, } static int -v4l2_setup_userptr_buffer(struct v4l2_fs *vid, - struct v4l2_frame *vf, - struct v4l2_buffer *v_buf) +v4l2_setup_userptr_buffer(struct v4l2_fs *vid, struct v4l2_frame *vf, struct v4l2_buffer *v_buf) { // align this to a memory page, v4l2 likes it that way long sz = sysconf(_SC_PAGESIZE); @@ -453,8 +441,7 @@ static struct v4l2_source_descriptor * v4l2_add_descriptor(struct v4l2_fs *vid) { uint32_t index = vid->num_descriptors++; - U_ARRAY_REALLOC_OR_FREE(vid->descriptors, struct v4l2_source_descriptor, - vid->num_descriptors); + U_ARRAY_REALLOC_OR_FREE(vid->descriptors, struct v4l2_source_descriptor, vid->num_descriptors); struct v4l2_source_descriptor *desc = &vid->descriptors[index]; U_ZERO(desc); @@ -468,26 +455,19 @@ v4l2_list_modes_interval(struct v4l2_fs *vid, const struct v4l2_frmsizeenum *size, const struct v4l2_frmivalenum *interval) { - if (interval->discrete.denominator % interval->discrete.numerator == - 0) { - int fps = interval->discrete.denominator / - interval->discrete.numerator; + if (interval->discrete.denominator % interval->discrete.numerator == 0) { + int fps = interval->discrete.denominator / interval->discrete.numerator; - V4L2_DEBUG(vid, "#%i %dx%d@%i", vid->num_descriptors, - interval->width, interval->height, fps); + V4L2_DEBUG(vid, "#%i %dx%d@%i", vid->num_descriptors, interval->width, interval->height, fps); } else { - double fps = (double)interval->discrete.denominator / - (double)interval->discrete.numerator; + double fps = (double)interval->discrete.denominator / (double)interval->discrete.numerator; - V4L2_DEBUG(vid, "#%i %dx%d@%f", vid->num_descriptors, - interval->width, interval->height, fps); + V4L2_DEBUG(vid, "#%i %dx%d@%f", vid->num_descriptors, interval->width, interval->height, fps); } } static void -v4l2_list_modes_size(struct v4l2_fs *vid, - const struct v4l2_fmtdesc *fmt, - const struct v4l2_frmsizeenum *size) +v4l2_list_modes_size(struct v4l2_fs *vid, const struct v4l2_fmtdesc *fmt, const struct v4l2_frmsizeenum *size) { if (size->type != V4L2_FRMSIZE_TYPE_DISCRETE) { V4L2_DEBUG(vid, "warning: Skipping non discrete frame size."); @@ -527,13 +507,11 @@ v4l2_list_modes_size(struct v4l2_fs *vid, desc->stream.width = interval.width; desc->stream.height = interval.height; desc->stream.format = interval.pixel_format; - snprintf(desc->format_name, sizeof(desc->format_name), "%s", - fmt->description); + snprintf(desc->format_name, sizeof(desc->format_name), "%s", fmt->description); if (u_format_is_blocks(format)) { - u_format_size_for_dimensions( - format, interval.width, interval.height, - &desc->stream.stride, &desc->stream.size); + u_format_size_for_dimensions(format, interval.width, interval.height, &desc->stream.stride, + &desc->stream.size); } // Fill out the out sink variables. @@ -546,17 +524,13 @@ v4l2_list_modes_size(struct v4l2_fs *vid, static void v4l2_list_modes_fmt(struct v4l2_fs *vid, const struct v4l2_fmtdesc *fmt) { - V4L2_DEBUG(vid, "format: %s %08x %d", fmt->description, - fmt->pixelformat, fmt->type); + V4L2_DEBUG(vid, "format: %s %08x %d", fmt->description, fmt->pixelformat, fmt->type); switch (fmt->pixelformat) { case V4L2_PIX_FMT_YUYV: break; case V4L2_PIX_FMT_UYVY: break; case V4L2_PIX_FMT_MJPEG: break; - default: - V4L2_ERROR(vid, "error: Unknown pixelformat '%s' '%08x'", - fmt->description, fmt->pixelformat); - return; + default: V4L2_ERROR(vid, "error: Unknown pixelformat '%s' '%08x'", fmt->description, fmt->pixelformat); return; } struct v4l2_frmsizeenum size = {0}; @@ -637,17 +611,14 @@ v4l2_update_controls(struct v4l2_fs *vid) */ static bool -v4l2_fs_enumerate_modes(struct xrt_fs *xfs, - struct xrt_fs_mode **out_modes, - uint32_t *out_count) +v4l2_fs_enumerate_modes(struct xrt_fs *xfs, struct xrt_fs_mode **out_modes, uint32_t *out_count) { struct v4l2_fs *vid = v4l2_fs(xfs); if (vid->num_descriptors == 0) { return false; } - struct xrt_fs_mode *modes = - U_TYPED_ARRAY_CALLOC(struct xrt_fs_mode, vid->num_descriptors); + struct xrt_fs_mode *modes = U_TYPED_ARRAY_CALLOC(struct xrt_fs_mode, vid->num_descriptors); if (modes == NULL) { return false; } @@ -663,8 +634,7 @@ v4l2_fs_enumerate_modes(struct xrt_fs *xfs, } static bool -v4l2_fs_configure_capture(struct xrt_fs *xfs, - struct xrt_fs_capture_parameters *cp) +v4l2_fs_configure_capture(struct xrt_fs *xfs, struct xrt_fs_capture_parameters *cp) { // struct v4l2_fs *vid = v4l2_fs(xfs); //! @todo @@ -680,8 +650,7 @@ v4l2_fs_stream_start(struct xrt_fs *xfs, struct v4l2_fs *vid = v4l2_fs(xfs); if (descriptor_index >= vid->num_descriptors) { - V4L2_ERROR(vid, "error Invalid descriptor_index (%i >= %i)", - descriptor_index, vid->num_descriptors); + V4L2_ERROR(vid, "error Invalid descriptor_index (%i >= %i)", descriptor_index, vid->num_descriptors); return false; } vid->selected = descriptor_index; @@ -689,8 +658,7 @@ v4l2_fs_stream_start(struct xrt_fs *xfs, vid->sink = xs; vid->is_running = true; vid->capture_type = capture_type; - if (pthread_create(&vid->stream_thread, NULL, v4l2_fs_stream_run, - xfs)) { + if (pthread_create(&vid->stream_thread, NULL, v4l2_fs_stream_run, xfs)) { vid->is_running = false; V4L2_ERROR(vid, "error: Could not create thread"); return false; @@ -860,10 +828,8 @@ v4l2_fs_stream_run(void *ptr) v_bufrequest.count = NUM_V4L2_BUFFERS; v_bufrequest.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - if (v4l2_try_userptr(vid, &v_bufrequest) != 0 && - v4l2_try_mmap(vid, &v_bufrequest) != 0) { - V4L2_ERROR(vid, - "error: Driver does not support mmap or userptr."); + if (v4l2_try_userptr(vid, &v_bufrequest) != 0 && v4l2_try_mmap(vid, &v_bufrequest) != 0) { + V4L2_ERROR(vid, "error: Driver does not support mmap or userptr."); return NULL; } @@ -884,12 +850,10 @@ v4l2_fs_stream_run(void *ptr) return NULL; } - if (vid->capture.userptr && - v4l2_setup_userptr_buffer(vid, vf, v_buf) != 0) { + if (vid->capture.userptr && v4l2_setup_userptr_buffer(vid, vf, v_buf) != 0) { return NULL; } - if (vid->capture.mmap && - v4l2_setup_mmap_buffer(vid, vf, v_buf) != 0) { + if (vid->capture.mmap && v4l2_setup_mmap_buffer(vid, vf, v_buf) != 0) { return NULL; } @@ -927,8 +891,7 @@ v4l2_fs_stream_run(void *ptr) v4l2_update_controls(vid); - V4L2_TRACE(vid, "Got frame #%u, index %i", v_buf.sequence, - v_buf.index); + V4L2_TRACE(vid, "Got frame #%u, index %i", v_buf.sequence, v_buf.index); struct v4l2_frame *vf = &vid->frames[v_buf.index]; struct xrt_frame *xf = NULL; @@ -975,8 +938,7 @@ static void dump_integer(struct v4l2_fs *vid, struct v4l2_queryctrl *queryctrl) { U_LOG_D(" Type: Integer"); - U_LOG_D(" min: %i, max: %i, step: %i.", queryctrl->minimum, - queryctrl->maximum, queryctrl->step); + U_LOG_D(" min: %i, max: %i, step: %i.", queryctrl->minimum, queryctrl->maximum, queryctrl->step); } static void @@ -1001,7 +963,7 @@ dump_contron_name(uint32_t id) { const char *str = "ERROR"; switch (id) { -#define CASE(CONTROL) \ +#define CASE(CONTROL) \ case V4L2_CID_##CONTROL: str = "V4L2_CID_" #CONTROL; break CASE(BRIGHTNESS); CASE(CONTRAST); @@ -1087,11 +1049,11 @@ dump_controls(struct v4l2_fs *vid) dump_contron_name(queryctrl.id); fprintf(stderr, " '%s'", queryctrl.name); -#define V_CHECK(FLAG) \ - do { \ - if (queryctrl.flags & V4L2_CTRL_FLAG_##FLAG) { \ - fprintf(stderr, ", " #FLAG); \ - } \ +#define V_CHECK(FLAG) \ + do { \ + if (queryctrl.flags & V4L2_CTRL_FLAG_##FLAG) { \ + fprintf(stderr, ", " #FLAG); \ + } \ } while (false) V_CHECK(DISABLED); @@ -1111,17 +1073,10 @@ dump_controls(struct v4l2_fs *vid) switch (queryctrl.type) { case V4L2_CTRL_TYPE_BOOLEAN: U_LOG_D(" Type: Boolean"); break; - case V4L2_CTRL_TYPE_INTEGER: - dump_integer(vid, &queryctrl); - break; - case V4L2_CTRL_TYPE_INTEGER64: - U_LOG_D(" Type: Integer64"); - break; + case V4L2_CTRL_TYPE_INTEGER: dump_integer(vid, &queryctrl); break; + case V4L2_CTRL_TYPE_INTEGER64: U_LOG_D(" Type: Integer64"); break; case V4L2_CTRL_TYPE_BUTTON: U_LOG_D(" Type: Buttons"); break; - case V4L2_CTRL_TYPE_MENU: - dump_menu(vid, queryctrl.id, queryctrl.minimum, - queryctrl.maximum); - break; + case V4L2_CTRL_TYPE_MENU: dump_menu(vid, queryctrl.id, queryctrl.minimum, queryctrl.maximum); break; case V4L2_CTRL_TYPE_STRING: U_LOG_D(" Type: String"); break; default: U_LOG_D(" Type: Unknown"); break; } diff --git a/src/xrt/drivers/vf/vf_driver.c b/src/xrt/drivers/vf/vf_driver.c index dba977b11..c5d9225c4 100644 --- a/src/xrt/drivers/vf/vf_driver.c +++ b/src/xrt/drivers/vf/vf_driver.c @@ -114,9 +114,7 @@ vf_fs(struct xrt_fs *xfs) */ static bool -vf_fs_enumerate_modes(struct xrt_fs *xfs, - struct xrt_fs_mode **out_modes, - uint32_t *out_count) +vf_fs_enumerate_modes(struct xrt_fs *xfs, struct xrt_fs_mode **out_modes, uint32_t *out_count) { struct vf_fs *vid = vf_fs(xfs); @@ -137,8 +135,7 @@ vf_fs_enumerate_modes(struct xrt_fs *xfs, } static bool -vf_fs_configure_capture(struct xrt_fs *xfs, - struct xrt_fs_capture_parameters *cp) +vf_fs_configure_capture(struct xrt_fs *xfs, struct xrt_fs_capture_parameters *cp) { // struct vf_fs *vid = vf_fs(xfs); //! @todo @@ -239,8 +236,7 @@ vf_fs_frame(struct vf_fs *vid, GstSample *sample) struct xrt_frame *xf = NULL; - u_frame_create_one_off(vid->format, vid->width, vid->height, - &xf); + u_frame_create_one_off(vid->format, vid->width, vid->height, &xf); //! @todo Sequence number and timestamp. xf->width = vid->width; @@ -307,8 +303,7 @@ print_gst_error(GstMessage *message) gchar *dbg_info = NULL; gst_message_parse_error(message, &err, &dbg_info); - U_LOG_E("ERROR from element %s: %s\n", GST_OBJECT_NAME(message->src), - err->message); + U_LOG_E("ERROR from element %s: %s\n", GST_OBJECT_NAME(message->src), err->message); U_LOG_E("Debugging info: %s\n", (dbg_info) ? dbg_info : "none"); g_error_free(err); g_free(dbg_info); @@ -408,17 +403,14 @@ vf_fs_create(struct xrt_frame_context *xfctx, const char *path) } vid->testsink = gst_bin_get_by_name(GST_BIN(vid->source), "testsink"); - g_object_set(G_OBJECT(vid->testsink), "emit-signals", TRUE, "sync", - TRUE, NULL); - g_signal_connect(vid->testsink, "new-sample", - G_CALLBACK(on_new_sample_from_sink), vid); + g_object_set(G_OBJECT(vid->testsink), "emit-signals", TRUE, "sync", TRUE, NULL); + g_signal_connect(vid->testsink, "new-sample", G_CALLBACK(on_new_sample_from_sink), vid); bus = gst_element_get_bus(vid->source); gst_bus_add_watch(bus, (GstBusFunc)on_source_message, vid); gst_object_unref(bus); - int ret = - os_thread_helper_start(&vid->play_thread, run_play_thread, vid); + int ret = os_thread_helper_start(&vid->play_thread, run_play_thread, vid); if (!ret) { VF_ERROR(vid, "Failed to start thread"); } diff --git a/src/xrt/drivers/vive/vive_config.c b/src/xrt/drivers/vive/vive_config.c index e2346950b..035593866 100644 --- a/src/xrt/drivers/vive/vive_config.c +++ b/src/xrt/drivers/vive/vive_config.c @@ -25,14 +25,10 @@ #define JSON_DOUBLE(a, b, c) u_json_get_double(u_json_get(a, b), c) #define JSON_VEC3(a, b, c) u_json_get_vec3_array(u_json_get(a, b), c) #define JSON_MATRIX_3X3(a, b, c) u_json_get_matrix_3x3(u_json_get(a, b), c) -#define JSON_STRING(a, b, c) \ - u_json_get_string_into_array(u_json_get(a, b), c, sizeof(c)) +#define JSON_STRING(a, b, c) u_json_get_string_into_array(u_json_get(a, b), c, sizeof(c)) static void -_get_color_coeffs(struct u_vive_values *values, - const cJSON *coeffs, - uint8_t eye, - uint8_t channel) +_get_color_coeffs(struct u_vive_values *values, const cJSON *coeffs, uint8_t eye, uint8_t channel) { // this is 4 on index, all values populated // assert(coeffs->length == 8); @@ -50,20 +46,15 @@ _get_color_coeffs(struct u_vive_values *values, } static void -_get_color_coeffs_lookup(struct u_vive_values *values, - const cJSON *eye_json, - const char *name, - uint8_t eye, - uint8_t channel) +_get_color_coeffs_lookup( + struct u_vive_values *values, const cJSON *eye_json, const char *name, uint8_t eye, uint8_t channel) { - const cJSON *distortion = - cJSON_GetObjectItemCaseSensitive(eye_json, name); + const cJSON *distortion = cJSON_GetObjectItemCaseSensitive(eye_json, name); if (distortion == NULL) { return; } - const cJSON *coeffs = - cJSON_GetObjectItemCaseSensitive(distortion, "coeffs"); + const cJSON *coeffs = cJSON_GetObjectItemCaseSensitive(distortion, "coeffs"); if (coeffs == NULL) { return; } @@ -83,9 +74,7 @@ _get_pose_from_pos_x_z(const cJSON *obj, struct xrt_pose *pose) } static void -_get_distortion_properties(struct vive_device *d, - const cJSON *eye_transform_json, - uint8_t eye) +_get_distortion_properties(struct vive_device *d, const cJSON *eye_transform_json, uint8_t eye) { const cJSON *eye_json = cJSON_GetArrayItem(eye_transform_json, eye); if (eye_json == NULL) { @@ -103,8 +92,7 @@ _get_distortion_properties(struct vive_device *d, JSON_FLOAT(eye_json, "undistort_r2_cutoff", &d->distortion[eye].undistort_r2_cutoff); // clang-format on - const cJSON *distortion = - cJSON_GetObjectItemCaseSensitive(eye_json, "distortion"); + const cJSON *distortion = cJSON_GetObjectItemCaseSensitive(eye_json, "distortion"); if (distortion != NULL) { // TODO: store center per color // clang-format off @@ -113,34 +101,27 @@ _get_distortion_properties(struct vive_device *d, // clang-format on // green - const cJSON *coeffs = - cJSON_GetObjectItemCaseSensitive(distortion, "coeffs"); + const cJSON *coeffs = cJSON_GetObjectItemCaseSensitive(distortion, "coeffs"); if (coeffs != NULL) { _get_color_coeffs(&d->distortion[eye], coeffs, eye, 1); } } - _get_color_coeffs_lookup(&d->distortion[eye], eye_json, - "distortion_red", eye, 0); - _get_color_coeffs_lookup(&d->distortion[eye], eye_json, - "distortion_blue", eye, 2); + _get_color_coeffs_lookup(&d->distortion[eye], eye_json, "distortion_red", eye, 0); + _get_color_coeffs_lookup(&d->distortion[eye], eye_json, "distortion_blue", eye, 2); } static void _get_lighthouse(struct vive_device *d, const cJSON *json) { - const cJSON *lh = - cJSON_GetObjectItemCaseSensitive(json, "lighthouse_config"); + const cJSON *lh = cJSON_GetObjectItemCaseSensitive(json, "lighthouse_config"); if (lh == NULL) { return; } - const cJSON *json_map = - cJSON_GetObjectItemCaseSensitive(lh, "channelMap"); - const cJSON *json_normals = - cJSON_GetObjectItemCaseSensitive(lh, "modelNormals"); - const cJSON *json_points = - cJSON_GetObjectItemCaseSensitive(lh, "modelPoints"); + const cJSON *json_map = cJSON_GetObjectItemCaseSensitive(lh, "channelMap"); + const cJSON *json_normals = cJSON_GetObjectItemCaseSensitive(lh, "modelNormals"); + const cJSON *json_points = cJSON_GetObjectItemCaseSensitive(lh, "modelPoints"); if (json_map == NULL || json_normals == NULL || json_points == NULL) { return; @@ -150,8 +131,7 @@ _get_lighthouse(struct vive_device *d, const cJSON *json) size_t normals_size = cJSON_GetArraySize(json_normals); size_t points_size = cJSON_GetArraySize(json_points); - if (map_size != normals_size || normals_size != points_size || - map_size <= 0) { + if (map_size != normals_size || normals_size != points_size || map_size <= 0) { return; } @@ -200,18 +180,15 @@ _get_lighthouse(struct vive_device *d, const cJSON *json) struct xrt_vec3 point = d->lh.sensors[i].pos; struct xrt_vec3 normal = d->lh.sensors[i].normal; - math_quat_rotate_vec3(&trackref_to_imu.orientation, &normal, - &d->lh.sensors[i].normal); - math_pose_transform_point(&trackref_to_imu, &point, - &d->lh.sensors[i].pos); + math_quat_rotate_vec3(&trackref_to_imu.orientation, &normal, &d->lh.sensors[i].normal); + math_pose_transform_point(&trackref_to_imu, &point, &d->lh.sensors[i].pos); } } static void _print_vec3(const char *title, struct xrt_vec3 *vec) { - U_LOG_D("%s = %f %f %f", title, (double)vec->x, (double)vec->y, - (double)vec->z); + U_LOG_D("%s = %f %f %f", title, (double)vec->x, (double)vec->y, (double)vec->z); } bool @@ -233,20 +210,17 @@ vive_config_parse(struct vive_device *d, char *json_string) JSON_VEC3(json, "gyro_scale", &d->imu.gyro_scale); break; case VIVE_VARIANT_PRO: { - const cJSON *imu = - cJSON_GetObjectItemCaseSensitive(json, "imu"); + const cJSON *imu = cJSON_GetObjectItemCaseSensitive(json, "imu"); JSON_VEC3(imu, "acc_bias", &d->imu.acc_bias); JSON_VEC3(imu, "acc_scale", &d->imu.acc_scale); JSON_VEC3(imu, "gyro_bias", &d->imu.gyro_bias); JSON_VEC3(imu, "gyro_scale", &d->imu.gyro_scale); } break; case VIVE_VARIANT_INDEX: { - const cJSON *head = - cJSON_GetObjectItemCaseSensitive(json, "head"); + const cJSON *head = cJSON_GetObjectItemCaseSensitive(json, "head"); _get_pose_from_pos_x_z(head, &d->display.trackref); - const cJSON *imu = - cJSON_GetObjectItemCaseSensitive(json, "imu"); + const cJSON *imu = cJSON_GetObjectItemCaseSensitive(json, "imu"); _get_pose_from_pos_x_z(imu, &d->imu.trackref); JSON_VEC3(imu, "acc_bias", &d->imu.acc_bias); @@ -259,8 +233,7 @@ vive_config_parse(struct vive_device *d, char *json_string) struct xrt_pose imu_to_head; math_pose_invert(&d->display.trackref, &trackref_to_head); - math_pose_transform(&trackref_to_head, &d->imu.trackref, - &imu_to_head); + math_pose_transform(&trackref_to_head, &d->imu.trackref, &imu_to_head); d->display.imuref = imu_to_head; } break; @@ -270,37 +243,27 @@ vive_config_parse(struct vive_device *d, char *json_string) JSON_STRING(json, "model_number", d->firmware.model_number); if (d->variant != VIVE_VARIANT_INDEX) { - JSON_STRING(json, "mb_serial_number", - d->firmware.mb_serial_number); + JSON_STRING(json, "mb_serial_number", d->firmware.mb_serial_number); } if (d->variant == VIVE_VARIANT_VIVE) { - JSON_DOUBLE(json, "lens_separation", - &d->display.lens_separation); + JSON_DOUBLE(json, "lens_separation", &d->display.lens_separation); } - JSON_STRING(json, "device_serial_number", - d->firmware.device_serial_number); + JSON_STRING(json, "device_serial_number", d->firmware.device_serial_number); - const cJSON *device_json = - cJSON_GetObjectItemCaseSensitive(json, "device"); + const cJSON *device_json = cJSON_GetObjectItemCaseSensitive(json, "device"); if (device_json) { if (d->variant != VIVE_VARIANT_INDEX) { - JSON_DOUBLE(device_json, "persistence", - &d->display.persistence); - JSON_FLOAT(device_json, "physical_aspect_x_over_y", - &d->distortion[0].aspect_x_over_y); + JSON_DOUBLE(device_json, "persistence", &d->display.persistence); + JSON_FLOAT(device_json, "physical_aspect_x_over_y", &d->distortion[0].aspect_x_over_y); - d->distortion[1].aspect_x_over_y = - d->distortion[0].aspect_x_over_y; + d->distortion[1].aspect_x_over_y = d->distortion[0].aspect_x_over_y; } - JSON_INT(device_json, "eye_target_height_in_pixels", - &d->display.eye_target_height_in_pixels); - JSON_INT(device_json, "eye_target_width_in_pixels", - &d->display.eye_target_width_in_pixels); + JSON_INT(device_json, "eye_target_height_in_pixels", &d->display.eye_target_height_in_pixels); + JSON_INT(device_json, "eye_target_width_in_pixels", &d->display.eye_target_width_in_pixels); } - const cJSON *eye_transform_json = - cJSON_GetObjectItemCaseSensitive(json, "tracking_to_eye_transform"); + const cJSON *eye_transform_json = cJSON_GetObjectItemCaseSensitive(json, "tracking_to_eye_transform"); if (eye_transform_json) { for (uint8_t eye = 0; eye < 2; eye++) { _get_distortion_properties(d, eye_transform_json, eye); @@ -339,8 +302,7 @@ vive_config_parse(struct vive_device *d, char *json_string) } bool -vive_config_parse_controller(struct vive_controller_device *d, - char *json_string) +vive_config_parse_controller(struct vive_controller_device *d, char *json_string) { VIVE_DEBUG(d, "JSON config:\n%s", json_string); @@ -369,8 +331,7 @@ vive_config_parse_controller(struct vive_controller_device *d, } else if (strcmp(d->firmware.model_number, "Vive Tracker PVT") == 0) { d->variant = CONTROLLER_TRACKER_GEN1; VIVE_DEBUG(d, "Found Gen 1 tracker."); - } else if (strcmp(d->firmware.model_number, "VIVE Tracker Pro MV") == - 0) { + } else if (strcmp(d->firmware.model_number, "VIVE Tracker Pro MV") == 0) { d->variant = CONTROLLER_TRACKER_GEN2; VIVE_DEBUG(d, "Found Gen 2 tracker."); } else { @@ -384,8 +345,7 @@ vive_config_parse_controller(struct vive_controller_device *d, JSON_VEC3(json, "acc_scale", &d->imu.acc_scale); JSON_VEC3(json, "gyro_bias", &d->imu.gyro_bias); JSON_VEC3(json, "gyro_scale", &d->imu.gyro_scale); - JSON_STRING(json, "mb_serial_number", - d->firmware.mb_serial_number); + JSON_STRING(json, "mb_serial_number", d->firmware.mb_serial_number); } break; case CONTROLLER_INDEX_LEFT: case CONTROLLER_INDEX_RIGHT: @@ -403,8 +363,7 @@ vive_config_parse_controller(struct vive_controller_device *d, default: VIVE_ERROR(d, "Unknown Vive watchman variant."); return false; } - JSON_STRING(json, "device_serial_number", - d->firmware.device_serial_number); + JSON_STRING(json, "device_serial_number", d->firmware.device_serial_number); cJSON_Delete(json); diff --git a/src/xrt/drivers/vive/vive_config.h b/src/xrt/drivers/vive/vive_config.h index d1b8bc9b2..aa7943601 100644 --- a/src/xrt/drivers/vive/vive_config.h +++ b/src/xrt/drivers/vive/vive_config.h @@ -20,5 +20,4 @@ vive_config_parse(struct vive_device *d, char *json_string); struct vive_controller_device; bool -vive_config_parse_controller(struct vive_controller_device *d, - char *json_string); +vive_config_parse_controller(struct vive_controller_device *d, char *json_string); diff --git a/src/xrt/drivers/vive/vive_controller.c b/src/xrt/drivers/vive/vive_controller.c index 7f2b0e110..4137215c2 100644 --- a/src/xrt/drivers/vive/vive_controller.c +++ b/src/xrt/drivers/vive/vive_controller.c @@ -95,8 +95,7 @@ static inline struct vive_controller_device * vive_controller_device(struct xrt_device *xdev) { assert(xdev); - struct vive_controller_device *ret = - (struct vive_controller_device *)xdev; + struct vive_controller_device *ret = (struct vive_controller_device *)xdev; return ret; } @@ -136,12 +135,9 @@ vive_controller_device_update_wand_inputs(struct xrt_device *xdev) /* d->state.buttons is bitmask of currently pressed buttons. * (index n) nth bit in the bitmask -> input "name" */ - const int button_index_map[] = {VIVE_CONTROLLER_INDEX_TRIGGER_CLICK, - VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH, - VIVE_CONTROLLER_INDEX_TRACKPAD_CLICK, - VIVE_CONTROLLER_INDEX_SYSTEM_CLICK, - VIVE_CONTROLLER_INDEX_SQUEEZE_CLICK, - VIVE_CONTROLLER_INDEX_MENU_CLICK}; + const int button_index_map[] = {VIVE_CONTROLLER_INDEX_TRIGGER_CLICK, VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH, + VIVE_CONTROLLER_INDEX_TRACKPAD_CLICK, VIVE_CONTROLLER_INDEX_SYSTEM_CLICK, + VIVE_CONTROLLER_INDEX_SQUEEZE_CLICK, VIVE_CONTROLLER_INDEX_MENU_CLICK}; int button_count = ARRAY_SIZE(button_index_map); for (int i = 0; i < button_count; i++) { @@ -150,30 +146,25 @@ vive_controller_device_update_wand_inputs(struct xrt_device *xdev) bool last_pressed = (d->state.last_buttons >> i) & 1; if (pressed != last_pressed) { - struct xrt_input *input = - &d->base.inputs[button_index_map[i]]; + struct xrt_input *input = &d->base.inputs[button_index_map[i]]; input->timestamp = now; input->value.boolean = pressed; - VIVE_DEBUG(d, "button %d %s\n", i, - pressed ? "pressed" : "released"); + VIVE_DEBUG(d, "button %d %s\n", i, pressed ? "pressed" : "released"); } } d->state.last_buttons = d->state.buttons; - struct xrt_input *trackpad_input = - &d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD]; + struct xrt_input *trackpad_input = &d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD]; trackpad_input->timestamp = now; trackpad_input->value.vec2.x = d->state.trackpad.x; trackpad_input->value.vec2.y = d->state.trackpad.y; - VIVE_TRACE(d, "Trackpad: %f, %f", d->state.trackpad.x, - d->state.trackpad.y); + VIVE_TRACE(d, "Trackpad: %f, %f", d->state.trackpad.x, d->state.trackpad.y); - struct xrt_input *trigger_input = - &d->base.inputs[VIVE_CONTROLLER_INDEX_TRIGGER_VALUE]; + struct xrt_input *trigger_input = &d->base.inputs[VIVE_CONTROLLER_INDEX_TRIGGER_VALUE]; trigger_input->timestamp = now; trigger_input->value.vec1.x = d->state.trigger; VIVE_TRACE(d, "Trigger: %f", d->state.trigger); @@ -197,20 +188,16 @@ vive_controller_device_update_index_inputs(struct xrt_device *xdev) printf("\n"); */ - bool was_trackpad_touched = - d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH].value.boolean; + bool was_trackpad_touched = d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH].value.boolean; uint64_t now = os_monotonic_get_ns(); /* d->state.buttons is bitmask of currently pressed buttons. * (index n) nth bit in the bitmask -> input "name" */ - const int button_index_map[] = {VIVE_CONTROLLER_INDEX_TRIGGER_CLICK, - VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH, - VIVE_CONTROLLER_INDEX_THUMBSTICK_CLICK, - VIVE_CONTROLLER_INDEX_SYSTEM_CLICK, - VIVE_CONTROLLER_INDEX_A_CLICK, - VIVE_CONTROLLER_INDEX_B_CLICK}; + const int button_index_map[] = {VIVE_CONTROLLER_INDEX_TRIGGER_CLICK, VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH, + VIVE_CONTROLLER_INDEX_THUMBSTICK_CLICK, VIVE_CONTROLLER_INDEX_SYSTEM_CLICK, + VIVE_CONTROLLER_INDEX_A_CLICK, VIVE_CONTROLLER_INDEX_B_CLICK}; int button_count = ARRAY_SIZE(button_index_map); for (int i = 0; i < button_count; i++) { @@ -219,20 +206,17 @@ vive_controller_device_update_index_inputs(struct xrt_device *xdev) bool last_pressed = (d->state.last_buttons >> i) & 1; if (pressed != last_pressed) { - struct xrt_input *input = - &d->base.inputs[button_index_map[i]]; + struct xrt_input *input = &d->base.inputs[button_index_map[i]]; input->timestamp = now; input->value.boolean = pressed; - VIVE_DEBUG(d, "button %d %s\n", i, - pressed ? "pressed" : "released"); + VIVE_DEBUG(d, "button %d %s\n", i, pressed ? "pressed" : "released"); } } d->state.last_buttons = d->state.buttons; - bool is_trackpad_touched = - d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH].value.boolean; + bool is_trackpad_touched = d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH].value.boolean; /* trackpad and thumbstick position are the same usb events. * report trackpad position when trackpad has been touched last, and @@ -249,15 +233,11 @@ vive_controller_device_update_index_inputs(struct xrt_device *xdev) thumb_input->value.vec2.x = d->state.trackpad.x; thumb_input->value.vec2.y = d->state.trackpad.y; - const char *component = is_trackpad_touched || was_trackpad_touched - ? "Trackpad" - : "Thumbstick"; - VIVE_TRACE(d, "%s: %f, %f", component, d->state.trackpad.x, - d->state.trackpad.y); + const char *component = is_trackpad_touched || was_trackpad_touched ? "Trackpad" : "Thumbstick"; + VIVE_TRACE(d, "%s: %f, %f", component, d->state.trackpad.x, d->state.trackpad.y); - struct xrt_input *trigger_input = - &d->base.inputs[VIVE_CONTROLLER_INDEX_TRIGGER_VALUE]; + struct xrt_input *trigger_input = &d->base.inputs[VIVE_CONTROLLER_INDEX_TRIGGER_VALUE]; trigger_input->timestamp = now; trigger_input->value.vec1.x = d->state.trigger; @@ -268,14 +248,13 @@ vive_controller_device_update_index_inputs(struct xrt_device *xdev) /* d->state.touch is bitmask of currently touched buttons. * (index n) nth bit in the bitmask -> input "name" */ - const int touched_button_index_map[] = { - 0, - 0, - 0, - VIVE_CONTROLLER_INDEX_SYSTEM_TOUCH, - VIVE_CONTROLLER_INDEX_A_TOUCH, - VIVE_CONTROLLER_INDEX_B_TOUCH, - VIVE_CONTROLLER_INDEX_THUMBSTICK_TOUCH}; + const int touched_button_index_map[] = {0, + 0, + 0, + VIVE_CONTROLLER_INDEX_SYSTEM_TOUCH, + VIVE_CONTROLLER_INDEX_A_TOUCH, + VIVE_CONTROLLER_INDEX_B_TOUCH, + VIVE_CONTROLLER_INDEX_THUMBSTICK_TOUCH}; int touch_button_count = ARRAY_SIZE(touched_button_index_map); uint8_t touch_buttons = d->state.touch; for (int i = 0; i < touch_button_count; i++) { @@ -284,32 +263,26 @@ vive_controller_device_update_index_inputs(struct xrt_device *xdev) bool last_touched = (d->state.last_touch >> i) & 1; if (touched != last_touched) { - struct xrt_input *input = - &d->base.inputs[touched_button_index_map[i]]; + struct xrt_input *input = &d->base.inputs[touched_button_index_map[i]]; input->timestamp = now; input->value.boolean = touched; - VIVE_DEBUG(d, "button %d %s\n", i, - touched ? "touched" : "untouched"); + VIVE_DEBUG(d, "button %d %s\n", i, touched ? "touched" : "untouched"); } } d->state.last_touch = d->state.touch; - d->base.inputs[VIVE_CONTROLLER_INDEX_SQUEEZE_FORCE].value.vec1.x = - (float)d->state.squeeze_force / UINT8_MAX; + d->base.inputs[VIVE_CONTROLLER_INDEX_SQUEEZE_FORCE].value.vec1.x = (float)d->state.squeeze_force / UINT8_MAX; d->base.inputs[VIVE_CONTROLLER_INDEX_SQUEEZE_FORCE].timestamp = now; if (d->state.squeeze_force > 0) { - VIVE_DEBUG(d, "Squeeze force: %f\n", - (float)d->state.squeeze_force / UINT8_MAX); + VIVE_DEBUG(d, "Squeeze force: %f\n", (float)d->state.squeeze_force / UINT8_MAX); } - d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD_FORCE].value.vec1.x = - (float)d->state.trackpad_force / UINT8_MAX; + d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD_FORCE].value.vec1.x = (float)d->state.trackpad_force / UINT8_MAX; d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD_FORCE].timestamp = now; if (d->state.trackpad_force > 0) { - VIVE_DEBUG(d, "Trackpad force: %f\n", - (float)d->state.trackpad_force / UINT8_MAX); + VIVE_DEBUG(d, "Trackpad force: %f\n", (float)d->state.trackpad_force / UINT8_MAX); } os_thread_helper_unlock(&d->controller_thread); @@ -330,36 +303,29 @@ vive_controller_get_hand_tracking(struct xrt_device *xdev, { struct vive_controller_device *d = vive_controller_device(xdev); - if (name != XRT_INPUT_GENERIC_HAND_TRACKING_LEFT && - name != XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT) { + if (name != XRT_INPUT_GENERIC_HAND_TRACKING_LEFT && name != XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT) { VIVE_ERROR(d, "unknown input name for hand tracker"); return; } - enum xrt_hand hand = d->variant == CONTROLLER_INDEX_LEFT - ? XRT_HAND_LEFT - : XRT_HAND_RIGHT; + enum xrt_hand hand = d->variant == CONTROLLER_INDEX_LEFT ? XRT_HAND_LEFT : XRT_HAND_RIGHT; float thumb_curl = 0.0f; //! @todo place thumb preciely on the button that is touched/pressed if (d->base.inputs[VIVE_CONTROLLER_INDEX_A_TOUCH].value.boolean || d->base.inputs[VIVE_CONTROLLER_INDEX_B_TOUCH].value.boolean || - d->base.inputs[VIVE_CONTROLLER_INDEX_THUMBSTICK_TOUCH] - .value.boolean || - d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH] - .value.boolean) { + d->base.inputs[VIVE_CONTROLLER_INDEX_THUMBSTICK_TOUCH].value.boolean || + d->base.inputs[VIVE_CONTROLLER_INDEX_TRACKPAD_TOUCH].value.boolean) { thumb_curl = 1.0; } - struct u_hand_tracking_curl_values values = { - .little = (float)d->state.pinky_finger_handle / UINT8_MAX, - .ring = (float)d->state.ring_finger_handle / UINT8_MAX, - .middle = (float)d->state.middle_finger_handle / UINT8_MAX, - .index = (float)d->state.index_finger_trigger / UINT8_MAX, - .thumb = thumb_curl}; + struct u_hand_tracking_curl_values values = {.little = (float)d->state.pinky_finger_handle / UINT8_MAX, + .ring = (float)d->state.ring_finger_handle / UINT8_MAX, + .middle = (float)d->state.middle_finger_handle / UINT8_MAX, + .index = (float)d->state.index_finger_trigger / UINT8_MAX, + .thumb = thumb_curl}; - u_hand_joints_update_curl(&d->hand_tracking, hand, at_timestamp_ns, - &values); + u_hand_joints_update_curl(&d->hand_tracking, hand, at_timestamp_ns, &values); /* Because IMU is at the very -z end of the controller, the rotation @@ -371,22 +337,17 @@ vive_controller_get_hand_tracking(struct xrt_device *xdev, float pivot_offset_z = 0.15; struct xrt_space_relation controller_relation = { - .pose = {.orientation = d->rot_filtered, - .position = {0, 0, pivot_offset_z}}}; - controller_relation.relation_flags = - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_VALID_BIT; + .pose = {.orientation = d->rot_filtered, .position = {0, 0, pivot_offset_z}}}; + controller_relation.relation_flags = XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_POSITION_VALID_BIT; struct xrt_vec3 static_offset = {0, 0, 0}; struct xrt_pose hand_on_handle_pose; - u_hand_joints_offset_valve_index_controller(hand, &static_offset, - &hand_on_handle_pose); + u_hand_joints_offset_valve_index_controller(hand, &static_offset, &hand_on_handle_pose); - u_hand_joints_set_out_data(&d->hand_tracking, hand, - &controller_relation, &hand_on_handle_pose, - out_value); + u_hand_joints_set_out_data(&d->hand_tracking, hand, &controller_relation, &hand_on_handle_pose, out_value); } static void @@ -398,9 +359,7 @@ vive_controller_device_get_tracked_pose(struct xrt_device *xdev, struct vive_controller_device *d = vive_controller_device(xdev); // U_LOG_D("input name %d %d", name, XRT_INPUT_VIVE_GRIP_POSE); - if (name != XRT_INPUT_VIVE_AIM_POSE && - name != XRT_INPUT_VIVE_GRIP_POSE && - name != XRT_INPUT_INDEX_AIM_POSE && + if (name != XRT_INPUT_VIVE_AIM_POSE && name != XRT_INPUT_VIVE_GRIP_POSE && name != XRT_INPUT_INDEX_AIM_POSE && name != XRT_INPUT_INDEX_GRIP_POSE) { VIVE_ERROR(d, "unknown input name"); return; @@ -421,41 +380,34 @@ vive_controller_device_get_tracked_pose(struct xrt_device *xdev, //! @todo assuming that orientation is actually currently tracked. out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT | - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + XRT_SPACE_RELATION_POSITION_VALID_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT | + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); os_thread_helper_unlock(&d->controller_thread); struct xrt_vec3 pos = out_relation->pose.position; struct xrt_quat quat = out_relation->pose.orientation; - VIVE_TRACE(d, "GET_TRACKED_POSE (%f, %f, %f) (%f, %f, %f, %f) ", pos.x, - pos.y, pos.z, quat.x, quat.y, quat.z, quat.w); + VIVE_TRACE(d, "GET_TRACKED_POSE (%f, %f, %f) (%f, %f, %f, %f) ", pos.x, pos.y, pos.z, quat.x, quat.y, quat.z, + quat.w); } static int -vive_controller_haptic_pulse(struct vive_controller_device *d, - union xrt_output_value *value) +vive_controller_haptic_pulse(struct vive_controller_device *d, union xrt_output_value *value) { float duration_seconds; if (value->vibration.duration == XRT_MIN_HAPTIC_DURATION) { - VIVE_TRACE(d, "Haptic pulse duration: using %f minimum", - MIN_HAPTIC_DURATION); + VIVE_TRACE(d, "Haptic pulse duration: using %f minimum", MIN_HAPTIC_DURATION); duration_seconds = MIN_HAPTIC_DURATION; } else { duration_seconds = time_ns_to_s(value->vibration.duration); } - VIVE_TRACE(d, "Haptic pulse amp %f, %fHz, %fs", - value->vibration.amplitude, value->vibration.frequency, + VIVE_TRACE(d, "Haptic pulse amp %f, %fHz, %fs", value->vibration.amplitude, value->vibration.frequency, duration_seconds); float frequency = value->vibration.frequency; if (frequency == XRT_FREQUENCY_UNSPECIFIED) { - VIVE_TRACE( - d, "Haptic pulse frequency unspecified, setting to %fHz", - DEFAULT_HAPTIC_FREQ); + VIVE_TRACE(d, "Haptic pulse frequency unspecified, setting to %fHz", DEFAULT_HAPTIC_FREQ); frequency = DEFAULT_HAPTIC_FREQ; } @@ -471,8 +423,7 @@ vive_controller_haptic_pulse(struct vive_controller_device *d, */ float high_plus_low = 1000.f * 1000.f / frequency; - uint16_t pulse_low = - (uint16_t)(value->vibration.amplitude * high_plus_low / 2.); + uint16_t pulse_low = (uint16_t)(value->vibration.amplitude * high_plus_low / 2.); /* Vive Controller doesn't vibrate with value == 0. * Not sure if this actually happens, but let's fix it anyway. */ @@ -493,19 +444,15 @@ vive_controller_haptic_pulse(struct vive_controller_device *d, .repeat_count = __cpu_to_le16(repeat_count), }; - return os_hid_set_feature(d->controller_hid, (uint8_t *)&report, - sizeof(report)); + return os_hid_set_feature(d->controller_hid, (uint8_t *)&report, sizeof(report)); } static void -vive_controller_device_set_output(struct xrt_device *xdev, - enum xrt_output_name name, - union xrt_output_value *value) +vive_controller_device_set_output(struct xrt_device *xdev, enum xrt_output_name name, union xrt_output_value *value) { struct vive_controller_device *d = vive_controller_device(xdev); - if (name != XRT_OUTPUT_NAME_VIVE_HAPTIC && - name != XRT_OUTPUT_NAME_INDEX_HAPTIC) { + if (name != XRT_OUTPUT_NAME_VIVE_HAPTIC && name != XRT_OUTPUT_NAME_INDEX_HAPTIC) { VIVE_ERROR(d, "Unknown output\n"); return; } @@ -519,11 +466,9 @@ vive_controller_device_set_output(struct xrt_device *xdev, } static void -controller_handle_battery(struct vive_controller_device *d, - struct vive_controller_battery_sample *sample) +controller_handle_battery(struct vive_controller_device *d, struct vive_controller_battery_sample *sample) { - uint8_t charge_percent = - sample->battery & VIVE_CONTROLLER_BATTERY_CHARGE_MASK; + uint8_t charge_percent = sample->battery & VIVE_CONTROLLER_BATTERY_CHARGE_MASK; bool charging = sample->battery & VIVE_CONTROLLER_BATTERY_CHARGING; VIVE_DEBUG(d, "Charging %d, percent %d\n", charging, charge_percent); d->state.charging = charging; @@ -531,39 +476,33 @@ controller_handle_battery(struct vive_controller_device *d, } static void -controller_handle_buttons(struct vive_controller_device *d, - struct vive_controller_button_sample *sample) +controller_handle_buttons(struct vive_controller_device *d, struct vive_controller_button_sample *sample) { d->state.buttons = sample->buttons; } static void -controller_handle_touch_position(struct vive_controller_device *d, - struct vive_controller_touch_sample *sample) +controller_handle_touch_position(struct vive_controller_device *d, struct vive_controller_touch_sample *sample) { int16_t x = __le16_to_cpu(sample->touch[0]); int16_t y = __le16_to_cpu(sample->touch[1]); d->state.trackpad.x = (float)x / INT16_MAX; d->state.trackpad.y = (float)y / INT16_MAX; if (d->state.trackpad.x != 0 || d->state.trackpad.y != 0) - VIVE_TRACE(d, "Trackpad %f,%f\n", d->state.trackpad.x, - d->state.trackpad.y); + VIVE_TRACE(d, "Trackpad %f,%f\n", d->state.trackpad.x, d->state.trackpad.y); } static void -controller_handle_analog_trigger(struct vive_controller_device *d, - struct vive_controller_trigger_sample *sample) +controller_handle_analog_trigger(struct vive_controller_device *d, struct vive_controller_trigger_sample *sample) { d->state.trigger = (float)sample->trigger / UINT8_MAX; VIVE_TRACE(d, "Trigger %f\n", d->state.trigger); } static inline uint32_t -calc_dt_raw_and_handle_overflow(struct vive_controller_device *d, - uint32_t sample_time) +calc_dt_raw_and_handle_overflow(struct vive_controller_device *d, uint32_t sample_time) { - uint64_t dt_raw = - (uint64_t)sample_time - (uint64_t)d->imu.last_sample_time_raw; + uint64_t dt_raw = (uint64_t)sample_time - (uint64_t)d->imu.last_sample_time_raw; d->imu.last_sample_time_raw = sample_time; // The 32-bit tick counter has rolled over, @@ -585,8 +524,7 @@ cald_dt_ns(uint32_t dt_raw) } static void -vive_controller_handle_imu_sample(struct vive_controller_device *d, - struct watchman_imu_sample *sample) +vive_controller_handle_imu_sample(struct vive_controller_device *d, struct watchman_imu_sample *sample) { /* ouvrt: "Time in 48 MHz ticks, but we are missing the low byte" */ uint32_t time_raw = d->last_ticks | (sample->timestamp_hi << 8); @@ -619,45 +557,31 @@ vive_controller_handle_imu_sample(struct vive_controller_device *d, scale * d->imu.gyro_scale.z * gyro[2] - d->imu.gyro_bias.z, }; - VIVE_TRACE(d, "ACC %f %f %f", acceleration.x, acceleration.y, - acceleration.z); - VIVE_TRACE(d, "GYRO %f %f %f", angular_velocity.x, angular_velocity.y, - angular_velocity.z); + VIVE_TRACE(d, "ACC %f %f %f", acceleration.x, acceleration.y, acceleration.z); + VIVE_TRACE(d, "GYRO %f %f %f", angular_velocity.x, angular_velocity.y, angular_velocity.z); /* */ if (d->variant == CONTROLLER_VIVE_WAND) { - struct xrt_vec3 fixed_acceleration = {.x = -acceleration.x, - .y = -acceleration.z, - .z = -acceleration.y}; + struct xrt_vec3 fixed_acceleration = {.x = -acceleration.x, .y = -acceleration.z, .z = -acceleration.y}; acceleration = fixed_acceleration; struct xrt_vec3 fixed_angular_velocity = { - .x = -angular_velocity.x, - .y = -angular_velocity.z, - .z = -angular_velocity.y}; + .x = -angular_velocity.x, .y = -angular_velocity.z, .z = -angular_velocity.y}; angular_velocity = fixed_angular_velocity; } else if (d->variant == CONTROLLER_INDEX_RIGHT) { - struct xrt_vec3 fixed_acceleration = {.x = acceleration.z, - .y = -acceleration.y, - .z = acceleration.x}; + struct xrt_vec3 fixed_acceleration = {.x = acceleration.z, .y = -acceleration.y, .z = acceleration.x}; acceleration = fixed_acceleration; struct xrt_vec3 fixed_angular_velocity = { - .x = angular_velocity.z, - .y = -angular_velocity.y, - .z = angular_velocity.x}; + .x = angular_velocity.z, .y = -angular_velocity.y, .z = angular_velocity.x}; angular_velocity = fixed_angular_velocity; } else if (d->variant == CONTROLLER_INDEX_LEFT) { - struct xrt_vec3 fixed_acceleration = {.x = -acceleration.z, - .y = acceleration.x, - .z = -acceleration.y}; + struct xrt_vec3 fixed_acceleration = {.x = -acceleration.z, .y = acceleration.x, .z = -acceleration.y}; acceleration = fixed_acceleration; struct xrt_vec3 fixed_angular_velocity = { - .x = -angular_velocity.z, - .y = angular_velocity.x, - .z = -angular_velocity.y}; + .x = -angular_velocity.z, .y = angular_velocity.x, .z = -angular_velocity.y}; angular_velocity = fixed_angular_velocity; } @@ -665,8 +589,7 @@ vive_controller_handle_imu_sample(struct vive_controller_device *d, d->last.acc = acceleration; d->last.gyro = angular_velocity; - m_imu_3dof_update(&d->fusion, d->imu.time_ns, &acceleration, - &angular_velocity); + m_imu_3dof_update(&d->fusion, d->imu.time_ns, &acceleration, &angular_velocity); d->rot_filtered = d->fusion.rot; @@ -675,8 +598,7 @@ vive_controller_handle_imu_sample(struct vive_controller_device *d, } static void -controller_handle_touch_force(struct vive_controller_device *d, - struct watchman_touch_force *sample) +controller_handle_touch_force(struct vive_controller_device *d, struct watchman_touch_force *sample) { d->state.touch = sample->touch; @@ -690,9 +612,7 @@ controller_handle_touch_force(struct vive_controller_device *d, } static void -vive_controller_handle_lighthousev1(struct vive_controller_device *d, - uint8_t *buf, - uint8_t len) +vive_controller_handle_lighthousev1(struct vive_controller_device *d, uint8_t *buf, uint8_t len) { VIVE_TRACE(d, "Got lighthouse message with len %d.\n", len); } @@ -702,8 +622,7 @@ vive_controller_handle_lighthousev1(struct vive_controller_device *d, * Then hands off to vive_controller_handle_lighthousev1(). */ static void -vive_controller_decode_watchmanv1(struct vive_controller_device *d, - struct vive_controller_message *message) +vive_controller_decode_watchmanv1(struct vive_controller_device *d, struct vive_controller_message *message) { uint8_t *buf = message->payload; uint8_t *end = message->payload + message->len - 1; @@ -755,35 +674,29 @@ vive_controller_decode_watchmanv1(struct vive_controller_device *d, VIVE_TRACE(d, "battery %d trigger %d trackpad %d " "buttons %d imu %d", - has_battery, has_trigger, has_trackpad, has_buttons, - has_imu); + has_battery, has_trigger, has_trackpad, has_buttons, has_imu); buf++; if (has_battery) { - controller_handle_battery( - d, (struct vive_controller_battery_sample *)buf); + controller_handle_battery(d, (struct vive_controller_battery_sample *)buf); buf += sizeof(struct vive_controller_battery_sample); } if (has_buttons) { - controller_handle_buttons( - d, (struct vive_controller_button_sample *)buf); + controller_handle_buttons(d, (struct vive_controller_button_sample *)buf); buf += sizeof(struct vive_controller_button_sample); } if (has_trigger) { - controller_handle_analog_trigger( - d, (struct vive_controller_trigger_sample *)buf); + controller_handle_analog_trigger(d, (struct vive_controller_trigger_sample *)buf); buf += sizeof(struct vive_controller_trigger_sample); } if (has_trackpad) { - controller_handle_touch_position( - d, (struct vive_controller_touch_sample *)buf); + controller_handle_touch_position(d, (struct vive_controller_touch_sample *)buf); buf += 4; } if (has_imu) { - vive_controller_handle_imu_sample( - d, (struct watchman_imu_sample *)buf); + vive_controller_handle_imu_sample(d, (struct watchman_imu_sample *)buf); buf += sizeof(struct watchman_imu_sample); } } @@ -802,8 +715,7 @@ vive_controller_decode_watchmanv1(struct vive_controller_device *d, * Then hands off to vive_controller_handle_lighthousev1(). */ static void -vive_controller_decode_watchmanv2(struct vive_controller_device *d, - struct vive_controller_message *message) +vive_controller_decode_watchmanv2(struct vive_controller_device *d, struct vive_controller_message *message) { uint8_t *buf = message->payload; uint8_t *end = message->payload + message->len - 1; @@ -834,8 +746,7 @@ vive_controller_decode_watchmanv2(struct vive_controller_device *d, */ if (*buf == 0xe1 && buf < end) { buf++; - controller_handle_battery( - d, (struct vive_controller_battery_sample *)buf); + controller_handle_battery(d, (struct vive_controller_battery_sample *)buf); buf += sizeof(struct vive_controller_battery_sample); #ifdef WATCHMAN2_PRINT_HID @@ -852,8 +763,7 @@ vive_controller_decode_watchmanv2(struct vive_controller_device *d, */ if (*buf == 0xf0 && buf < end) { buf++; - controller_handle_touch_force( - d, (struct watchman_touch_force *)buf); + controller_handle_touch_force(d, (struct watchman_touch_force *)buf); size_t s = sizeof(struct watchman_touch_force); buf += s; @@ -871,8 +781,7 @@ vive_controller_decode_watchmanv2(struct vive_controller_device *d, // TODO: it's possible we misparse non-im udata as imu data if (*buf == 0xe8 && buf < end) { buf++; - vive_controller_handle_imu_sample( - d, (struct watchman_imu_sample *)buf); + vive_controller_handle_imu_sample(d, (struct watchman_imu_sample *)buf); size_t s = sizeof(struct watchman_imu_sample); buf += s; @@ -911,58 +820,47 @@ vive_controller_decode_watchmanv2(struct vive_controller_device *d, #endif if (has_buttons) { - controller_handle_buttons( - d, (struct vive_controller_button_sample *)buf); + controller_handle_buttons(d, (struct vive_controller_button_sample *)buf); buf += sizeof(struct vive_controller_button_sample); #ifdef WATCHMAN2_PRINT_HID printf(" buttons"); #endif } if (has_trigger) { - controller_handle_analog_trigger( - d, (struct vive_controller_trigger_sample *)buf); + controller_handle_analog_trigger(d, (struct vive_controller_trigger_sample *)buf); buf += sizeof(struct vive_controller_trigger_sample); #ifdef WATCHMAN2_PRINT_HID printf(" trigger"); #endif } if (has_trackpad) { - controller_handle_touch_position( - d, (struct vive_controller_touch_sample *)buf); + controller_handle_touch_position(d, (struct vive_controller_touch_sample *)buf); buf += sizeof(struct vive_controller_touch_sample); #ifdef WATCHMAN2_PRINT_HID - for (unsigned long i = 0; - i < sizeof(struct vive_controller_touch_sample); - i++) + for (unsigned long i = 0; i < sizeof(struct vive_controller_touch_sample); i++) printf(" trackpad"); #endif } if (has_touch_force) { uint8_t type_flag = *buf; if (type_flag == TYPE_FLAG_TOUCH_FORCE) { - controller_handle_touch_force( - d, (struct watchman_touch_force *)buf); + controller_handle_touch_force(d, (struct watchman_touch_force *)buf); size_t s = sizeof(struct watchman_touch_force); buf += s; #ifdef WATCHMAN2_PRINT_HID - for (unsigned long i = 0; - i < sizeof(struct watchman_touch_force); - i++) + for (unsigned long i = 0; i < sizeof(struct watchman_touch_force); i++) printf(" t&force"); #endif } } // if something still follows, usually imu // sometimes it's 5 unknown bytes' - if (buf < end && - end - buf >= (long)sizeof(struct watchman_imu_sample)) { - vive_controller_handle_imu_sample( - d, (struct watchman_imu_sample *)buf); + if (buf < end && end - buf >= (long)sizeof(struct watchman_imu_sample)) { + vive_controller_handle_imu_sample(d, (struct watchman_imu_sample *)buf); size_t s = sizeof(struct watchman_imu_sample); buf += s; #ifdef WATCHMAN2_PRINT_HID - for (unsigned long i = 0; - i < sizeof(struct watchman_imu_sample); i++) + for (unsigned long i = 0; i < sizeof(struct watchman_imu_sample); i++) printf(" imu"); #endif } @@ -974,8 +872,7 @@ vive_controller_decode_watchmanv2(struct vive_controller_device *d, #endif if (buf < end) { - VIVE_TRACE(d, "%ld bytes unparsed data in message\n", - message->len - (buf - message->payload) - 1); + VIVE_TRACE(d, "%ld bytes unparsed data in message\n", message->len - (buf - message->payload) - 1); } if (buf > end) VIVE_ERROR(d, "overshoot: %ld\n", buf - end); @@ -986,21 +883,15 @@ vive_controller_decode_watchmanv2(struct vive_controller_device *d, * Decodes multiplexed Wireless Receiver messages. */ static void -vive_controller_decode_message(struct vive_controller_device *d, - struct vive_controller_message *message) +vive_controller_decode_message(struct vive_controller_device *d, struct vive_controller_message *message) { - d->last_ticks = - (message->timestamp_hi << 24) | (message->timestamp_lo << 16); + d->last_ticks = (message->timestamp_hi << 24) | (message->timestamp_lo << 16); //! @todo: Check if Vive controller on watchman2 is correctly handled //! with watchman2 codepath switch (d->watchman_gen) { - case WATCHMAN_GEN1: - vive_controller_decode_watchmanv1(d, message); - break; - case WATCHMAN_GEN2: - vive_controller_decode_watchmanv2(d, message); - break; + case WATCHMAN_GEN1: vive_controller_decode_watchmanv1(d, message); break; + case WATCHMAN_GEN2: vive_controller_decode_watchmanv2(d, message); break; default: VIVE_ERROR(d, "Can't decode unknown watchman gen"); } } @@ -1025,19 +916,14 @@ vive_controller_device_update(struct vive_controller_device *d) switch (buf[0]) { case VIVE_CONTROLLER_REPORT1_ID: - vive_controller_decode_message( - d, &((struct vive_controller_report1 *)buf)->message); + vive_controller_decode_message(d, &((struct vive_controller_report1 *)buf)->message); break; case VIVE_CONTROLLER_REPORT2_ID: - vive_controller_decode_message( - d, &((struct vive_controller_report2 *)buf)->message[0]); - vive_controller_decode_message( - d, &((struct vive_controller_report2 *)buf)->message[1]); - break; - case VIVE_CONTROLLER_DISCONNECT_REPORT_ID: - VIVE_DEBUG(d, "Controller disconnected."); + vive_controller_decode_message(d, &((struct vive_controller_report2 *)buf)->message[0]); + vive_controller_decode_message(d, &((struct vive_controller_report2 *)buf)->message[1]); break; + case VIVE_CONTROLLER_DISCONNECT_REPORT_ID: VIVE_DEBUG(d, "Controller disconnected."); break; default: VIVE_ERROR(d, "Unknown controller message type: %u", buf[0]); } @@ -1117,27 +1003,23 @@ static struct xrt_binding_profile binding_profiles_vive[1] = { }, }; -#define SET_WAND_INPUT(NAME, NAME2) \ - do { \ - (d->base.inputs[VIVE_CONTROLLER_INDEX_##NAME].name = \ - XRT_INPUT_VIVE_##NAME2); \ +#define SET_WAND_INPUT(NAME, NAME2) \ + do { \ + (d->base.inputs[VIVE_CONTROLLER_INDEX_##NAME].name = XRT_INPUT_VIVE_##NAME2); \ } while (0) -#define SET_INDEX_INPUT(NAME, NAME2) \ - do { \ - (d->base.inputs[VIVE_CONTROLLER_INDEX_##NAME].name = \ - XRT_INPUT_INDEX_##NAME2); \ +#define SET_INDEX_INPUT(NAME, NAME2) \ + do { \ + (d->base.inputs[VIVE_CONTROLLER_INDEX_##NAME].name = XRT_INPUT_INDEX_##NAME2); \ } while (0) struct vive_controller_device * -vive_controller_create(struct os_hid_device *controller_hid, - enum watchman_gen watchman_gen, - int controller_num) +vive_controller_create(struct os_hid_device *controller_hid, enum watchman_gen watchman_gen, int controller_num) { enum u_device_alloc_flags flags = U_DEVICE_ALLOC_TRACKING_NONE; - struct vive_controller_device *d = U_DEVICE_ALLOCATE( - struct vive_controller_device, flags, VIVE_CONTROLLER_MAX_INDEX, 1); + struct vive_controller_device *d = + U_DEVICE_ALLOCATE(struct vive_controller_device, flags, VIVE_CONTROLLER_MAX_INDEX, 1); d->ll = debug_get_log_option_vive_log(); d->watchman_gen = WATCHMAN_GEN_UNKNOWN; @@ -1171,23 +1053,19 @@ vive_controller_create(struct os_hid_device *controller_hid, d->base.get_tracked_pose = vive_controller_device_get_tracked_pose; d->base.set_output = vive_controller_device_set_output; - snprintf(d->base.str, XRT_DEVICE_NAME_LEN, "%s %i", "Vive Controller", - (int)(controller_num)); + snprintf(d->base.str, XRT_DEVICE_NAME_LEN, "%s %i", "Vive Controller", (int)(controller_num)); d->index = controller_num; //! @todo: reading range report fails for powered off controller - if (vive_get_imu_range_report(d->controller_hid, &d->imu.gyro_range, - &d->imu.acc_range) != 0) { + if (vive_get_imu_range_report(d->controller_hid, &d->imu.gyro_range, &d->imu.acc_range) != 0) { VIVE_ERROR(d, "Could not get watchman IMU range packet!"); free(d); return 0; } - VIVE_DEBUG(d, "Vive controller gyroscope range %f", - d->imu.gyro_range); - VIVE_DEBUG(d, "Vive controller accelerometer range %f", - d->imu.acc_range); + VIVE_DEBUG(d, "Vive controller gyroscope range %f", d->imu.gyro_range); + VIVE_DEBUG(d, "Vive controller accelerometer range %f", d->imu.acc_range); // successful config parsing determines d->variant char *config = vive_read_config(d->controller_hid); @@ -1217,16 +1095,13 @@ vive_controller_create(struct os_hid_device *controller_hid, d->base.outputs[0].name = XRT_OUTPUT_NAME_VIVE_HAPTIC; - d->base.update_inputs = - vive_controller_device_update_wand_inputs; + d->base.update_inputs = vive_controller_device_update_wand_inputs; d->base.binding_profiles = binding_profiles_vive; - d->base.num_binding_profiles = - ARRAY_SIZE(binding_profiles_vive); + d->base.num_binding_profiles = ARRAY_SIZE(binding_profiles_vive); d->base.device_type = XRT_DEVICE_TYPE_ANY_HAND_CONTROLLER; - } else if (d->variant == CONTROLLER_INDEX_LEFT || - d->variant == CONTROLLER_INDEX_RIGHT) { + } else if (d->variant == CONTROLLER_INDEX_LEFT || d->variant == CONTROLLER_INDEX_RIGHT) { d->base.name = XRT_DEVICE_INDEX_CONTROLLER; SET_INDEX_INPUT(SYSTEM_CLICK, SYSTEM_CLICK); @@ -1253,33 +1128,23 @@ vive_controller_create(struct os_hid_device *controller_hid, d->base.outputs[0].name = XRT_OUTPUT_NAME_INDEX_HAPTIC; - d->base.update_inputs = - vive_controller_device_update_index_inputs; + d->base.update_inputs = vive_controller_device_update_index_inputs; d->base.get_hand_tracking = vive_controller_get_hand_tracking; - enum xrt_hand hand = d->variant == CONTROLLER_INDEX_LEFT - ? XRT_HAND_LEFT - : XRT_HAND_RIGHT; + enum xrt_hand hand = d->variant == CONTROLLER_INDEX_LEFT ? XRT_HAND_LEFT : XRT_HAND_RIGHT; - u_hand_joints_init_default_set( - &d->hand_tracking, hand, - XRT_HAND_TRACKING_MODEL_FINGERL_CURL, 1.0); + u_hand_joints_init_default_set(&d->hand_tracking, hand, XRT_HAND_TRACKING_MODEL_FINGERL_CURL, 1.0); d->base.binding_profiles = binding_profiles_index; - d->base.num_binding_profiles = - ARRAY_SIZE(binding_profiles_index); + d->base.num_binding_profiles = ARRAY_SIZE(binding_profiles_index); if (d->variant == CONTROLLER_INDEX_LEFT) { - d->base.device_type = - XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER; - d->base.inputs[VIVE_CONTROLLER_HAND_TRACKING].name = - XRT_INPUT_GENERIC_HAND_TRACKING_LEFT; + d->base.device_type = XRT_DEVICE_TYPE_LEFT_HAND_CONTROLLER; + d->base.inputs[VIVE_CONTROLLER_HAND_TRACKING].name = XRT_INPUT_GENERIC_HAND_TRACKING_LEFT; } else if (d->variant == CONTROLLER_INDEX_RIGHT) { - d->base.device_type = - XRT_DEVICE_TYPE_RIGHT_HAND_CONTROLLER; - d->base.inputs[VIVE_CONTROLLER_HAND_TRACKING].name = - XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT; + d->base.device_type = XRT_DEVICE_TYPE_RIGHT_HAND_CONTROLLER; + d->base.inputs[VIVE_CONTROLLER_HAND_TRACKING].name = XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT; } } else if (d->variant == CONTROLLER_TRACKER_GEN1) { d->base.name = XRT_DEVICE_VIVE_TRACKER_GEN1; @@ -1296,8 +1161,7 @@ vive_controller_create(struct os_hid_device *controller_hid, } if (d->controller_hid) { - int ret = os_thread_helper_start(&d->controller_thread, - vive_controller_run_thread, d); + int ret = os_thread_helper_start(&d->controller_thread, vive_controller_run_thread, d); if (ret != 0) { VIVE_ERROR(d, "Failed to start mainboard thread!"); vive_controller_device_destroy((struct xrt_device *)d); @@ -1308,8 +1172,7 @@ vive_controller_create(struct os_hid_device *controller_hid, VIVE_DEBUG(d, "Opened vive controller!\n"); d->base.orientation_tracking_supported = true; d->base.position_tracking_supported = false; - d->base.hand_tracking_supported = d->variant == CONTROLLER_INDEX_LEFT || - d->variant == CONTROLLER_INDEX_RIGHT; + d->base.hand_tracking_supported = d->variant == CONTROLLER_INDEX_LEFT || d->variant == CONTROLLER_INDEX_RIGHT; return d; } diff --git a/src/xrt/drivers/vive/vive_controller.h b/src/xrt/drivers/vive/vive_controller.h index 4b90c9a7a..387998cd8 100644 --- a/src/xrt/drivers/vive/vive_controller.h +++ b/src/xrt/drivers/vive/vive_controller.h @@ -132,9 +132,7 @@ struct vive_controller_device }; struct vive_controller_device * -vive_controller_create(struct os_hid_device *controller_hid, - enum watchman_gen watchman_gen, - int controller_num); +vive_controller_create(struct os_hid_device *controller_hid, enum watchman_gen watchman_gen, int controller_num); #ifdef __cplusplus } diff --git a/src/xrt/drivers/vive/vive_device.c b/src/xrt/drivers/vive/vive_device.c index ebaf3f4b6..6da1c6964 100644 --- a/src/xrt/drivers/vive/vive_device.c +++ b/src/xrt/drivers/vive/vive_device.c @@ -121,10 +121,8 @@ vive_device_get_tracked_pose(struct xrt_device *xdev, //! @todo assuming that orientation is actually currently tracked. out_relation->relation_flags = (enum xrt_space_relation_flags)( - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT | - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + XRT_SPACE_RELATION_POSITION_VALID_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT | + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); os_thread_helper_unlock(&d->sensors_thread); } @@ -168,28 +166,23 @@ vive_mainboard_get_device_info(struct vive_device *d) uint16_t type; int ret; - ret = os_hid_get_feature(d->mainboard_dev, report.id, - (uint8_t *)&report, sizeof(report)); + ret = os_hid_get_feature(d->mainboard_dev, report.id, (uint8_t *)&report, sizeof(report)); if (ret < 0) return ret; type = __le16_to_cpu(report.type); - if (type != VIVE_HEADSET_MAINBOARD_DEVICE_INFO_REPORT_TYPE || - report.len != 60) { + if (type != VIVE_HEADSET_MAINBOARD_DEVICE_INFO_REPORT_TYPE || report.len != 60) { VIVE_WARN(d, "Unexpected device info!"); return -1; } edid_vid = __be16_to_cpu(report.edid_vid); - d->firmware.display_firmware_version = - __le32_to_cpu(report.display_firmware_version); + d->firmware.display_firmware_version = __le32_to_cpu(report.display_firmware_version); - VIVE_INFO(d, "EDID Manufacturer ID: %c%c%c, Product code: 0x%04x", - '@' + (edid_vid >> 10), '@' + ((edid_vid >> 5) & 0x1f), - '@' + (edid_vid & 0x1f), __le16_to_cpu(report.edid_pid)); - VIVE_INFO(d, "Display firmware version: %u", - d->firmware.display_firmware_version); + VIVE_INFO(d, "EDID Manufacturer ID: %c%c%c, Product code: 0x%04x", '@' + (edid_vid >> 10), + '@' + ((edid_vid >> 5) & 0x1f), '@' + (edid_vid & 0x1f), __le16_to_cpu(report.edid_pid)); + VIVE_INFO(d, "Display firmware version: %u", d->firmware.display_firmware_version); return 0; } @@ -199,9 +192,7 @@ static bool vive_mainboard_power_on(struct vive_device *d) { int ret; - ret = os_hid_set_feature(d->mainboard_dev, - (const uint8_t *)&power_on_report, - sizeof(power_on_report)); + ret = os_hid_set_feature(d->mainboard_dev, (const uint8_t *)&power_on_report, sizeof(power_on_report)); VIVE_DEBUG(d, "Power on: %d", ret); return true; } @@ -210,24 +201,21 @@ static bool vive_mainboard_power_off(struct vive_device *d) { int ret; - ret = os_hid_set_feature(d->mainboard_dev, - (const uint8_t *)&power_off_report, - sizeof(power_off_report)); + ret = os_hid_set_feature(d->mainboard_dev, (const uint8_t *)&power_off_report, sizeof(power_off_report)); VIVE_DEBUG(d, "Power off: %d", ret); return true; } static void -vive_mainboard_decode_message(struct vive_device *d, - struct vive_mainboard_status_report *report) +vive_mainboard_decode_message(struct vive_device *d, struct vive_mainboard_status_report *report) { uint16_t ipd; uint16_t lens_separation; uint16_t proximity; - if (__le16_to_cpu(report->unknown) != 0x2cd0 || report->len != 60 || - report->reserved1 || report->reserved2[0]) { + if (__le16_to_cpu(report->unknown) != 0x2cd0 || report->len != 60 || report->reserved1 || + report->reserved2[0]) { VIVE_WARN(d, "Unexpected message content."); } @@ -238,8 +226,7 @@ vive_mainboard_decode_message(struct vive_device *d, if (d->board.ipd != ipd) { d->board.ipd = ipd; d->board.lens_separation = lens_separation; - VIVE_TRACE(d, "IPD %4.1f mm. Lens separation %4.1f mm.", - 1e-2 * ipd, 1e-2 * lens_separation); + VIVE_TRACE(d, "IPD %4.1f mm. Lens separation %4.1f mm.", 1e-2 * ipd, 1e-2 * lens_separation); } if (d->board.proximity != proximity) { @@ -268,8 +255,7 @@ oldest_sequence_index(uint8_t a, uint8_t b, uint8_t c) static inline uint32_t calc_dt_raw_and_handle_overflow(struct vive_device *d, uint32_t sample_time) { - uint64_t dt_raw = - (uint64_t)sample_time - (uint64_t)d->imu.last_sample_time_raw; + uint64_t dt_raw = (uint64_t)sample_time - (uint64_t)d->imu.last_sample_time_raw; d->imu.last_sample_time_raw = sample_time; // The 32-bit tick counter has rolled over, @@ -315,8 +301,7 @@ update_imu(struct vive_device *d, const void *buffer) seq = sample->seq; /* Skip already seen samples */ - if (seq == last_seq || seq == (uint8_t)(last_seq - 1) || - seq == (uint8_t)(last_seq - 2)) { + if (seq == last_seq || seq == (uint8_t)(last_seq - 1) || seq == (uint8_t)(last_seq - 2)) { continue; } @@ -351,11 +336,9 @@ update_imu(struct vive_device *d, const void *buffer) scale * d->imu.gyro_scale.z * gyro[2] - d->imu.gyro_bias.z, }; - VIVE_TRACE(d, "ACC %f %f %f", acceleration.x, acceleration.y, - acceleration.z); + VIVE_TRACE(d, "ACC %f %f %f", acceleration.x, acceleration.y, acceleration.z); - VIVE_TRACE(d, "GYRO %f %f %f", angular_velocity.x, - angular_velocity.y, angular_velocity.z); + VIVE_TRACE(d, "GYRO %f %f %f", angular_velocity.x, angular_velocity.y, angular_velocity.z); switch (d->variant) { case VIVE_VARIANT_VIVE: @@ -400,8 +383,7 @@ update_imu(struct vive_device *d, const void *buffer) d->last.gyro = angular_velocity; d->imu.sequence = seq; - m_imu_3dof_update(&d->fusion, d->imu.time_ns, &acceleration, - &angular_velocity); + m_imu_3dof_update(&d->fusion, d->imu.time_ns, &acceleration, &angular_velocity); d->rot_filtered = d->fusion.rot; } @@ -432,16 +414,12 @@ vive_mainboard_read_one_msg(struct vive_device *d) switch (buffer[0]) { case VIVE_MAINBOARD_STATUS_REPORT_ID: if (ret != sizeof(struct vive_mainboard_status_report)) { - VIVE_ERROR(d, - "Mainboard status report has invalid size."); + VIVE_ERROR(d, "Mainboard status report has invalid size."); return false; } - vive_mainboard_decode_message( - d, (struct vive_mainboard_status_report *)buffer); - break; - default: - VIVE_ERROR(d, "Unknown mainboard message type %d", buffer[0]); + vive_mainboard_decode_message(d, (struct vive_mainboard_status_report *)buffer); break; + default: VIVE_ERROR(d, "Unknown mainboard message type %d", buffer[0]); break; } return true; @@ -496,14 +474,10 @@ vive_sensors_enable_watchman(struct vive_device *d, bool enable_sensors) } static void -_print_v1_pulse(struct vive_device *d, - uint8_t sensor_id, - uint32_t timestamp, - uint16_t duration) +_print_v1_pulse(struct vive_device *d, uint8_t sensor_id, uint32_t timestamp, uint16_t duration) { - VIVE_TRACE(d, "[sensor %02d] timestamp %8u ticks (%3.5fs) duration: %d", - sensor_id, timestamp, timestamp / (float)VIVE_CLOCK_FREQ, - duration); + VIVE_TRACE(d, "[sensor %02d] timestamp %8u ticks (%3.5fs) duration: %d", sensor_id, timestamp, + timestamp / (float)VIVE_CLOCK_FREQ, duration); } static void @@ -532,8 +506,7 @@ _decode_pulse_report(struct vive_device *d, const void *buffer) } if (sensor_id > 31) { - VIVE_ERROR(d, "Unexpected sensor id: %04x\n", - sensor_id); + VIVE_ERROR(d, "Unexpected sensor id: %04x\n", sensor_id); return; } @@ -541,8 +514,7 @@ _decode_pulse_report(struct vive_device *d, const void *buffer) _print_v1_pulse(d, sensor_id, timestamp, duration); - lighthouse_watchman_handle_pulse(&d->watchman, sensor_id, - duration, timestamp); + lighthouse_watchman_handle_pulse(&d->watchman, sensor_id, duration, timestamp); } } @@ -551,26 +523,19 @@ _sensors_get_report_string(uint32_t report_id) { switch (report_id) { case VIVE_IMU_REPORT_ID: return "VIVE_IMU_REPORT_ID"; - case VIVE_HEADSET_LIGHTHOUSE_PULSE_REPORT_ID: - return "VIVE_HEADSET_LIGHTHOUSE_PULSE_REPORT_ID"; - case VIVE_CONTROLLER_LIGHTHOUSE_PULSE_REPORT_ID: - return "VIVE_CONTROLLER_LIGHTHOUSE_PULSE_REPORT_ID"; - case VIVE_HEADSET_LIGHTHOUSE_V2_PULSE_REPORT_ID: - return "VIVE_HEADSET_LIGHTHOUSE_V2_PULSE_REPORT_ID"; + case VIVE_HEADSET_LIGHTHOUSE_PULSE_REPORT_ID: return "VIVE_HEADSET_LIGHTHOUSE_PULSE_REPORT_ID"; + case VIVE_CONTROLLER_LIGHTHOUSE_PULSE_REPORT_ID: return "VIVE_CONTROLLER_LIGHTHOUSE_PULSE_REPORT_ID"; + case VIVE_HEADSET_LIGHTHOUSE_V2_PULSE_REPORT_ID: return "VIVE_HEADSET_LIGHTHOUSE_V2_PULSE_REPORT_ID"; default: return "Unknown"; } } static bool -_is_report_size_valid(struct vive_device *d, - int size, - int report_size, - int report_id) +_is_report_size_valid(struct vive_device *d, int size, int report_size, int report_id) { if (size != report_size) { - VIVE_WARN(d, "Wrong size %d for report %s (%02x). Expected %d.", - size, _sensors_get_report_string(report_id), - report_id, report_size); + VIVE_WARN(d, "Wrong size %d for report %s (%02x). Expected %d.", size, + _sensors_get_report_string(report_id), report_id, report_size); return false; } return true; @@ -581,8 +546,7 @@ vive_sensors_read_one_msg(struct vive_device *d, struct os_hid_device *dev, uint32_t report_id, int report_size, - void (*process_cb)(struct vive_device *d, - const void *buffer)) + void (*process_cb)(struct vive_device *d, const void *buffer)) { uint8_t buffer[64]; @@ -593,8 +557,7 @@ vive_sensors_read_one_msg(struct vive_device *d, return true; } if (ret < 0) { - VIVE_ERROR(d, "Failed to read device %p: %i.", (void *)dev, - ret); + VIVE_ERROR(d, "Failed to read device %p: %i.", (void *)dev, ret); return false; } @@ -603,22 +566,17 @@ vive_sensors_read_one_msg(struct vive_device *d, return false; process_cb(d, buffer); } else { - VIVE_ERROR(d, "Unexpected sensor report type %s (0x%x).", - _sensors_get_report_string(buffer[0]), buffer[0]); - VIVE_ERROR(d, "Expected %s (0x%x).", - _sensors_get_report_string(report_id), report_id); + VIVE_ERROR(d, "Unexpected sensor report type %s (0x%x).", _sensors_get_report_string(buffer[0]), + buffer[0]); + VIVE_ERROR(d, "Expected %s (0x%x).", _sensors_get_report_string(report_id), report_id); } return true; } static void -_print_v2_pulse(struct vive_device *d, - uint8_t sensor_id, - uint8_t flag, - uint32_t timestamp, - uint32_t data, - uint32_t mask) +_print_v2_pulse( + struct vive_device *d, uint8_t sensor_id, uint8_t flag, uint32_t timestamp, uint32_t data, uint32_t mask) { char data_str[32]; @@ -635,8 +593,7 @@ _print_v2_pulse(struct vive_device *d, VIVE_TRACE(d, "[sensor %02d] flag: %03u " "timestamp %8u ticks (%3.5fs) data: %s", - sensor_id, flag, timestamp, - timestamp / (float)VIVE_CLOCK_FREQ, data_str); + sensor_id, flag, timestamp, timestamp / (float)VIVE_CLOCK_FREQ, data_str); } static bool @@ -645,8 +602,7 @@ _print_pulse_report_v2(struct vive_device *d, const void *buffer) const struct vive_headset_lighthouse_v2_pulse_report *report = buffer; for (uint32_t i = 0; i < 4; i++) { - const struct vive_headset_lighthouse_v2_pulse *p = - &report->pulse[i]; + const struct vive_headset_lighthouse_v2_pulse *p = &report->pulse[i]; if (p->sensor_id == 0xff) continue; @@ -664,8 +620,7 @@ _print_pulse_report_v2(struct vive_device *d, const void *buffer) } uint32_t timestamp = __le32_to_cpu(p->timestamp); - _print_v2_pulse(d, sensor_id, flag, timestamp, p->data, - p->mask); + _print_v2_pulse(d, sensor_id, flag, timestamp, p->data, p->mask); } return true; @@ -715,9 +670,8 @@ vive_sensors_read_lighthouse_msg(struct vive_device *d) return false; break; default: - VIVE_ERROR( - d, "Unexpected sensor report type %s (0x%x). %d bytes.", - _sensors_get_report_string(buffer[0]), buffer[0], ret); + VIVE_ERROR(d, "Unexpected sensor report type %s (0x%x). %d bytes.", + _sensors_get_report_string(buffer[0]), buffer[0], ret); } return true; @@ -752,9 +706,7 @@ vive_sensors_run_thread(void *ptr) while (os_thread_helper_is_running_locked(&d->sensors_thread)) { os_thread_helper_unlock(&d->sensors_thread); - if (!vive_sensors_read_one_msg(d, d->sensors_dev, - VIVE_IMU_REPORT_ID, 52, - update_imu)) { + if (!vive_sensors_read_one_msg(d, d->sensors_dev, VIVE_IMU_REPORT_ID, 52, update_imu)) { return NULL; } @@ -796,11 +748,7 @@ vive_init_defaults(struct vive_device *d) static bool -compute_distortion(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result) +compute_distortion(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result) { struct vive_device *d = vive_device(xdev); return u_compute_distortion_vive(&d->distortion[view], u, v, result); @@ -812,10 +760,9 @@ vive_device_create(struct os_hid_device *mainboard_dev, struct os_hid_device *watchman_dev, enum VIVE_VARIANT variant) { - enum u_device_alloc_flags flags = (enum u_device_alloc_flags)( - U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); - struct vive_device *d = - U_DEVICE_ALLOCATE(struct vive_device, flags, 1, 0); + enum u_device_alloc_flags flags = + (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD | U_DEVICE_ALLOC_TRACKING_NONE); + struct vive_device *d = U_DEVICE_ALLOCATE(struct vive_device, flags, 1, 0); d->base.hmd->blend_mode = XRT_BLEND_MODE_OPAQUE; d->base.update_inputs = vive_device_update_inputs; @@ -837,28 +784,18 @@ vive_device_create(struct os_hid_device *mainboard_dev, vive_init_defaults(d); switch (variant) { - case VIVE_VARIANT_VIVE: - snprintf(d->base.str, XRT_DEVICE_NAME_LEN, "HTC Vive"); - break; - case VIVE_VARIANT_PRO: - snprintf(d->base.str, XRT_DEVICE_NAME_LEN, "HTC Vive Pro"); - break; - case VIVE_VARIANT_INDEX: - snprintf(d->base.str, XRT_DEVICE_NAME_LEN, "Valve Index"); - break; - default: - snprintf(d->base.str, XRT_DEVICE_NAME_LEN, - "Unknown Vive device"); + case VIVE_VARIANT_VIVE: snprintf(d->base.str, XRT_DEVICE_NAME_LEN, "HTC Vive"); break; + case VIVE_VARIANT_PRO: snprintf(d->base.str, XRT_DEVICE_NAME_LEN, "HTC Vive Pro"); break; + case VIVE_VARIANT_INDEX: snprintf(d->base.str, XRT_DEVICE_NAME_LEN, "Valve Index"); break; + default: snprintf(d->base.str, XRT_DEVICE_NAME_LEN, "Unknown Vive device"); } if (d->mainboard_dev) { vive_mainboard_power_on(d); vive_mainboard_get_device_info(d); } - vive_read_firmware(d->sensors_dev, &d->firmware.firmware_version, - &d->firmware.hardware_revision, - &d->firmware.hardware_version_micro, - &d->firmware.hardware_version_minor, + vive_read_firmware(d->sensors_dev, &d->firmware.firmware_version, &d->firmware.hardware_revision, + &d->firmware.hardware_version_micro, &d->firmware.hardware_version_minor, &d->firmware.hardware_version_major); /* @@ -868,14 +805,11 @@ vive_device_create(struct os_hid_device *mainboard_dev, */ VIVE_INFO(d, "Firmware version %u", d->firmware.firmware_version); - VIVE_INFO(d, "Hardware revision: %d rev %d.%d.%d", - d->firmware.hardware_revision, - d->firmware.hardware_version_major, - d->firmware.hardware_version_minor, + VIVE_INFO(d, "Hardware revision: %d rev %d.%d.%d", d->firmware.hardware_revision, + d->firmware.hardware_version_major, d->firmware.hardware_version_minor, d->firmware.hardware_version_micro); - vive_get_imu_range_report(d->sensors_dev, &d->imu.gyro_range, - &d->imu.acc_range); + vive_get_imu_range_report(d->sensors_dev, &d->imu.gyro_range, &d->imu.acc_range); VIVE_INFO(d, "Vive gyroscope range %f", d->imu.gyro_range); VIVE_INFO(d, "Vive accelerometer range %f", d->imu.acc_range); @@ -904,15 +838,12 @@ vive_device_create(struct os_hid_device *mainboard_dev, // eye relief knob adjusts this around [0.0255(near)-0.275(far)] eye_to_screen_distance = 0.0255; - d->base.hmd->screens[0].nominal_frame_interval_ns = - (uint64_t)time_s_to_ns(1.0f / 144.0f); + d->base.hmd->screens[0].nominal_frame_interval_ns = (uint64_t)time_s_to_ns(1.0f / 144.0f); } else { - d->base.hmd->screens[0].nominal_frame_interval_ns = - (uint64_t)time_s_to_ns(1.0f / 90.0f); + d->base.hmd->screens[0].nominal_frame_interval_ns = (uint64_t)time_s_to_ns(1.0f / 90.0f); } - double fov = 2 * atan2(w_meters - lens_horizontal_separation / 2.0, - eye_to_screen_distance); + double fov = 2 * atan2(w_meters - lens_horizontal_separation / 2.0, eye_to_screen_distance); struct xrt_vec2 lens_center[2]; @@ -938,12 +869,9 @@ vive_device_create(struct os_hid_device *mainboard_dev, d->base.hmd->views[1].viewport.x_pixels = w_pixels; for (uint8_t eye = 0; eye < 2; eye++) { - if (!math_compute_fovs(w_meters, (double)lens_center[eye].x, - fov, h_meters, - (double)lens_center[eye].y, 0, - &d->base.hmd->views[eye].fov)) { - VIVE_ERROR( - d, "Failed to compute the partial fields of view."); + if (!math_compute_fovs(w_meters, (double)lens_center[eye].x, fov, h_meters, (double)lens_center[eye].y, + 0, &d->base.hmd->views[eye].fov)) { + VIVE_ERROR(d, "Failed to compute the partial fields of view."); free(d); return NULL; } @@ -970,14 +898,12 @@ vive_device_create(struct os_hid_device *mainboard_dev, VIVE_ERROR(d, "Could not enable watchman receiver."); } else { lighthouse_watchman_init(&d->watchman, "headset"); - VIVE_DEBUG(d, - "Successfully enabled watchman receiver."); + VIVE_DEBUG(d, "Successfully enabled watchman receiver."); } } if (d->mainboard_dev) { - ret = os_thread_helper_start(&d->mainboard_thread, - vive_mainboard_run_thread, d); + ret = os_thread_helper_start(&d->mainboard_thread, vive_mainboard_run_thread, d); if (ret != 0) { VIVE_ERROR(d, "Failed to start mainboard thread!"); vive_device_destroy((struct xrt_device *)d); @@ -989,16 +915,14 @@ vive_device_create(struct os_hid_device *mainboard_dev, d->base.position_tracking_supported = false; d->base.device_type = XRT_DEVICE_TYPE_HMD; - ret = os_thread_helper_start(&d->sensors_thread, - vive_sensors_run_thread, d); + ret = os_thread_helper_start(&d->sensors_thread, vive_sensors_run_thread, d); if (ret != 0) { VIVE_ERROR(d, "Failed to start sensors thread!"); vive_device_destroy((struct xrt_device *)d); return NULL; } - ret = os_thread_helper_start(&d->watchman_thread, - vive_watchman_run_thread, d); + ret = os_thread_helper_start(&d->watchman_thread, vive_watchman_run_thread, d); if (ret != 0) { VIVE_ERROR(d, "Failed to start watchman thread!"); vive_device_destroy((struct xrt_device *)d); diff --git a/src/xrt/drivers/vive/vive_lighthouse.c b/src/xrt/drivers/vive/vive_lighthouse.c index 0a00fdd19..5cb61c06c 100644 --- a/src/xrt/drivers/vive/vive_lighthouse.c +++ b/src/xrt/drivers/vive/vive_lighthouse.c @@ -143,9 +143,7 @@ _handle_ootx_frame(struct lighthouse_base *base) int i; if (len != 33) { - LH_WARN( - "Lighthouse Base %X: unexpected OOTX payload length: %d", - base->serial, len); + LH_WARN("Lighthouse Base %X: unexpected OOTX payload length: %d", base->serial, len); return; } @@ -153,17 +151,14 @@ _handle_ootx_frame(struct lighthouse_base *base) crc = crc32(crc, base->ootx + 2, 33); if (ootx_crc != crc) { - LH_ERROR("Lighthouse Base %X: CRC error: %08x != %08x", - base->serial, crc, ootx_crc); + LH_ERROR("Lighthouse Base %X: CRC error: %08x != %08x", base->serial, crc, ootx_crc); return; } version = __le16_to_cpu(report->version); ootx_version = version & 0x3f; if (ootx_version != 6) { - LH_ERROR( - "Lighthouse Base %X: unexpected OOTX frame version: %d", - base->serial, ootx_version); + LH_ERROR("Lighthouse Base %X: unexpected OOTX frame version: %d", base->serial, ootx_version); return; } @@ -191,8 +186,7 @@ _handle_ootx_frame(struct lighthouse_base *base) LH_INFO( "Lighthouse Base %X: firmware version: %d, model id: %d, " "channel: %c", - base->serial, base->firmware_version, base->model_id, - base->channel); + base->serial, base->firmware_version, base->model_id, base->channel); for (i = 0; i < 2; i++) { struct lighthouse_rotor_calibration *rotor; @@ -202,8 +196,7 @@ _handle_ootx_frame(struct lighthouse_base *base) LH_INFO( "Lighthouse Base %X: rotor %d: [ %12.9f %12.9f " "%12.9f %12.9f %12.9f ]", - base->serial, i, rotor->tilt, rotor->phase, - rotor->curve, rotor->gibphase, rotor->gibmag); + base->serial, i, rotor->tilt, rotor->phase, rotor->curve, rotor->gibphase, rotor->gibmag); } } @@ -211,17 +204,15 @@ _handle_ootx_frame(struct lighthouse_base *base) gravity.y = report->gravity[1]; gravity.z = report->gravity[2]; math_vec3_normalize(&gravity); - if (gravity.x != base->gravity.x || gravity.y != base->gravity.y || - gravity.z != base->gravity.z) { + if (gravity.x != base->gravity.x || gravity.y != base->gravity.y || gravity.z != base->gravity.z) { base->gravity = gravity; - LH_INFO("Lighthouse Base %X: gravity: [ %9.6f %9.6f %9.6f ]", - base->serial, gravity.x, gravity.y, gravity.z); + LH_INFO("Lighthouse Base %X: gravity: [ %9.6f %9.6f %9.6f ]", base->serial, gravity.x, gravity.y, + gravity.z); } if (base->reset_count != report->reset_count) { base->reset_count = report->reset_count; - LH_INFO("Lighthouse Base %X: reset count: %d", base->serial, - base->reset_count); + LH_INFO("Lighthouse Base %X: reset count: %d", base->serial, base->reset_count); } } @@ -235,27 +226,23 @@ lighthouse_base_reset(struct lighthouse_base *base) } static void -_handle_ootx_data_word(struct lighthouse_watchman *watchman, - struct lighthouse_base *base) +_handle_ootx_data_word(struct lighthouse_watchman *watchman, struct lighthouse_base *base) { uint16_t len = (__le16)*base->ootx; /* After 4 OOTX words we have received the base station serial number */ if (base->data_word == 4) { - struct lighthouse_ootx_report *report = - (void *)(base->ootx + 2); + struct lighthouse_ootx_report *report = (void *)(base->ootx + 2); uint16_t ootx_version = __le16_to_cpu(report->version) & 0x3f; uint32_t serial = __le32_to_cpu(report->serial); if (len != 33) { - LH_WARN("%s: unexpected OOTX frame length %d", - watchman->name, len); + LH_WARN("%s: unexpected OOTX frame length %d", watchman->name, len); return; } if (ootx_version == 6 && serial != base->serial) { - LH_DEBUG("%s: spotted Lighthouse Base %X", - watchman->name, serial); + LH_DEBUG("%s: spotted Lighthouse Base %X", watchman->name, serial); } } if (len == 33 && base->data_word == 20) { /* (len + 3)/4 * 2 + 2 */ @@ -264,9 +251,7 @@ _handle_ootx_data_word(struct lighthouse_watchman *watchman, } static void -lighthouse_base_handle_ootx_data_bit(struct lighthouse_watchman *watchman, - struct lighthouse_base *base, - bool data) +lighthouse_base_handle_ootx_data_bit(struct lighthouse_watchman *watchman, struct lighthouse_base *base, bool data) { if (base->data_word >= (int)sizeof(base->ootx) / 2) { base->data_word = -1; @@ -278,8 +263,7 @@ lighthouse_base_handle_ootx_data_bit(struct lighthouse_watchman *watchman, base->data_word++; _handle_ootx_data_word(watchman, base); } else { - LH_WARN("%s: Missed a sync bit, restarting", - watchman->name); + LH_WARN("%s: Missed a sync bit, restarting", watchman->name); /* Missing sync bit, restart */ base->data_word = -1; } @@ -289,8 +273,7 @@ lighthouse_base_handle_ootx_data_bit(struct lighthouse_watchman *watchman, * transmitted MSB-first. */ if (data) { - int idx = - 2 * base->data_word + (base->data_bit >> 3); + int idx = 2 * base->data_word + (base->data_bit >> 3); base->ootx[idx] |= 0x80 >> (base->data_bit % 8); } @@ -352,8 +335,7 @@ lighthouse_base_handle_frame(struct lighthouse_watchman *watchman, #define ROTOR_BIT 1 static void -_handle_sync_pulse(struct lighthouse_watchman *watchman, - struct lighthouse_pulse *sync) +_handle_sync_pulse(struct lighthouse_watchman *watchman, struct lighthouse_pulse *sync) { struct lighthouse_base *base; unsigned char channel; @@ -364,8 +346,7 @@ _handle_sync_pulse(struct lighthouse_watchman *watchman, return; if (sync->duration < 2750 || sync->duration > 6750) { - LH_WARN("%s: Unknown pulse length: %d", watchman->name, - sync->duration); + LH_WARN("%s: Unknown pulse length: %d", watchman->name, sync->duration); return; } code = (sync->duration - 2750) / 500; @@ -395,8 +376,7 @@ _handle_sync_pulse(struct lighthouse_watchman *watchman, LH_WARN( "%s: Irregular sync pulse: %08x -> %08x " "(%+d)", - watchman->name, watchman->last_timestamp, - sync->timestamp, dt); + watchman->name, watchman->last_timestamp, sync->timestamp, dt); lighthouse_base_reset(&watchman->base[0]); lighthouse_base_reset(&watchman->base[1]); } @@ -425,10 +405,7 @@ _handle_sync_pulse(struct lighthouse_watchman *watchman, } static void -_handle_sweep_pulse(struct lighthouse_watchman *watchman, - uint8_t id, - uint32_t timestamp, - uint16_t duration) +_handle_sweep_pulse(struct lighthouse_watchman *watchman, uint8_t id, uint32_t timestamp, uint16_t duration) { struct lighthouse_base *base = watchman->active_base; struct lighthouse_frame *frame; @@ -458,9 +435,7 @@ _handle_sweep_pulse(struct lighthouse_watchman *watchman, } if (frame->sweep_ids & (1 << id)) { - LH_WARN( - "%s: sensor %u hit twice per frame, assuming reflection", - watchman->name, id); + LH_WARN("%s: sensor %u hit twice per frame, assuming reflection", watchman->name, id); return; } @@ -470,15 +445,11 @@ _handle_sweep_pulse(struct lighthouse_watchman *watchman, } static void -accumulate_sync_pulse(struct lighthouse_watchman *watchman, - uint8_t id, - uint32_t timestamp, - uint16_t duration) +accumulate_sync_pulse(struct lighthouse_watchman *watchman, uint8_t id, uint32_t timestamp, uint16_t duration) { int32_t dt = timestamp - watchman->last_sync.timestamp; - if (dt > watchman->last_sync.duration || - watchman->last_sync.duration == 0) { + if (dt > watchman->last_sync.duration || watchman->last_sync.duration == 0) { watchman->seen_by = 1 << id; watchman->last_sync.timestamp = timestamp; watchman->last_sync.duration = duration; @@ -486,8 +457,7 @@ accumulate_sync_pulse(struct lighthouse_watchman *watchman, } else { watchman->seen_by |= 1 << id; if (timestamp < watchman->last_sync.timestamp) { - watchman->last_sync.duration += - watchman->last_sync.timestamp - timestamp; + watchman->last_sync.duration += watchman->last_sync.timestamp - timestamp; watchman->last_sync.timestamp = timestamp; } if (duration > watchman->last_sync.duration) @@ -512,10 +482,8 @@ lighthouse_watchman_handle_pulse(struct lighthouse_watchman *watchman, watchman->seen_by = 0; } - if (pulse_in_this_sync_window(dt, duration) || - pulse_in_next_sync_window(dt, duration)) { - accumulate_sync_pulse(watchman, id, timestamp, - duration); + if (pulse_in_this_sync_window(dt, duration) || pulse_in_next_sync_window(dt, duration)) { + accumulate_sync_pulse(watchman, id, timestamp, duration); } else if (pulse_in_sweep_window(dt, duration)) { _handle_sweep_pulse(watchman, id, timestamp, duration); } else { @@ -526,11 +494,9 @@ lighthouse_watchman_handle_pulse(struct lighthouse_watchman *watchman, */ if (dt > 407500) { watchman->sync_lock = false; - LH_WARN("%s: late pulse, lost sync", - watchman->name); + LH_WARN("%s: late pulse, lost sync", watchman->name); } else { - LH_WARN("%s: spurious pulse: %08x (%02x %d %u)", - watchman->name, timestamp, id, dt, + LH_WARN("%s: spurious pulse: %08x (%02x %d %u)", watchman->name, timestamp, id, dt, duration); } watchman->seen_by = 0; @@ -556,8 +522,7 @@ lighthouse_watchman_handle_pulse(struct lighthouse_watchman *watchman, watchman->sync_lock = true; } - accumulate_sync_pulse(watchman, id, timestamp, - duration); + accumulate_sync_pulse(watchman, id, timestamp, duration); } else { /* Assume this is a sweep, ignore it until we lock */ } diff --git a/src/xrt/drivers/vive/vive_lighthouse.h b/src/xrt/drivers/vive/vive_lighthouse.h index 224e13e8d..e3fae7f63 100644 --- a/src/xrt/drivers/vive/vive_lighthouse.h +++ b/src/xrt/drivers/vive/vive_lighthouse.h @@ -106,5 +106,4 @@ lighthouse_watchman_handle_pulse(struct lighthouse_watchman *watchman, uint16_t duration, uint32_t timestamp); void -lighthouse_watchman_init(struct lighthouse_watchman *watchman, - const char *name); +lighthouse_watchman_init(struct lighthouse_watchman *watchman, const char *name); diff --git a/src/xrt/drivers/vive/vive_prober.c b/src/xrt/drivers/vive/vive_prober.c index dd066f84c..a01919b05 100644 --- a/src/xrt/drivers/vive/vive_prober.c +++ b/src/xrt/drivers/vive/vive_prober.c @@ -25,9 +25,7 @@ static const char VIVE_MANUFACTURER_STRING[] = "HTC"; DEBUG_GET_ONCE_LOG_OPTION(vive_log, "VIVE_LOG", U_LOGGING_WARN) static int -log_vive_string(struct xrt_prober *xp, - struct xrt_prober_device *dev, - enum xrt_prober_string type) +log_vive_string(struct xrt_prober *xp, struct xrt_prober_device *dev, enum xrt_prober_string type) { unsigned char s[256] = {0}; int len = xrt_prober_get_string_descriptor(xp, dev, type, s, sizeof(s)); @@ -37,9 +35,7 @@ log_vive_string(struct xrt_prober *xp, } static void -log_vive_device(enum u_logging_level log_level, - struct xrt_prober *xp, - struct xrt_prober_device *dev) +log_vive_device(enum u_logging_level log_level, struct xrt_prober *xp, struct xrt_prober_device *dev) { if (log_level > U_LOGGING_INFO) return; @@ -64,10 +60,8 @@ init_vive1(struct xrt_prober *xp, { log_vive_device(ll, xp, dev); - if (!xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_MANUFACTURER, - VIVE_MANUFACTURER_STRING) || - !xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_PRODUCT, - VIVE_PRODUCT_STRING)) { + if (!xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_MANUFACTURER, VIVE_MANUFACTURER_STRING) || + !xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_PRODUCT, VIVE_PRODUCT_STRING)) { return -1; } @@ -77,14 +71,12 @@ init_vive1(struct xrt_prober *xp, for (uint32_t i = 0; i < num_devices; i++) { struct xrt_prober_device *d = devices[i]; - if (d->vendor_id != VALVE_VID && - d->product_id != VIVE_LIGHTHOUSE_FPGA_RX) + if (d->vendor_id != VALVE_VID && d->product_id != VIVE_LIGHTHOUSE_FPGA_RX) continue; log_vive_device(ll, xp, d); - int result = - xrt_prober_open_hid_interface(xp, d, 0, &sensors_dev); + int result = xrt_prober_open_hid_interface(xp, d, 0, &sensors_dev); if (result != 0) { U_LOG_E("Could not open Vive sensors device."); return -1; @@ -117,8 +109,7 @@ init_vive1(struct xrt_prober *xp, free(sensors_dev); return -1; } - struct vive_device *d = vive_device_create( - mainboard_dev, sensors_dev, watchman_dev, VIVE_VARIANT_VIVE); + struct vive_device *d = vive_device_create(mainboard_dev, sensors_dev, watchman_dev, VIVE_VARIANT_VIVE); if (d == NULL) { free(sensors_dev); free(mainboard_dev); @@ -140,10 +131,8 @@ init_vive_pro(struct xrt_prober *xp, { log_vive_device(ll, xp, dev); - if (!xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_MANUFACTURER, - VIVE_MANUFACTURER_STRING) || - !xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_PRODUCT, - VIVE_PRO_PRODUCT_STRING)) { + if (!xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_MANUFACTURER, VIVE_MANUFACTURER_STRING) || + !xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_PRODUCT, VIVE_PRO_PRODUCT_STRING)) { U_LOG_D("Vive Pro manufacturer string did not match."); return -1; } @@ -154,14 +143,12 @@ init_vive_pro(struct xrt_prober *xp, for (uint32_t i = 0; i < num_devices; i++) { struct xrt_prober_device *d = devices[i]; - if (d->vendor_id != VALVE_VID && - d->product_id != VIVE_PRO_LHR_PID) + if (d->vendor_id != VALVE_VID && d->product_id != VIVE_PRO_LHR_PID) continue; log_vive_device(ll, xp, d); - int result = - xrt_prober_open_hid_interface(xp, d, 0, &sensors_dev); + int result = xrt_prober_open_hid_interface(xp, d, 0, &sensors_dev); if (result != 0) { U_LOG_E("Could not open Vive sensors device."); return -1; @@ -194,8 +181,7 @@ init_vive_pro(struct xrt_prober *xp, free(sensors_dev); return -1; } - struct vive_device *d = vive_device_create( - mainboard_dev, sensors_dev, watchman_dev, VIVE_VARIANT_PRO); + struct vive_device *d = vive_device_create(mainboard_dev, sensors_dev, watchman_dev, VIVE_VARIANT_PRO); if (d == NULL) { free(sensors_dev); free(mainboard_dev); @@ -217,10 +203,8 @@ init_valve_index(struct xrt_prober *xp, { log_vive_device(ll, xp, dev); - if (!xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_MANUFACTURER, - VALVE_INDEX_MANUFACTURER_STRING) || - !xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_PRODUCT, - VALVE_INDEX_PRODUCT_STRING)) { + if (!xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_MANUFACTURER, VALVE_INDEX_MANUFACTURER_STRING) || + !xrt_prober_match_string(xp, dev, XRT_PROBER_STRING_PRODUCT, VALVE_INDEX_PRODUCT_STRING)) { U_LOG_D("Valve Index manufacturer string did not match."); return -1; } @@ -250,8 +234,7 @@ init_valve_index(struct xrt_prober *xp, return -1; } - struct vive_device *d = vive_device_create( - NULL, sensors_dev, watchman_dev, VIVE_VARIANT_INDEX); + struct vive_device *d = vive_device_create(NULL, sensors_dev, watchman_dev, VIVE_VARIANT_INDEX); if (d == NULL) { return -1; } @@ -281,17 +264,10 @@ vive_found(struct xrt_prober *xp, } switch (dev->product_id) { - case VIVE_PID: - return init_vive1(xp, dev, devices, num_devices, ll, out_xdev); - case VIVE_PRO_MAINBOARD_PID: - return init_vive_pro(xp, dev, devices, num_devices, ll, - out_xdev); - case VIVE_PRO_LHR_PID: - return init_valve_index(xp, dev, devices, num_devices, ll, - out_xdev); - default: - U_LOG_E("No product ids matched %.4x", dev->product_id); - return -1; + case VIVE_PID: return init_vive1(xp, dev, devices, num_devices, ll, out_xdev); + case VIVE_PRO_MAINBOARD_PID: return init_vive_pro(xp, dev, devices, num_devices, ll, out_xdev); + case VIVE_PRO_LHR_PID: return init_valve_index(xp, dev, devices, num_devices, ll, out_xdev); + default: U_LOG_E("No product ids matched %.4x", dev->product_id); return -1; } return -1; @@ -318,18 +294,15 @@ vive_controller_found(struct xrt_prober *xp, } enum watchman_gen gen = WATCHMAN_GEN_UNKNOWN; - if (dev->vendor_id == VALVE_VID && - dev->product_id == VIVE_WATCHMAN_DONGLE) { + if (dev->vendor_id == VALVE_VID && dev->product_id == VIVE_WATCHMAN_DONGLE) { gen = WATCHMAN_GEN1; - } else if (dev->vendor_id == VALVE_VID && - dev->product_id == VIVE_WATCHMAN_DONGLE_GEN2) { + } else if (dev->vendor_id == VALVE_VID && dev->product_id == VIVE_WATCHMAN_DONGLE_GEN2) { gen = WATCHMAN_GEN2; } else { U_LOG_E("Unknown watchman gen"); } - struct vive_controller_device *d = - vive_controller_create(controller_hid, gen, controller_num); + struct vive_controller_device *d = vive_controller_create(controller_hid, gen, controller_num); *out_xdevs = &d->base; diff --git a/src/xrt/drivers/vive/vive_protocol.c b/src/xrt/drivers/vive/vive_protocol.c index d4fd2eb3c..e11ddfb5e 100644 --- a/src/xrt/drivers/vive/vive_protocol.c +++ b/src/xrt/drivers/vive/vive_protocol.c @@ -68,8 +68,7 @@ vive_read_config(struct os_hid_device *hid_dev) .id = VIVE_CONFIG_START_REPORT_ID, }; - int ret = os_hid_get_feature_timeout(hid_dev, &start_report, - sizeof(start_report), 100); + int ret = os_hid_get_feature_timeout(hid_dev, &start_report, sizeof(start_report), 100); if (ret < 0) { U_LOG_E("Could not get config start report."); return NULL; @@ -83,8 +82,7 @@ vive_read_config(struct os_hid_device *hid_dev) uint32_t count = 0; do { - ret = os_hid_get_feature_timeout(hid_dev, &report, - sizeof(report), 100); + ret = os_hid_get_feature_timeout(hid_dev, &report, sizeof(report), 100); if (ret < 0) { U_LOG_E("Read error after %d bytes: %d", count, ret); free(config_z); @@ -145,12 +143,9 @@ vive_read_config(struct os_hid_device *hid_dev) } int -vive_get_imu_range_report(struct os_hid_device *hid_dev, - double *gyro_range, - double *acc_range) +vive_get_imu_range_report(struct os_hid_device *hid_dev, double *gyro_range, double *acc_range) { - struct vive_imu_range_modes_report report = { - .id = VIVE_IMU_RANGE_MODES_REPORT_ID}; + struct vive_imu_range_modes_report report = {.id = VIVE_IMU_RANGE_MODES_REPORT_ID}; int ret; @@ -164,16 +159,14 @@ vive_get_imu_range_report(struct os_hid_device *hid_dev, U_LOG_W( "Invalid gyroscope and accelerometer data." "Trying to fetch again."); - ret = os_hid_get_feature(hid_dev, report.id, (uint8_t *)&report, - sizeof(report)); + ret = os_hid_get_feature(hid_dev, report.id, (uint8_t *)&report, sizeof(report)); if (ret < 0) { U_LOG_E("Could not get feature report %d.", report.id); return ret; } if (!report.gyro_range || !report.accel_range) { - U_LOG_E("Unexpected range mode report: %02x %02x %02x", - report.id, report.gyro_range, + U_LOG_E("Unexpected range mode report: %02x %02x %02x", report.id, report.gyro_range, report.accel_range); for (int i = 0; i < 61; i++) printf(" %02x", report.unknown[i]); @@ -214,8 +207,7 @@ vive_read_firmware(struct os_hid_device *hid_dev, }; int ret; - ret = os_hid_get_feature(hid_dev, report.id, (uint8_t *)&report, - sizeof(report)); + ret = os_hid_get_feature(hid_dev, report.id, (uint8_t *)&report, sizeof(report)); if (ret < 0) return ret; diff --git a/src/xrt/drivers/vive/vive_protocol.h b/src/xrt/drivers/vive/vive_protocol.h index 5c0a87382..61a570af0 100644 --- a/src/xrt/drivers/vive/vive_protocol.h +++ b/src/xrt/drivers/vive/vive_protocol.h @@ -333,9 +333,7 @@ char * vive_read_config(struct os_hid_device *hid_dev); int -vive_get_imu_range_report(struct os_hid_device *hid_dev, - double *gyro_range, - double *acc_range); +vive_get_imu_range_report(struct os_hid_device *hid_dev, double *gyro_range, double *acc_range); int vive_read_firmware(struct os_hid_device *hid_dev, diff --git a/src/xrt/include/xrt/xrt_compiler.h b/src/xrt/include/xrt/xrt_compiler.h index 653adf090..19c97a4e5 100644 --- a/src/xrt/include/xrt/xrt_compiler.h +++ b/src/xrt/include/xrt/xrt_compiler.h @@ -35,8 +35,7 @@ */ #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) -#if defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || \ - defined(_ARCH_PPC64) || defined(__s390x__) || \ +#if defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || defined(_ARCH_PPC64) || defined(__s390x__) || \ (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 8) #define XRT_64_BIT #else @@ -143,5 +142,4 @@ typedef int32_t ssize_t; * * @ingroup xrt_iface */ -#define container_of(ptr, type, field) \ - (type *)((char *)ptr - offsetof(type, field)) +#define container_of(ptr, type, field) (type *)((char *)ptr - offsetof(type, field)) diff --git a/src/xrt/include/xrt/xrt_compositor.h b/src/xrt/include/xrt/xrt_compositor.h index 71629acd8..7a0c7c47a 100644 --- a/src/xrt/include/xrt/xrt_compositor.h +++ b/src/xrt/include/xrt/xrt_compositor.h @@ -381,21 +381,17 @@ struct xrt_swapchain * @param xsc Self pointer * @param[out] out_index Image index to use next */ - xrt_result_t (*acquire_image)(struct xrt_swapchain *xsc, - uint32_t *out_index); + xrt_result_t (*acquire_image)(struct xrt_swapchain *xsc, uint32_t *out_index); /*! * See xrWaitSwapchainImage, state tracker needs to track index. */ - xrt_result_t (*wait_image)(struct xrt_swapchain *xsc, - uint64_t timeout, - uint32_t index); + xrt_result_t (*wait_image)(struct xrt_swapchain *xsc, uint64_t timeout, uint32_t index); /*! * See xrReleaseSwapchainImage, state tracker needs to track index. */ - xrt_result_t (*release_image)(struct xrt_swapchain *xsc, - uint32_t index); + xrt_result_t (*release_image)(struct xrt_swapchain *xsc, uint32_t index); }; /*! @@ -419,9 +415,7 @@ xrt_swapchain_acquire_image(struct xrt_swapchain *xsc, uint32_t *out_index) * @public @memberof xrt_swapchain */ static inline xrt_result_t -xrt_swapchain_wait_image(struct xrt_swapchain *xsc, - uint64_t timeout, - uint32_t index) +xrt_swapchain_wait_image(struct xrt_swapchain *xsc, uint64_t timeout, uint32_t index) { return xsc->wait_image(xsc, timeout, index); } @@ -582,41 +576,35 @@ struct xrt_compositor /*! * Create a swapchain with a set of images. */ - xrt_result_t (*create_swapchain)( - struct xrt_compositor *xc, - const struct xrt_swapchain_create_info *info, - struct xrt_swapchain **out_xsc); + xrt_result_t (*create_swapchain)(struct xrt_compositor *xc, + const struct xrt_swapchain_create_info *info, + struct xrt_swapchain **out_xsc); /*! * Create a swapchain from a set of native images. */ - xrt_result_t (*import_swapchain)( - struct xrt_compositor *xc, - const struct xrt_swapchain_create_info *info, - struct xrt_image_native *native_images, - uint32_t num_images, - struct xrt_swapchain **out_xsc); + xrt_result_t (*import_swapchain)(struct xrt_compositor *xc, + const struct xrt_swapchain_create_info *info, + struct xrt_image_native *native_images, + uint32_t num_images, + struct xrt_swapchain **out_xsc); /*! * Poll events from this compositor. * * This function is very much WIP. */ - xrt_result_t (*poll_events)(struct xrt_compositor *xc, - union xrt_compositor_event *out_xce); + xrt_result_t (*poll_events)(struct xrt_compositor *xc, union xrt_compositor_event *out_xce); /*! * This function is implicit in the OpenXR spec but made explicit here. */ - xrt_result_t (*prepare_session)( - struct xrt_compositor *xc, - const struct xrt_session_prepare_info *xspi); + xrt_result_t (*prepare_session)(struct xrt_compositor *xc, const struct xrt_session_prepare_info *xspi); /*! * See xrBeginSession. */ - xrt_result_t (*begin_session)(struct xrt_compositor *xc, - enum xrt_view_type view_type); + xrt_result_t (*begin_session)(struct xrt_compositor *xc, enum xrt_view_type view_type); /*! * See xrEndSession, unlike the OpenXR one the state tracker is @@ -639,8 +627,7 @@ struct xrt_compositor /*! * See xrBeginFrame. */ - xrt_result_t (*begin_frame)(struct xrt_compositor *xc, - int64_t frame_id); + xrt_result_t (*begin_frame)(struct xrt_compositor *xc, int64_t frame_id); /*! * This isn't in the OpenXR API but is explicit in the XRT interfaces. @@ -653,8 +640,7 @@ struct xrt_compositor * xc->begin_frame(xc, frame_id) * ``` */ - xrt_result_t (*discard_frame)(struct xrt_compositor *xc, - int64_t frame_id); + xrt_result_t (*discard_frame)(struct xrt_compositor *xc, int64_t frame_id); /*! * Begins layer submission, this and the other layer_* calls are @@ -662,9 +648,7 @@ struct xrt_compositor * @p layer_commit that layers will be displayed. From the point of view * of the swapchain the image is used as soon as it's given in a call. */ - xrt_result_t (*layer_begin)(struct xrt_compositor *xc, - int64_t frame_id, - enum xrt_blend_mode env_blend_mode); + xrt_result_t (*layer_begin)(struct xrt_compositor *xc, int64_t frame_id, enum xrt_blend_mode env_blend_mode); /*! * Adds a stereo projection layer for submissions. @@ -675,12 +659,11 @@ struct xrt_compositor * @param r_xsc Right swapchain. * @param data All of the pure data bits. */ - xrt_result_t (*layer_stereo_projection)( - struct xrt_compositor *xc, - struct xrt_device *xdev, - struct xrt_swapchain *l_xsc, - struct xrt_swapchain *r_xsc, - const struct xrt_layer_data *data); + xrt_result_t (*layer_stereo_projection)(struct xrt_compositor *xc, + struct xrt_device *xdev, + struct xrt_swapchain *l_xsc, + struct xrt_swapchain *r_xsc, + const struct xrt_layer_data *data); /*! * Adds a stereo projection layer for submission, has depth information. @@ -693,14 +676,13 @@ struct xrt_compositor * @param r_d_xsc Right depth swapchain. * @param data All of the pure data bits. */ - xrt_result_t (*layer_stereo_projection_depth)( - struct xrt_compositor *xc, - struct xrt_device *xdev, - struct xrt_swapchain *l_xsc, - struct xrt_swapchain *r_xsc, - struct xrt_swapchain *l_d_xsc, - struct xrt_swapchain *r_d_xsc, - const struct xrt_layer_data *data); + xrt_result_t (*layer_stereo_projection_depth)(struct xrt_compositor *xc, + struct xrt_device *xdev, + struct xrt_swapchain *l_xsc, + struct xrt_swapchain *r_xsc, + struct xrt_swapchain *l_d_xsc, + struct xrt_swapchain *r_d_xsc, + const struct xrt_layer_data *data); /*! * Adds a quad layer for submission, the center of the quad is specified @@ -815,8 +797,7 @@ xrt_comp_import_swapchain(struct xrt_compositor *xc, uint32_t num_images, struct xrt_swapchain **out_xsc) { - return xc->import_swapchain(xc, info, native_images, num_images, - out_xsc); + return xc->import_swapchain(xc, info, native_images, num_images, out_xsc); } /*! @@ -827,8 +808,7 @@ xrt_comp_import_swapchain(struct xrt_compositor *xc, * @public @memberof xrt_compositor */ static inline xrt_result_t -xrt_comp_poll_events(struct xrt_compositor *xc, - union xrt_compositor_event *out_xce) +xrt_comp_poll_events(struct xrt_compositor *xc, union xrt_compositor_event *out_xce) { return xc->poll_events(xc, out_xce); } @@ -841,8 +821,7 @@ xrt_comp_poll_events(struct xrt_compositor *xc, * @public @memberof xrt_compositor */ static inline xrt_result_t -xrt_comp_prepare_session(struct xrt_compositor *xc, - const struct xrt_session_prepare_info *xspi) +xrt_comp_prepare_session(struct xrt_compositor *xc, const struct xrt_session_prepare_info *xspi) { return xc->prepare_session(xc, xspi); } @@ -886,8 +865,7 @@ xrt_comp_wait_frame(struct xrt_compositor *xc, uint64_t *predicted_display_time, uint64_t *predicted_display_period) { - return xc->wait_frame(xc, out_frame_id, predicted_display_time, - predicted_display_period); + return xc->wait_frame(xc, out_frame_id, predicted_display_time, predicted_display_period); } /*! @@ -924,9 +902,7 @@ xrt_comp_discard_frame(struct xrt_compositor *xc, int64_t frame_id) * @public @memberof xrt_compositor */ static inline xrt_result_t -xrt_comp_layer_begin(struct xrt_compositor *xc, - int64_t frame_id, - enum xrt_blend_mode env_blend_mode) +xrt_comp_layer_begin(struct xrt_compositor *xc, int64_t frame_id, enum xrt_blend_mode env_blend_mode) { return xc->layer_begin(xc, frame_id, env_blend_mode); } @@ -964,8 +940,7 @@ xrt_comp_layer_stereo_projection_depth(struct xrt_compositor *xc, struct xrt_swapchain *r_d_xsc, const struct xrt_layer_data *data) { - return xc->layer_stereo_projection_depth(xc, xdev, l_xsc, r_xsc, - l_d_xsc, r_d_xsc, data); + return xc->layer_stereo_projection_depth(xc, xdev, l_xsc, r_xsc, l_d_xsc, r_d_xsc, data); } /*! @@ -1057,9 +1032,7 @@ xrt_comp_layer_equirect2(struct xrt_compositor *xc, * @public @memberof xrt_compositor */ static inline xrt_result_t -xrt_comp_layer_commit(struct xrt_compositor *xc, - int64_t frame_id, - xrt_graphics_sync_handle_t sync_handle) +xrt_comp_layer_commit(struct xrt_compositor *xc, int64_t frame_id, xrt_graphics_sync_handle_t sync_handle) { return xc->layer_commit(xc, frame_id, sync_handle); } @@ -1328,11 +1301,10 @@ struct xrt_image_native_allocator * Allocate a set of images suitable to be used to back a swapchain * with the given create info properties (@p xsci). */ - xrt_result_t (*images_allocate)( - struct xrt_image_native_allocator *xina, - const struct xrt_swapchain_create_info *xsci, - size_t num_images, - struct xrt_image_native *out_images); + xrt_result_t (*images_allocate)(struct xrt_image_native_allocator *xina, + const struct xrt_swapchain_create_info *xsci, + size_t num_images, + struct xrt_image_native *out_images); /*! * Free the given images. @@ -1371,9 +1343,7 @@ xrt_images_allocate(struct xrt_image_native_allocator *xina, * @public @memberof xrt_image_native_allocate */ static inline xrt_result_t -xrt_images_free(struct xrt_image_native_allocator *xina, - size_t num_images, - struct xrt_image_native *images) +xrt_images_free(struct xrt_image_native_allocator *xina, size_t num_images, struct xrt_image_native *images) { return xina->images_free(xina, num_images, images); } diff --git a/src/xrt/include/xrt/xrt_defines.h b/src/xrt/include/xrt/xrt_defines.h index 5dd56aaa7..a82ab79d0 100644 --- a/src/xrt/include/xrt/xrt_defines.h +++ b/src/xrt/include/xrt/xrt_defines.h @@ -347,12 +347,9 @@ enum xrt_space_relation_flags XRT_SPACE_RELATION_POSITION_TRACKED_BIT = (1 << 5), // clang-format on XRT_SPACE_RELATION_BITMASK_ALL = - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | - XRT_SPACE_RELATION_POSITION_VALID_BIT | - XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT | - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT | - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | - XRT_SPACE_RELATION_POSITION_TRACKED_BIT, + XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_POSITION_VALID_BIT | + XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT | XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT, XRT_SPACE_RELATION_BITMASK_NONE = 0 }; @@ -669,8 +666,7 @@ enum xrt_finger struct xrt_hand_joint_set { union { - struct xrt_hand_joint_value - hand_joint_set_default[XRT_HAND_JOINT_COUNT]; + struct xrt_hand_joint_value hand_joint_set_default[XRT_HAND_JOINT_COUNT]; } values; // in driver global space, without tracking_origin offset diff --git a/src/xrt/include/xrt/xrt_device.h b/src/xrt/include/xrt/xrt_device.h index f67edb359..47ea18d7e 100644 --- a/src/xrt/include/xrt/xrt_device.h +++ b/src/xrt/include/xrt/xrt_device.h @@ -315,9 +315,7 @@ struct xrt_device * @todo make this param a pointer to const. * @see xrt_output_name */ - void (*set_output)(struct xrt_device *xdev, - enum xrt_output_name name, - union xrt_output_value *value); + void (*set_output)(struct xrt_device *xdev, enum xrt_output_name name, union xrt_output_value *value); /*! * Get the per view pose in relation to the view space. Does not do any @@ -342,11 +340,7 @@ struct xrt_device uint32_t view_index, struct xrt_pose *out_pose); - bool (*compute_distortion)(struct xrt_device *xdev, - int view, - float u, - float v, - struct xrt_uv_triplet *result); + bool (*compute_distortion)(struct xrt_device *xdev, int view, float u, float v, struct xrt_uv_triplet *result); /*! * Destroy device. @@ -376,8 +370,7 @@ xrt_device_get_tracked_pose(struct xrt_device *xdev, uint64_t requested_timestamp_ns, struct xrt_space_relation *out_relation) { - xdev->get_tracked_pose(xdev, name, requested_timestamp_ns, - out_relation); + xdev->get_tracked_pose(xdev, name, requested_timestamp_ns, out_relation); } /*! @@ -400,9 +393,7 @@ xrt_device_get_hand_tracking(struct xrt_device *xdev, * @public @memberof xrt_device */ static inline void -xrt_device_set_output(struct xrt_device *xdev, - enum xrt_output_name name, - union xrt_output_value *value) +xrt_device_set_output(struct xrt_device *xdev, enum xrt_output_name name, union xrt_output_value *value) { xdev->set_output(xdev, name, value); } diff --git a/src/xrt/include/xrt/xrt_frame.h b/src/xrt/include/xrt/xrt_frame.h index f01823eda..d1bdc6861 100644 --- a/src/xrt/include/xrt/xrt_frame.h +++ b/src/xrt/include/xrt/xrt_frame.h @@ -39,7 +39,7 @@ struct xrt_frame uint64_t timestamp; uint64_t source_timestamp; uint64_t source_sequence; //!< sequence id - uint64_t source_id; //!< Which @ref xrt_fs this frame originated from. + uint64_t source_id; //!< Which @ref xrt_fs this frame originated from. }; @@ -59,8 +59,7 @@ struct xrt_frame_sink /*! * Push a frame into the sink. */ - void (*push_frame)(struct xrt_frame_sink *sink, - struct xrt_frame *frame); + void (*push_frame)(struct xrt_frame_sink *sink, struct xrt_frame *frame); }; /*! @@ -143,8 +142,7 @@ xrt_frame_reference(struct xrt_frame **dst, struct xrt_frame *src) * @public @memberof xrt_frame_context */ static inline void -xrt_frame_context_add(struct xrt_frame_context *xfctx, - struct xrt_frame_node *node) +xrt_frame_context_add(struct xrt_frame_context *xfctx, struct xrt_frame_node *node) { node->next = xfctx->nodes; xfctx->nodes = node; diff --git a/src/xrt/include/xrt/xrt_frameserver.h b/src/xrt/include/xrt/xrt_frameserver.h index af13c879b..92c036127 100644 --- a/src/xrt/include/xrt/xrt_frameserver.h +++ b/src/xrt/include/xrt/xrt_frameserver.h @@ -80,16 +80,13 @@ struct xrt_fs /*! * Enumerate all available modes that this frameserver supports. */ - bool (*enumerate_modes)(struct xrt_fs *xfs, - struct xrt_fs_mode **out_modes, - uint32_t *out_count); + bool (*enumerate_modes)(struct xrt_fs *xfs, struct xrt_fs_mode **out_modes, uint32_t *out_count); /*! * Set the capture parameters, may not be supported on all capture * devices. */ - bool (*configure_capture)(struct xrt_fs *xfs, - struct xrt_fs_capture_parameters *cp); + bool (*configure_capture)(struct xrt_fs *xfs, struct xrt_fs_capture_parameters *cp); /*! * Start the capture stream. @@ -125,9 +122,7 @@ struct xrt_fs * @public @memberof xrt_fs */ static inline bool -xrt_fs_enumerate_modes(struct xrt_fs *xfs, - struct xrt_fs_mode **out_modes, - uint32_t *out_count) +xrt_fs_enumerate_modes(struct xrt_fs *xfs, struct xrt_fs_mode **out_modes, uint32_t *out_count) { return xfs->enumerate_modes(xfs, out_modes, out_count); } @@ -140,8 +135,7 @@ xrt_fs_enumerate_modes(struct xrt_fs *xfs, * @public @memberof xrt_fs */ static inline bool -xrt_fs_configure_capture(struct xrt_fs *xfs, - struct xrt_fs_capture_parameters *cp) +xrt_fs_configure_capture(struct xrt_fs *xfs, struct xrt_fs_capture_parameters *cp) { return xfs->configure_capture(xfs, cp); } diff --git a/src/xrt/include/xrt/xrt_gfx_egl.h b/src/xrt/include/xrt/xrt_gfx_egl.h index 1d4363081..44af50142 100644 --- a/src/xrt/include/xrt/xrt_gfx_egl.h +++ b/src/xrt/include/xrt/xrt_gfx_egl.h @@ -20,8 +20,7 @@ typedef void *EGLDisplay; typedef void *EGLConfig; typedef void *EGLContext; typedef void (*__eglMustCastToProperFunctionPointerType)(void); -typedef __eglMustCastToProperFunctionPointerType (*PFNEGLGETPROCADDRESSPROC)( - const char *proc); +typedef __eglMustCastToProperFunctionPointerType (*PFNEGLGETPROCADDRESSPROC)(const char *proc); struct time_state; /*! diff --git a/src/xrt/include/xrt/xrt_instance.h b/src/xrt/include/xrt/xrt_instance.h index d90e756ef..ce524cbc7 100644 --- a/src/xrt/include/xrt/xrt_instance.h +++ b/src/xrt/include/xrt/xrt_instance.h @@ -81,9 +81,7 @@ struct xrt_instance * * @see xrt_prober::probe, xrt_prober::select */ - int (*select)(struct xrt_instance *xinst, - struct xrt_device **xdevs, - size_t num_xdevs); + int (*select)(struct xrt_instance *xinst, struct xrt_device **xdevs, size_t num_xdevs); /*! * Creates a @ref xrt_compositor_native. @@ -127,8 +125,7 @@ struct xrt_instance * @return 0 on success, <0 on error. (Note that success may mean * returning a null pointer!) */ - int (*get_prober)(struct xrt_instance *xinst, - struct xrt_prober **out_xp); + int (*get_prober)(struct xrt_instance *xinst, struct xrt_prober **out_xp); /*! * Destroy the instance and its owned objects, including the prober (if @@ -153,9 +150,7 @@ struct xrt_instance * @public @memberof xrt_instance */ static inline int -xrt_instance_select(struct xrt_instance *xinst, - struct xrt_device **xdevs, - size_t num_xdevs) +xrt_instance_select(struct xrt_instance *xinst, struct xrt_device **xdevs, size_t num_xdevs) { return xinst->select(xinst, xdevs, num_xdevs); } @@ -233,8 +228,7 @@ xrt_instance_destroy(struct xrt_instance **xinst_ptr) * @relates xrt_instance */ int -xrt_instance_create(struct xrt_instance_info *ii, - struct xrt_instance **out_xinst +xrt_instance_create(struct xrt_instance_info *ii, struct xrt_instance **out_xinst ); diff --git a/src/xrt/include/xrt/xrt_openxr_includes.h b/src/xrt/include/xrt/xrt_openxr_includes.h index 5d87246e8..9ab416bc6 100644 --- a/src/xrt/include/xrt/xrt_openxr_includes.h +++ b/src/xrt/include/xrt/xrt_openxr_includes.h @@ -34,8 +34,7 @@ typedef void *EGLDisplay; typedef void *EGLContext; typedef void *EGLConfig; typedef void (*__eglMustCastToProperFunctionPointerType)(void); -typedef __eglMustCastToProperFunctionPointerType (*PFNEGLGETPROCADDRESSPROC)( - const char *procname); +typedef __eglMustCastToProperFunctionPointerType (*PFNEGLGETPROCADDRESSPROC)(const char *procname); #endif #ifdef XR_USE_TIMESPEC diff --git a/src/xrt/include/xrt/xrt_prober.h b/src/xrt/include/xrt/xrt_prober.h index b66f2a5c5..ad7623bba 100644 --- a/src/xrt/include/xrt/xrt_prober.h +++ b/src/xrt/include/xrt/xrt_prober.h @@ -190,9 +190,7 @@ struct xrt_prober * xrt_instance_select() method which usually calls xrt_prober_probe() * and xrt_prober_select(). */ - int (*select)(struct xrt_prober *xp, - struct xrt_device **xdevs, - size_t num_xdevs); + int (*select)(struct xrt_prober *xp, struct xrt_device **xdevs, size_t num_xdevs); int (*open_hid_interface)(struct xrt_prober *xp, struct xrt_prober_device *xpdev, int interface, @@ -201,16 +199,13 @@ struct xrt_prober struct xrt_prober_device *xpdev, struct xrt_frame_context *xfctx, struct xrt_fs **out_xfs); - int (*list_video_devices)(struct xrt_prober *xp, - xrt_prober_list_video_cb cb, - void *ptr); + int (*list_video_devices)(struct xrt_prober *xp, xrt_prober_list_video_cb cb, void *ptr); int (*get_string_descriptor)(struct xrt_prober *xp, struct xrt_prober_device *xpdev, enum xrt_prober_string which_string, unsigned char *buffer, int length); - bool (*can_open)(struct xrt_prober *xp, - struct xrt_prober_device *xpdev); + bool (*can_open)(struct xrt_prober *xp, struct xrt_prober_device *xpdev); /*! * Destroy the prober and set the pointer to null. * @@ -249,9 +244,7 @@ xrt_prober_dump(struct xrt_prober *xp) * @public @memberof xrt_prober */ static inline int -xrt_prober_select(struct xrt_prober *xp, - struct xrt_device **xdevs, - size_t num_xdevs) +xrt_prober_select(struct xrt_prober *xp, struct xrt_device **xdevs, size_t num_xdevs) { return xp->select(xp, xdevs, num_xdevs); } @@ -282,8 +275,7 @@ xrt_prober_get_string_descriptor(struct xrt_prober *xp, unsigned char *buffer, int length) { - return xp->get_string_descriptor(xp, xpdev, which_string, buffer, - length); + return xp->get_string_descriptor(xp, xpdev, which_string, buffer, length); } /*! @@ -318,9 +310,7 @@ xrt_prober_open_video_device(struct xrt_prober *xp, * @public @memberof xrt_prober */ static inline int -xrt_prober_list_video_devices(struct xrt_prober *xp, - xrt_prober_list_video_cb cb, - void *ptr) +xrt_prober_list_video_devices(struct xrt_prober *xp, xrt_prober_list_video_cb cb, void *ptr) { return xp->list_video_devices(xp, cb, ptr); } @@ -354,8 +344,7 @@ xrt_prober_destroy(struct xrt_prober **xp_ptr) * @public @memberof xrt_prober */ int -xrt_prober_create_with_lists(struct xrt_prober **out_xp, - struct xrt_prober_entry_lists *list); +xrt_prober_create_with_lists(struct xrt_prober **out_xp, struct xrt_prober_entry_lists *list); /*! * @public @memberof xrt_prober diff --git a/src/xrt/include/xrt/xrt_tracking.h b/src/xrt/include/xrt/xrt_tracking.h index 21599a1b9..ee1e11d01 100644 --- a/src/xrt/include/xrt/xrt_tracking.h +++ b/src/xrt/include/xrt/xrt_tracking.h @@ -140,9 +140,7 @@ struct xrt_tracked_psmv /*! * Push a IMU sample into the tracking system. */ - void (*push_imu)(struct xrt_tracked_psmv *, - timepoint_ns timestamp_ns, - struct xrt_tracking_sample *sample); + void (*push_imu)(struct xrt_tracked_psmv *, timepoint_ns timestamp_ns, struct xrt_tracking_sample *sample); /*! * Called by the owning @ref xrt_device @ref xdev to get the pose of @@ -181,9 +179,7 @@ struct xrt_tracked_psvr /*! * Push a IMU sample into the tracking system. */ - void (*push_imu)(struct xrt_tracked_psvr *, - timepoint_ns timestamp_ns, - struct xrt_tracking_sample *sample); + void (*push_imu)(struct xrt_tracked_psvr *, timepoint_ns timestamp_ns, struct xrt_tracking_sample *sample); /*! * Called by the owning @ref xrt_device @ref xdev to get the pose of @@ -246,9 +242,7 @@ xrt_tracked_psmv_get_tracked_pose(struct xrt_tracked_psmv *psmv, //! @public @memberof xrt_tracked_psmv static inline void -xrt_tracked_psmv_push_imu(struct xrt_tracked_psmv *psmv, - timepoint_ns timestamp_ns, - struct xrt_tracking_sample *sample) +xrt_tracked_psmv_push_imu(struct xrt_tracked_psmv *psmv, timepoint_ns timestamp_ns, struct xrt_tracking_sample *sample) { psmv->push_imu(psmv, timestamp_ns, sample); } @@ -277,9 +271,7 @@ xrt_tracked_psvr_get_tracked_pose(struct xrt_tracked_psvr *psvr, //! @public @memberof xrt_tracked_psmv static inline void -xrt_tracked_psvr_push_imu(struct xrt_tracked_psvr *psvr, - timepoint_ns timestamp_ns, - struct xrt_tracking_sample *sample) +xrt_tracked_psvr_push_imu(struct xrt_tracked_psvr *psvr, timepoint_ns timestamp_ns, struct xrt_tracking_sample *sample) { psvr->push_imu(psvr, timestamp_ns, sample); } diff --git a/src/xrt/ipc/android/ipc_client_android.cpp b/src/xrt/ipc/android/ipc_client_android.cpp index de516702e..46adb195a 100644 --- a/src/xrt/ipc/android/ipc_client_android.cpp +++ b/src/xrt/ipc/android/ipc_client_android.cpp @@ -39,8 +39,7 @@ ipc_client_android::~ipc_client_android() } } catch (std::exception const &e) { // Must catch and ignore any exceptions in the destructor! - U_LOG_E("Failure while marking IPC client as discarded: %s", - e.what()); + U_LOG_E("Failure while marking IPC client as discarded: %s", e.what()); } } @@ -52,27 +51,22 @@ ipc_client_android_create(struct _JavaVM *vm, void *activity) try { auto info = getAppInfo(XRT_ANDROID_PACKAGE, (jobject)activity); if (info.isNull()) { - U_LOG_E( - "Could not get application info for package '%s'", - "org.freedesktop.monado.openxr_runtime"); + U_LOG_E("Could not get application info for package '%s'", + "org.freedesktop.monado.openxr_runtime"); return nullptr; } - auto clazz = - loadClassFromPackage(info, (jobject)activity, - Client::getFullyQualifiedTypeName()); + auto clazz = loadClassFromPackage(info, (jobject)activity, Client::getFullyQualifiedTypeName()); if (clazz.isNull()) { - U_LOG_E("Could not load class '%s' from package '%s'", - Client::getFullyQualifiedTypeName(), + U_LOG_E("Could not load class '%s' from package '%s'", Client::getFullyQualifiedTypeName(), XRT_ANDROID_PACKAGE); return nullptr; } // Teach the wrapper our class before we start to use it. Client::staticInitClass((jclass)clazz.object().getHandle()); - std::unique_ptr ret = - std::make_unique((jobject)activity); + std::unique_ptr ret = std::make_unique((jobject)activity); ret->client = Client::construct(ret.get()); @@ -88,8 +82,7 @@ int ipc_client_android_blocking_connect(struct ipc_client_android *ica) { try { - int fd = ica->client.blockingConnect(ica->activity, - XRT_ANDROID_PACKAGE); + int fd = ica->client.blockingConnect(ica->activity, XRT_ANDROID_PACKAGE); return fd; } catch (std::exception const &e) { // Must catch and ignore any exceptions in the destructor! diff --git a/src/xrt/ipc/android/org.freedesktop.monado.ipc.cpp b/src/xrt/ipc/android/org.freedesktop.monado.ipc.cpp index 81063a8bb..9c8e3d5a5 100644 --- a/src/xrt/ipc/android/org.freedesktop.monado.ipc.cpp +++ b/src/xrt/ipc/android/org.freedesktop.monado.ipc.cpp @@ -13,19 +13,14 @@ namespace wrap { namespace org::freedesktop::monado::ipc { Client::Meta::Meta(jni::jclass clazz) - : MetaBase(Client::getTypeName(), clazz), - monado(classRef(), "monado"), failed(classRef(), "failed"), + : MetaBase(Client::getTypeName(), clazz), monado(classRef(), "monado"), failed(classRef(), "failed"), init(classRef().getMethod("", "(J)V")), - markAsDiscardedByNative( - classRef().getMethod("markAsDiscardedByNative", "()V")), - blockingConnect(classRef().getMethod( - "blockingConnect", - "(Landroid/content/Context;Ljava/lang/String;)I")) + markAsDiscardedByNative(classRef().getMethod("markAsDiscardedByNative", "()V")), + blockingConnect(classRef().getMethod("blockingConnect", "(Landroid/content/Context;Ljava/lang/String;)I")) {} IMonado::Meta::Meta(jni::jclass clazz) : MetaBase(IMonado::getTypeName(), clazz), - passAppSurface(classRef().getMethod("passAppSurface", - "(Landroid/view/Surface;)V")) + passAppSurface(classRef().getMethod("passAppSurface", "(Landroid/view/Surface;)V")) {} } // namespace org::freedesktop::monado::ipc } // namespace wrap diff --git a/src/xrt/ipc/android/org.freedesktop.monado.ipc.hpp b/src/xrt/ipc/android/org.freedesktop.monado.ipc.hpp index a381e6e6c..e2ca7e265 100644 --- a/src/xrt/ipc/android/org.freedesktop.monado.ipc.hpp +++ b/src/xrt/ipc/android/org.freedesktop.monado.ipc.hpp @@ -108,8 +108,7 @@ namespace org::freedesktop::monado::ipc { * */ int32_t - blockingConnect(android::content::Context const &context, - std::string const &packageName); + blockingConnect(android::content::Context const &context, std::string const &packageName); /*! * Initialize the static metadata of this wrapper with a known diff --git a/src/xrt/ipc/android/org.freedesktop.monado.ipc.impl.hpp b/src/xrt/ipc/android/org.freedesktop.monado.ipc.impl.hpp index db80f4c2b..dd2c8178a 100644 --- a/src/xrt/ipc/android/org.freedesktop.monado.ipc.impl.hpp +++ b/src/xrt/ipc/android/org.freedesktop.monado.ipc.impl.hpp @@ -34,33 +34,27 @@ namespace org::freedesktop::monado::ipc { Client::construct(void *nativePointer) { return Client(Meta::data().clazz().newInstance( - Meta::data().init, - static_cast( - reinterpret_cast(nativePointer)))); + Meta::data().init, static_cast(reinterpret_cast(nativePointer)))); } inline void Client::markAsDiscardedByNative() { assert(!isNull()); - return object().call( - Meta::data().markAsDiscardedByNative); + return object().call(Meta::data().markAsDiscardedByNative); } inline int32_t - Client::blockingConnect(android::content::Context const &context, - std::string const &packageName) + Client::blockingConnect(android::content::Context const &context, std::string const &packageName) { assert(!isNull()); - return object().call(Meta::data().blockingConnect, - context.object(), packageName); + return object().call(Meta::data().blockingConnect, context.object(), packageName); } inline void IMonado::passAppSurface(android::view::Surface const &surface) { assert(!isNull()); - return object().call(Meta::data().passAppSurface, - surface.object()); + return object().call(Meta::data().passAppSurface, surface.object()); } } // namespace org::freedesktop::monado::ipc } // namespace wrap diff --git a/src/xrt/ipc/client/ipc_client.h b/src/xrt/ipc/client/ipc_client.h index 23a09c386..a46fd738d 100644 --- a/src/xrt/ipc/client/ipc_client.h +++ b/src/xrt/ipc/client/ipc_client.h @@ -83,11 +83,7 @@ ipc_client_compositor_create(struct ipc_connection *ipc_c, struct xrt_compositor_native **out_xcn); struct xrt_device * -ipc_client_hmd_create(struct ipc_connection *ipc_c, - struct xrt_tracking_origin *xtrack, - uint32_t device_id); +ipc_client_hmd_create(struct ipc_connection *ipc_c, struct xrt_tracking_origin *xtrack, uint32_t device_id); struct xrt_device * -ipc_client_device_create(struct ipc_connection *ipc_c, - struct xrt_tracking_origin *xtrack, - uint32_t device_id); +ipc_client_device_create(struct ipc_connection *ipc_c, struct xrt_tracking_origin *xtrack, uint32_t device_id); diff --git a/src/xrt/ipc/client/ipc_client_compositor.c b/src/xrt/ipc/client/ipc_client_compositor.c index bc6c4086a..925442fac 100644 --- a/src/xrt/ipc/client/ipc_client_compositor.c +++ b/src/xrt/ipc/client/ipc_client_compositor.c @@ -109,10 +109,10 @@ compositor_disconnect(struct ipc_connection *ipc_c) ipc_message_channel_close(&ipc_c->imc); } -#define IPC_CALL_CHK(call) \ - xrt_result_t res = (call); \ - if (res == XRT_ERROR_IPC_FAILURE) { \ - IPC_ERROR(icc->ipc_c, "IPC: %s call error!", __func__); \ +#define IPC_CALL_CHK(call) \ + xrt_result_t res = (call); \ + if (res == XRT_ERROR_IPC_FAILURE) { \ + IPC_ERROR(icc->ipc_c, "IPC: %s call error!", __func__); \ } static xrt_result_t @@ -144,41 +144,34 @@ ipc_compositor_swapchain_destroy(struct xrt_swapchain *xsc) } static xrt_result_t -ipc_compositor_swapchain_wait_image(struct xrt_swapchain *xsc, - uint64_t timeout, - uint32_t index) +ipc_compositor_swapchain_wait_image(struct xrt_swapchain *xsc, uint64_t timeout, uint32_t index) { struct ipc_client_swapchain *ics = ipc_client_swapchain(xsc); struct ipc_client_compositor *icc = ics->icc; - IPC_CALL_CHK( - ipc_call_swapchain_wait_image(icc->ipc_c, ics->id, timeout, index)); + IPC_CALL_CHK(ipc_call_swapchain_wait_image(icc->ipc_c, ics->id, timeout, index)); return res; } static xrt_result_t -ipc_compositor_swapchain_acquire_image(struct xrt_swapchain *xsc, - uint32_t *out_index) +ipc_compositor_swapchain_acquire_image(struct xrt_swapchain *xsc, uint32_t *out_index) { struct ipc_client_swapchain *ics = ipc_client_swapchain(xsc); struct ipc_client_compositor *icc = ics->icc; - IPC_CALL_CHK( - ipc_call_swapchain_acquire_image(icc->ipc_c, ics->id, out_index)); + IPC_CALL_CHK(ipc_call_swapchain_acquire_image(icc->ipc_c, ics->id, out_index)); return res; } static xrt_result_t -ipc_compositor_swapchain_release_image(struct xrt_swapchain *xsc, - uint32_t index) +ipc_compositor_swapchain_release_image(struct xrt_swapchain *xsc, uint32_t index) { struct ipc_client_swapchain *ics = ipc_client_swapchain(xsc); struct ipc_client_compositor *icc = ics->icc; - IPC_CALL_CHK( - ipc_call_swapchain_release_image(icc->ipc_c, ics->id, index)); + IPC_CALL_CHK(ipc_call_swapchain_release_image(icc->ipc_c, ics->id, index)); return res; } @@ -196,8 +189,7 @@ swapchain_server_create(struct ipc_client_compositor *icc, const struct xrt_swapchain_create_info *info, struct xrt_swapchain **out_xsc) { - xrt_graphics_buffer_handle_t remote_handles[IPC_MAX_SWAPCHAIN_HANDLES] = - {0}; + xrt_graphics_buffer_handle_t remote_handles[IPC_MAX_SWAPCHAIN_HANDLES] = {0}; xrt_result_t r = XRT_SUCCESS; uint32_t handle; uint32_t num_images; @@ -214,8 +206,7 @@ swapchain_server_create(struct ipc_client_compositor *icc, return r; } - struct ipc_client_swapchain *ics = - U_TYPED_CALLOC(struct ipc_client_swapchain); + struct ipc_client_swapchain *ics = U_TYPED_CALLOC(struct ipc_client_swapchain); ics->base.base.num_images = num_images; ics->base.base.wait_image = ipc_compositor_swapchain_wait_image; ics->base.base.acquire_image = ipc_compositor_swapchain_acquire_image; @@ -262,8 +253,7 @@ swapchain_server_import(struct ipc_client_compositor *icc, return r; } - struct ipc_client_swapchain *ics = - U_TYPED_CALLOC(struct ipc_client_swapchain); + struct ipc_client_swapchain *ics = U_TYPED_CALLOC(struct ipc_client_swapchain); ics->base.base.num_images = num_images; ics->base.base.wait_image = ipc_compositor_swapchain_wait_image; ics->base.base.acquire_image = ipc_compositor_swapchain_acquire_image; @@ -339,13 +329,11 @@ ipc_compositor_swapchain_import(struct xrt_compositor *xc, struct xrt_swapchain **out_xsc) { struct ipc_client_compositor *icc = ipc_client_compositor(xc); - return swapchain_server_import(icc, info, native_images, num_images, - out_xsc); + return swapchain_server_import(icc, info, native_images, num_images, out_xsc); } static xrt_result_t -ipc_compositor_prepare_session(struct xrt_compositor *xc, - const struct xrt_session_prepare_info *xspi) +ipc_compositor_prepare_session(struct xrt_compositor *xc, const struct xrt_session_prepare_info *xspi) { struct ipc_client_compositor *icc = ipc_client_compositor(xc); @@ -356,8 +344,7 @@ ipc_compositor_prepare_session(struct xrt_compositor *xc, } static xrt_result_t -ipc_compositor_poll_events(struct xrt_compositor *xc, - union xrt_compositor_event *out_xce) +ipc_compositor_poll_events(struct xrt_compositor *xc, union xrt_compositor_event *out_xce) { struct ipc_client_compositor *icc = ipc_client_compositor(xc); @@ -369,8 +356,7 @@ ipc_compositor_poll_events(struct xrt_compositor *xc, } static xrt_result_t -ipc_compositor_begin_session(struct xrt_compositor *xc, - enum xrt_view_type view_type) +ipc_compositor_begin_session(struct xrt_compositor *xc, enum xrt_view_type view_type) { struct ipc_client_compositor *icc = ipc_client_compositor(xc); @@ -404,13 +390,12 @@ ipc_compositor_wait_frame(struct xrt_compositor *xc, uint64_t wake_up_time_ns = 0; uint64_t min_display_period_ns = 0; - IPC_CALL_CHK(ipc_call_compositor_wait_frame( - icc->ipc_c, // Connection - out_frame_id, // Frame id - out_predicted_display_time, // Display time - &wake_up_time_ns, // When we should wake up - out_predicted_display_period, // Current period - &min_display_period_ns)); // Minimum display period + IPC_CALL_CHK(ipc_call_compositor_wait_frame(icc->ipc_c, // Connection + out_frame_id, // Frame id + out_predicted_display_time, // Display time + &wake_up_time_ns, // When we should wake up + out_predicted_display_period, // Current period + &min_display_period_ns)); // Minimum display period uint64_t now_ns = os_monotonic_get_ns(); @@ -464,9 +449,7 @@ ipc_compositor_begin_frame(struct xrt_compositor *xc, int64_t frame_id) } static xrt_result_t -ipc_compositor_layer_begin(struct xrt_compositor *xc, - int64_t frame_id, - enum xrt_blend_mode env_blend_mode) +ipc_compositor_layer_begin(struct xrt_compositor *xc, int64_t frame_id, enum xrt_blend_mode env_blend_mode) { struct ipc_client_compositor *icc = ipc_client_compositor(xc); @@ -614,9 +597,7 @@ ipc_compositor_layer_equirect2(struct xrt_compositor *xc, } static xrt_result_t -ipc_compositor_layer_commit(struct xrt_compositor *xc, - int64_t frame_id, - xrt_graphics_sync_handle_t sync_handle) +ipc_compositor_layer_commit(struct xrt_compositor *xc, int64_t frame_id, xrt_graphics_sync_handle_t sync_handle) { struct ipc_client_compositor *icc = ipc_client_compositor(xc); @@ -690,8 +671,7 @@ ipc_compositor_images_allocate(struct xrt_image_native_allocator *xina, size_t in_num_images, struct xrt_image_native *out_images) { - struct ipc_client_compositor *icc = - container_of(xina, struct ipc_client_compositor, loopback_xina); + struct ipc_client_compositor *icc = container_of(xina, struct ipc_client_compositor, loopback_xina); int remote_fds[IPC_MAX_SWAPCHAIN_FDS] = {0}; xrt_result_t r = XRT_SUCCESS; @@ -798,8 +778,7 @@ ipc_client_compositor_create(struct ipc_connection *ipc_c, struct xrt_device *xdev, struct xrt_compositor_native **out_xcn) { - struct ipc_client_compositor *c = - U_TYPED_CALLOC(struct ipc_client_compositor); + struct ipc_client_compositor *c = U_TYPED_CALLOC(struct ipc_client_compositor); c->base.base.create_swapchain = ipc_compositor_swapchain_create; c->base.base.import_swapchain = ipc_compositor_swapchain_import; @@ -810,10 +789,8 @@ ipc_client_compositor_create(struct ipc_connection *ipc_c, c->base.base.begin_frame = ipc_compositor_begin_frame; c->base.base.discard_frame = ipc_compositor_discard_frame; c->base.base.layer_begin = ipc_compositor_layer_begin; - c->base.base.layer_stereo_projection = - ipc_compositor_layer_stereo_projection; - c->base.base.layer_stereo_projection_depth = - ipc_compositor_layer_stereo_projection_depth; + c->base.base.layer_stereo_projection = ipc_compositor_layer_stereo_projection; + c->base.base.layer_stereo_projection_depth = ipc_compositor_layer_stereo_projection_depth; c->base.base.layer_quad = ipc_compositor_layer_quad; c->base.base.layer_cube = ipc_compositor_layer_cube; c->base.base.layer_cylinder = ipc_compositor_layer_cylinder; diff --git a/src/xrt/ipc/client/ipc_client_device.c b/src/xrt/ipc/client/ipc_client_device.c index 8cb24e23f..ca84dbccb 100644 --- a/src/xrt/ipc/client/ipc_client_device.c +++ b/src/xrt/ipc/client/ipc_client_device.c @@ -82,8 +82,7 @@ ipc_client_device_update_inputs(struct xrt_device *xdev) { struct ipc_client_device *icd = ipc_client_device(xdev); - xrt_result_t r = - ipc_call_device_update_input(icd->ipc_c, icd->device_id); + xrt_result_t r = ipc_call_device_update_input(icd->ipc_c, icd->device_id); if (r != XRT_SUCCESS) { IPC_ERROR(icd->ipc_c, "Error sending input update!"); } @@ -97,8 +96,8 @@ ipc_client_device_get_tracked_pose(struct xrt_device *xdev, { struct ipc_client_device *icd = ipc_client_device(xdev); - xrt_result_t r = ipc_call_device_get_tracked_pose( - icd->ipc_c, icd->device_id, name, at_timestamp_ns, out_relation); + xrt_result_t r = + ipc_call_device_get_tracked_pose(icd->ipc_c, icd->device_id, name, at_timestamp_ns, out_relation); if (r != XRT_SUCCESS) { IPC_ERROR(icd->ipc_c, "Error sending input update!"); } @@ -112,8 +111,8 @@ ipc_client_device_get_hand_tracking(struct xrt_device *xdev, { struct ipc_client_device *icd = ipc_client_device(xdev); - xrt_result_t r = ipc_call_device_get_hand_tracking( - icd->ipc_c, icd->device_id, name, at_timestamp_ns, out_value); + xrt_result_t r = + ipc_call_device_get_hand_tracking(icd->ipc_c, icd->device_id, name, at_timestamp_ns, out_value); if (r != XRT_SUCCESS) { IPC_ERROR(icd->ipc_c, "IPC: Error sending input update!"); } @@ -129,14 +128,11 @@ ipc_client_device_get_view_pose(struct xrt_device *xdev, } static void -ipc_client_device_set_output(struct xrt_device *xdev, - enum xrt_output_name name, - union xrt_output_value *value) +ipc_client_device_set_output(struct xrt_device *xdev, enum xrt_output_name name, union xrt_output_value *value) { struct ipc_client_device *icd = ipc_client_device(xdev); - xrt_result_t r = - ipc_call_device_set_output(icd->ipc_c, icd->device_id, name, value); + xrt_result_t r = ipc_call_device_set_output(icd->ipc_c, icd->device_id, name, value); if (r != XRT_SUCCESS) { IPC_ERROR(icd->ipc_c, "IPC: Error sending set output!"); } @@ -146,19 +142,15 @@ ipc_client_device_set_output(struct xrt_device *xdev, * @public @memberof ipc_client_device */ struct xrt_device * -ipc_client_device_create(struct ipc_connection *ipc_c, - struct xrt_tracking_origin *xtrack, - uint32_t device_id) +ipc_client_device_create(struct ipc_connection *ipc_c, struct xrt_tracking_origin *xtrack, uint32_t device_id) { // Helpers. struct ipc_shared_memory *ism = ipc_c->ism; struct ipc_shared_device *isdev = &ism->isdevs[device_id]; // Allocate and setup the basics. - enum u_device_alloc_flags flags = - (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD); - struct ipc_client_device *icd = - U_DEVICE_ALLOCATE(struct ipc_client_device, flags, 0, 0); + enum u_device_alloc_flags flags = (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD); + struct ipc_client_device *icd = U_DEVICE_ALLOCATE(struct ipc_client_device, flags, 0, 0); icd->ipc_c = ipc_c; icd->base.update_inputs = ipc_client_device_update_inputs; icd->base.get_tracked_pose = ipc_client_device_get_tracked_pose; @@ -189,27 +181,23 @@ ipc_client_device_create(struct ipc_connection *ipc_c, } if (isdev->num_binding_profiles > 0) { - icd->base.binding_profiles = U_TYPED_ARRAY_CALLOC( - struct xrt_binding_profile, isdev->num_binding_profiles); + icd->base.binding_profiles = + U_TYPED_ARRAY_CALLOC(struct xrt_binding_profile, isdev->num_binding_profiles); icd->base.num_binding_profiles = isdev->num_binding_profiles; } for (size_t i = 0; i < isdev->num_binding_profiles; i++) { - struct xrt_binding_profile *xbp = - &icd->base.binding_profiles[i]; + struct xrt_binding_profile *xbp = &icd->base.binding_profiles[i]; struct ipc_shared_binding_profile *isbp = - &ism->binding_profiles[isdev->first_binding_profile_index + - i]; + &ism->binding_profiles[isdev->first_binding_profile_index + i]; xbp->name = isbp->name; if (isbp->num_inputs > 0) { - xbp->inputs = - &ism->input_pairs[isbp->first_input_index]; + xbp->inputs = &ism->input_pairs[isbp->first_input_index]; xbp->num_inputs = isbp->num_inputs; } if (isbp->num_outputs > 0) { - xbp->outputs = - &ism->output_pairs[isbp->first_output_index]; + xbp->outputs = &ism->output_pairs[isbp->first_output_index]; xbp->num_outputs = isbp->num_inputs; } } @@ -218,10 +206,8 @@ ipc_client_device_create(struct ipc_connection *ipc_c, u_var_add_root(icd, icd->base.str, true); u_var_add_ro_u32(icd, &icd->device_id, "device_id"); - icd->base.orientation_tracking_supported = - isdev->orientation_tracking_supported; - icd->base.position_tracking_supported = - isdev->position_tracking_supported; + icd->base.orientation_tracking_supported = isdev->orientation_tracking_supported; + icd->base.position_tracking_supported = isdev->position_tracking_supported; icd->base.hand_tracking_supported = isdev->hand_tracking_supported; icd->base.device_type = isdev->device_type; diff --git a/src/xrt/ipc/client/ipc_client_hmd.c b/src/xrt/ipc/client/ipc_client_hmd.c index df27a695f..39fb5fb56 100644 --- a/src/xrt/ipc/client/ipc_client_hmd.c +++ b/src/xrt/ipc/client/ipc_client_hmd.c @@ -83,8 +83,7 @@ ipc_client_hmd_update_inputs(struct xrt_device *xdev) { struct ipc_client_hmd *ich = ipc_client_hmd(xdev); - xrt_result_t r = - ipc_call_device_update_input(ich->ipc_c, ich->device_id); + xrt_result_t r = ipc_call_device_update_input(ich->ipc_c, ich->device_id); if (r != XRT_SUCCESS) { IPC_ERROR(ich->ipc_c, "Error calling input update!"); } @@ -98,8 +97,8 @@ ipc_client_hmd_get_tracked_pose(struct xrt_device *xdev, { struct ipc_client_hmd *ich = ipc_client_hmd(xdev); - xrt_result_t r = ipc_call_device_get_tracked_pose( - ich->ipc_c, ich->device_id, name, at_timestamp_ns, out_relation); + xrt_result_t r = + ipc_call_device_get_tracked_pose(ich->ipc_c, ich->device_id, name, at_timestamp_ns, out_relation); if (r != XRT_SUCCESS) { IPC_ERROR(ich->ipc_c, "Error calling tracked pose!"); } @@ -113,8 +112,7 @@ ipc_client_hmd_get_view_pose(struct xrt_device *xdev, { struct ipc_client_hmd *ich = ipc_client_hmd(xdev); - xrt_result_t r = ipc_call_device_get_view_pose( - ich->ipc_c, ich->device_id, eye_relation, view_index, out_pose); + xrt_result_t r = ipc_call_device_get_view_pose(ich->ipc_c, ich->device_id, eye_relation, view_index, out_pose); if (r != XRT_SUCCESS) { IPC_ERROR(ich->ipc_c, "IPC: Error calling view pose!"); } @@ -124,19 +122,15 @@ ipc_client_hmd_get_view_pose(struct xrt_device *xdev, * @public @memberof ipc_client_hmd */ struct xrt_device * -ipc_client_hmd_create(struct ipc_connection *ipc_c, - struct xrt_tracking_origin *xtrack, - uint32_t device_id) +ipc_client_hmd_create(struct ipc_connection *ipc_c, struct xrt_tracking_origin *xtrack, uint32_t device_id) { struct ipc_shared_memory *ism = ipc_c->ism; struct ipc_shared_device *isdev = &ism->isdevs[device_id]; - enum u_device_alloc_flags flags = - (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD); - struct ipc_client_hmd *ich = - U_DEVICE_ALLOCATE(struct ipc_client_hmd, flags, 0, 0); + enum u_device_alloc_flags flags = (enum u_device_alloc_flags)(U_DEVICE_ALLOC_HMD); + struct ipc_client_hmd *ich = U_DEVICE_ALLOCATE(struct ipc_client_hmd, flags, 0, 0); ich->ipc_c = ipc_c; ich->device_id = device_id; ich->base.update_inputs = ipc_client_hmd_update_inputs; @@ -178,15 +172,11 @@ ipc_client_hmd_create(struct ipc_connection *ipc_c, // clang-foramt off ich->base.hmd->blend_mode = XRT_BLEND_MODE_OPAQUE; - ich->base.hmd->views[0].display.w_pixels = - ipc_c->ism->hmd.views[0].display.w_pixels; - ich->base.hmd->views[0].display.h_pixels = - ipc_c->ism->hmd.views[0].display.h_pixels; + ich->base.hmd->views[0].display.w_pixels = ipc_c->ism->hmd.views[0].display.w_pixels; + ich->base.hmd->views[0].display.h_pixels = ipc_c->ism->hmd.views[0].display.h_pixels; ich->base.hmd->views[0].fov = ipc_c->ism->hmd.views[0].fov; - ich->base.hmd->views[1].display.w_pixels = - ipc_c->ism->hmd.views[1].display.w_pixels; - ich->base.hmd->views[1].display.h_pixels = - ipc_c->ism->hmd.views[1].display.h_pixels; + ich->base.hmd->views[1].display.w_pixels = ipc_c->ism->hmd.views[1].display.w_pixels; + ich->base.hmd->views[1].display.h_pixels = ipc_c->ism->hmd.views[1].display.h_pixels; ich->base.hmd->views[1].fov = ipc_c->ism->hmd.views[1].fov; // clang-foramt on @@ -197,10 +187,8 @@ ipc_client_hmd_create(struct ipc_connection *ipc_c, u_var_add_root(ich, ich->base.str, true); u_var_add_ro_u32(ich, &ich->device_id, "device_id"); - ich->base.orientation_tracking_supported = - isdev->orientation_tracking_supported; - ich->base.position_tracking_supported = - isdev->position_tracking_supported; + ich->base.orientation_tracking_supported = isdev->orientation_tracking_supported; + ich->base.position_tracking_supported = isdev->position_tracking_supported; ich->base.device_type = isdev->device_type; ich->base.hand_tracking_supported = isdev->hand_tracking_supported; diff --git a/src/xrt/ipc/client/ipc_client_instance.c b/src/xrt/ipc/client/ipc_client_instance.c index 7ddd5ae9d..7089c434d 100644 --- a/src/xrt/ipc/client/ipc_client_instance.c +++ b/src/xrt/ipc/client/ipc_client_instance.c @@ -79,8 +79,7 @@ ipc_connect(struct ipc_connection *ipc_c) { ipc_c->ll = debug_get_log_option_ipc_log(); - ipc_c->ica = ipc_client_android_create(android_globals_get_vm(), - android_globals_get_activity()); + ipc_c->ica = ipc_client_android_create(android_globals_get_vm(), android_globals_get_activity()); if (ipc_c->ica == NULL) { IPC_ERROR(ipc_c, "Client create error!"); @@ -145,9 +144,7 @@ ipc_connect(struct ipc_connection *ipc_c) */ static int -ipc_client_instance_select(struct xrt_instance *xinst, - struct xrt_device **xdevs, - size_t num_xdevs) +ipc_client_instance_select(struct xrt_instance *xinst, struct xrt_device **xdevs, size_t num_xdevs) { struct ipc_client_instance *ii = ipc_client_instance(xinst); @@ -164,10 +161,9 @@ ipc_client_instance_select(struct xrt_instance *xinst, } static int -ipc_client_instance_create_native_compositor( - struct xrt_instance *xinst, - struct xrt_device *xdev, - struct xrt_compositor_native **out_xcn) +ipc_client_instance_create_native_compositor(struct xrt_instance *xinst, + struct xrt_device *xdev, + struct xrt_compositor_native **out_xcn) { struct ipc_client_instance *ii = ipc_client_instance(xinst); struct xrt_compositor_native *xcn = NULL; @@ -190,8 +186,7 @@ ipc_client_instance_create_native_compositor( } static int -ipc_client_instance_get_prober(struct xrt_instance *xinst, - struct xrt_prober **out_xp) +ipc_client_instance_get_prober(struct xrt_instance *xinst, struct xrt_prober **out_xp) { *out_xp = NULL; @@ -235,14 +230,11 @@ ipc_client_instance_destroy(struct xrt_instance *xinst) * @public @memberof ipc_instance */ int -ipc_instance_create(struct xrt_instance_info *i_info, - struct xrt_instance **out_xinst) +ipc_instance_create(struct xrt_instance_info *i_info, struct xrt_instance **out_xinst) { - struct ipc_client_instance *ii = - U_TYPED_CALLOC(struct ipc_client_instance); + struct ipc_client_instance *ii = U_TYPED_CALLOC(struct ipc_client_instance); ii->base.select = ipc_client_instance_select; - ii->base.create_native_compositor = - ipc_client_instance_create_native_compositor; + ii->base.create_native_compositor = ipc_client_instance_create_native_compositor; ii->base.get_prober = ipc_client_instance_get_prober; ii->base.destroy = ipc_client_instance_destroy; @@ -251,25 +243,23 @@ ipc_instance_create(struct xrt_instance_info *i_info, ii->ipc_c.ism_handle = XRT_SHMEM_HANDLE_INVALID; if (!ipc_connect(&ii->ipc_c)) { - IPC_ERROR( - (&ii->ipc_c), - "Failed to connect to monado service process\n\n" - "###\n" - "#\n" - "# Please make sure that the service process is running\n" - "#\n" - "# It is called \"monado-service\"\n" - "# For builds it's located " - "\"build-dir/src/xrt/targets/service/monado-service\"\n" - "#\n" - "###\n"); + IPC_ERROR((&ii->ipc_c), + "Failed to connect to monado service process\n\n" + "###\n" + "#\n" + "# Please make sure that the service process is running\n" + "#\n" + "# It is called \"monado-service\"\n" + "# For builds it's located " + "\"build-dir/src/xrt/targets/service/monado-service\"\n" + "#\n" + "###\n"); free(ii); return -1; } // get our xdev shm from the server and mmap it - xrt_result_t r = - ipc_call_instance_get_shm_fd(&ii->ipc_c, &ii->ipc_c.ism_handle, 1); + xrt_result_t r = ipc_call_instance_get_shm_fd(&ii->ipc_c, &ii->ipc_c.ism_handle, 1); if (r != XRT_SUCCESS) { IPC_ERROR((&ii->ipc_c), "Failed to retrieve shm fd"); free(ii); @@ -291,8 +281,7 @@ ipc_instance_create(struct xrt_instance_info *i_info, const int access = PROT_READ | PROT_WRITE; const size_t size = sizeof(struct ipc_shared_memory); - ii->ipc_c.ism = - mmap(NULL, size, access, flags, ii->ipc_c.ism_handle, 0); + ii->ipc_c.ism = mmap(NULL, size, access, flags, ii->ipc_c.ism_handle, 0); if (ii->ipc_c.ism == NULL) { IPC_ERROR((&ii->ipc_c), "Failed to mmap shm "); free(ii); @@ -308,8 +297,7 @@ ipc_instance_create(struct xrt_instance_info *i_info, for (uint32_t i = 0; i < ism->num_itracks; i++) { xtrack = U_TYPED_CALLOC(struct xrt_tracking_origin); - memcpy(xtrack->name, ism->itracks[i].name, - sizeof(xtrack->name)); + memcpy(xtrack->name, ism->itracks[i].name, sizeof(xtrack->name)); xtrack->type = ism->itracks[i].type; xtrack->offset = ism->itracks[i].offset; @@ -329,11 +317,9 @@ ipc_instance_create(struct xrt_instance_info *i_info, xtrack = ii->xtracks[isdev->tracking_origin_index]; if (isdev->name == XRT_DEVICE_GENERIC_HMD) { - ii->xdevs[count++] = - ipc_client_hmd_create(&ii->ipc_c, xtrack, i); + ii->xdevs[count++] = ipc_client_hmd_create(&ii->ipc_c, xtrack, i); } else { - ii->xdevs[count++] = - ipc_client_device_create(&ii->ipc_c, xtrack, i); + ii->xdevs[count++] = ipc_client_device_create(&ii->ipc_c, xtrack, i); } } diff --git a/src/xrt/ipc/server/ipc_server_handler.c b/src/xrt/ipc/server/ipc_server_handler.c index f377efc72..213df738f 100644 --- a/src/xrt/ipc/server/ipc_server_handler.c +++ b/src/xrt/ipc/server/ipc_server_handler.c @@ -26,8 +26,7 @@ */ static xrt_result_t -validate_swapchain_state(volatile struct ipc_client_state *ics, - uint32_t *out_index) +validate_swapchain_state(volatile struct ipc_client_state *ics, uint32_t *out_index) { // Our handle is just the index for now. uint32_t index = 0; @@ -81,8 +80,7 @@ ipc_handle_instance_get_shm_fd(volatile struct ipc_client_state *ics, return XRT_SUCCESS; } xrt_result_t -ipc_handle_session_create(volatile struct ipc_client_state *ics, - const struct xrt_session_prepare_info *xspi) +ipc_handle_session_create(volatile struct ipc_client_state *ics, const struct xrt_session_prepare_info *xspi) { ics->client_state.session_active = false; ics->client_state.session_overlay = false; @@ -114,8 +112,7 @@ ipc_handle_session_end(volatile struct ipc_client_state *ics) } xrt_result_t -ipc_handle_compositor_get_info(volatile struct ipc_client_state *ics, - struct xrt_compositor_info *out_info) +ipc_handle_compositor_get_info(volatile struct ipc_client_state *ics, struct xrt_compositor_info *out_info) { *out_info = ics->xc->info; @@ -132,8 +129,7 @@ ipc_handle_compositor_wait_frame(volatile struct ipc_client_state *ics, { os_mutex_lock(&ics->server->global_state_lock); - u_rt_helper_predict((struct u_rt_helper *)&ics->urth, out_frame_id, - predicted_display_time, wake_up_time, + u_rt_helper_predict((struct u_rt_helper *)&ics->urth, out_frame_id, predicted_display_time, wake_up_time, predicted_display_period, min_display_period); os_mutex_unlock(&ics->server->global_state_lock); @@ -145,8 +141,7 @@ ipc_handle_compositor_wait_frame(volatile struct ipc_client_state *ics, } xrt_result_t -ipc_handle_compositor_wait_woke(volatile struct ipc_client_state *ics, - int64_t frame_id) +ipc_handle_compositor_wait_woke(volatile struct ipc_client_state *ics, int64_t frame_id) { os_mutex_lock(&ics->server->global_state_lock); @@ -158,8 +153,7 @@ ipc_handle_compositor_wait_woke(volatile struct ipc_client_state *ics, } xrt_result_t -ipc_handle_compositor_begin_frame(volatile struct ipc_client_state *ics, - int64_t frame_id) +ipc_handle_compositor_begin_frame(volatile struct ipc_client_state *ics, int64_t frame_id) { os_mutex_lock(&ics->server->global_state_lock); @@ -171,8 +165,7 @@ ipc_handle_compositor_begin_frame(volatile struct ipc_client_state *ics, } xrt_result_t -ipc_handle_compositor_discard_frame(volatile struct ipc_client_state *ics, - int64_t frame_id) +ipc_handle_compositor_discard_frame(volatile struct ipc_client_state *ics, int64_t frame_id) { os_mutex_lock(&ics->server->global_state_lock); @@ -211,8 +204,7 @@ ipc_handle_compositor_layer_sync(volatile struct ipc_client_state *ics, os_mutex_lock(&ics->server->global_state_lock); - *out_free_slot_id = - (ics->server->current_slot_index + 1) % IPC_MAX_SLOTS; + *out_free_slot_id = (ics->server->current_slot_index + 1) % IPC_MAX_SLOTS; ics->server->current_slot_index = *out_free_slot_id; // Also protected by the global lock. @@ -224,8 +216,7 @@ ipc_handle_compositor_layer_sync(volatile struct ipc_client_state *ics, } xrt_result_t -ipc_handle_compositor_poll_events(volatile struct ipc_client_state *ics, - union xrt_compositor_event *out_xce) +ipc_handle_compositor_poll_events(volatile struct ipc_client_state *ics, union xrt_compositor_event *out_xce) { uint64_t l_timestamp = UINT64_MAX; volatile struct ipc_queued_event *event_to_send = NULL; @@ -275,8 +266,7 @@ ipc_handle_system_get_client_info(volatile struct ipc_client_state *_ics, } xrt_result_t -ipc_handle_system_set_client_info(volatile struct ipc_client_state *ics, - struct ipc_app_state *client_desc) +ipc_handle_system_set_client_info(volatile struct ipc_client_state *ics, struct ipc_app_state *client_desc) { ics->client_state.info = client_desc->info; ics->client_state.pid = client_desc->pid; @@ -284,8 +274,7 @@ ipc_handle_system_set_client_info(volatile struct ipc_client_state *ics, } xrt_result_t -ipc_handle_system_get_clients(volatile struct ipc_client_state *_ics, - struct ipc_client_list *list) +ipc_handle_system_get_clients(volatile struct ipc_client_state *_ics, struct ipc_client_list *list) { for (uint32_t i = 0; i < IPC_MAX_CLIENTS; i++) { list->ids[i] = _ics->server->threads[i].ics.server_thread_index; @@ -294,31 +283,25 @@ ipc_handle_system_get_clients(volatile struct ipc_client_state *_ics, } xrt_result_t -ipc_handle_system_set_primary_client(volatile struct ipc_client_state *ics, - uint32_t client_id) +ipc_handle_system_set_primary_client(volatile struct ipc_client_state *ics, uint32_t client_id) { ics->server->active_client_index = client_id; - IPC_INFO(ics->server, "system setting active client to %d\n", - client_id); + IPC_INFO(ics->server, "system setting active client to %d\n", client_id); update_server_state(ics->server); return XRT_SUCCESS; } xrt_result_t -ipc_handle_system_set_focused_client(volatile struct ipc_client_state *ics, - uint32_t client_id) +ipc_handle_system_set_focused_client(volatile struct ipc_client_state *ics, uint32_t client_id) { - IPC_INFO(ics->server, - "UNIMPLEMENTED: system setting focused client to %d\n", - client_id); + IPC_INFO(ics->server, "UNIMPLEMENTED: system setting focused client to %d\n", client_id); return XRT_SUCCESS; } xrt_result_t -ipc_handle_system_toggle_io_client(volatile struct ipc_client_state *_ics, - uint32_t client_id) +ipc_handle_system_toggle_io_client(volatile struct ipc_client_state *_ics, uint32_t client_id) { volatile struct ipc_client_state *ics = NULL; @@ -338,8 +321,7 @@ ipc_handle_system_toggle_io_client(volatile struct ipc_client_state *_ics, } xrt_result_t -ipc_handle_system_toggle_io_device(volatile struct ipc_client_state *ics, - uint32_t device_id) +ipc_handle_system_toggle_io_device(volatile struct ipc_client_state *ics, uint32_t device_id) { if (device_id >= IPC_MAX_DEVICES) { return XRT_ERROR_IPC_FAILURE; @@ -374,8 +356,7 @@ ipc_handle_swapchain_create(volatile struct ipc_client_state *ics, struct xrt_swapchain *xsc = NULL; xret = xrt_comp_create_swapchain(ics->xc, info, &xsc); if (xret != XRT_SUCCESS) { - IPC_ERROR(ics->server, - "ERROR: xrt_comp_create_swapchain failed!\n"); + IPC_ERROR(ics->server, "ERROR: xrt_comp_create_swapchain failed!\n"); return xret; } @@ -430,8 +411,7 @@ ipc_handle_swapchain_import(volatile struct ipc_client_state *ics, // create the swapchain struct xrt_swapchain *xsc = NULL; - xret = - xrt_comp_import_swapchain(ics->xc, info, xins, num_handles, &xsc); + xret = xrt_comp_import_swapchain(ics->xc, info, xins, num_handles, &xsc); if (xret != XRT_SUCCESS) { return xret; } @@ -448,10 +428,7 @@ ipc_handle_swapchain_import(volatile struct ipc_client_state *ics, } xrt_result_t -ipc_handle_swapchain_wait_image(volatile struct ipc_client_state *ics, - uint32_t id, - uint64_t timeout, - uint32_t index) +ipc_handle_swapchain_wait_image(volatile struct ipc_client_state *ics, uint32_t id, uint64_t timeout, uint32_t index) { //! @todo Look up the index. uint32_t sc_index = id; @@ -463,9 +440,7 @@ ipc_handle_swapchain_wait_image(volatile struct ipc_client_state *ics, } xrt_result_t -ipc_handle_swapchain_acquire_image(volatile struct ipc_client_state *ics, - uint32_t id, - uint32_t *out_index) +ipc_handle_swapchain_acquire_image(volatile struct ipc_client_state *ics, uint32_t id, uint32_t *out_index) { //! @todo Look up the index. uint32_t sc_index = id; @@ -477,9 +452,7 @@ ipc_handle_swapchain_acquire_image(volatile struct ipc_client_state *ics, } xrt_result_t -ipc_handle_swapchain_release_image(volatile struct ipc_client_state *ics, - uint32_t id, - uint32_t index) +ipc_handle_swapchain_release_image(volatile struct ipc_client_state *ics, uint32_t id, uint32_t index) { //! @todo Look up the index. uint32_t sc_index = id; @@ -503,8 +476,7 @@ ipc_handle_swapchain_destroy(volatile struct ipc_client_state *ics, uint32_t id) } xrt_result_t -ipc_handle_device_update_input(volatile struct ipc_client_state *ics, - uint32_t id) +ipc_handle_device_update_input(volatile struct ipc_client_state *ics, uint32_t id) { // To make the code a bit more readable. uint32_t device_id = id; @@ -542,9 +514,7 @@ ipc_handle_device_update_input(volatile struct ipc_client_state *ics, } static struct xrt_input * -find_input(volatile struct ipc_client_state *ics, - uint32_t device_id, - enum xrt_input_name name) +find_input(volatile struct ipc_client_state *ics, uint32_t device_id, enum xrt_input_name name) { struct ipc_shared_memory *ism = ics->server->ism; struct ipc_shared_device *isdev = &ism->isdevs[device_id]; @@ -579,8 +549,7 @@ ipc_handle_device_get_tracked_pose(volatile struct ipc_client_state *ics, } // Special case the headpose. - bool disabled = (!isdev->io_active || !ics->io_active) && - name != XRT_INPUT_GENERIC_HEAD_POSE; + bool disabled = (!isdev->io_active || !ics->io_active) && name != XRT_INPUT_GENERIC_HEAD_POSE; bool active_on_client = input->active; // We have been disabled but the client hasn't called update. diff --git a/src/xrt/ipc/server/ipc_server_per_client_thread.c b/src/xrt/ipc/server/ipc_server_per_client_thread.c index 79fb9a95b..bcaae88b8 100644 --- a/src/xrt/ipc/server/ipc_server_per_client_thread.c +++ b/src/xrt/ipc/server/ipc_server_per_client_thread.c @@ -50,8 +50,7 @@ setup_epoll(volatile struct ipc_client_state *ics) ev.data.fd = listen_socket; ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_socket, &ev); if (ret < 0) { - IPC_ERROR(ics->server, "epoll_ctl(listen_socket) failed '%i'\n", - ret); + IPC_ERROR(ics->server, "epoll_ctl(listen_socket) failed '%i'\n", ret); return ret; } @@ -88,10 +87,7 @@ client_loop(volatile struct ipc_client_state *ics) // We use epoll here to be able to timeout. int ret = epoll_wait(epoll_fd, &event, 1, half_a_second_ms); if (ret < 0) { - IPC_ERROR( - ics->server, - "Failed epoll_wait '%i', disconnecting client.\n", - ret); + IPC_ERROR(ics->server, "Failed epoll_wait '%i', disconnecting client.\n", ret); break; } @@ -110,9 +106,7 @@ client_loop(volatile struct ipc_client_state *ics) //! @todo replace this call ssize_t len = recv(ics->imc.socket_fd, &buf, IPC_BUF_SIZE, 0); if (len < 4) { - IPC_ERROR( - ics->server, - "Invalid packet received, disconnecting client.\n"); + IPC_ERROR(ics->server, "Invalid packet received, disconnecting client.\n"); break; } @@ -120,9 +114,7 @@ client_loop(volatile struct ipc_client_state *ics) ipc_command_t *ipc_command = (uint32_t *)buf; xrt_result_t result = ipc_dispatch(ics, ipc_command); if (result != XRT_SUCCESS) { - IPC_ERROR( - ics->server, - "During packet handling, disconnecting client.\n"); + IPC_ERROR(ics->server, "During packet handling, disconnecting client.\n"); break; } } @@ -140,8 +132,7 @@ client_loop(volatile struct ipc_client_state *ics) ics->num_swapchains = 0; - ics->server->threads[ics->server_thread_index].state = - IPC_THREAD_STOPPING; + ics->server->threads[ics->server_thread_index].state = IPC_THREAD_STOPPING; ics->server_thread_index = -1; memset((void *)&ics->client_state, 0, sizeof(struct ipc_app_state)); @@ -149,8 +140,7 @@ client_loop(volatile struct ipc_client_state *ics) ics->rendering_state = false; ics->render_state.num_layers = 0; for (uint32_t i = 0; i < ARRAY_SIZE(ics->render_state.layers); ++i) { - volatile struct ipc_layer_entry *rl = - &ics->render_state.layers[i]; + volatile struct ipc_layer_entry *rl = &ics->render_state.layers[i]; rl->swapchain_ids[0] = 0; rl->swapchain_ids[1] = 0; diff --git a/src/xrt/ipc/server/ipc_server_process.c b/src/xrt/ipc/server/ipc_server_process.c index c005eabe8..3bb003543 100644 --- a/src/xrt/ipc/server/ipc_server_process.c +++ b/src/xrt/ipc/server/ipc_server_process.c @@ -223,8 +223,7 @@ init_shm(struct ipc_server *s) // servers memory. assert(i < IPC_SHARED_MAX_DEVICES); - struct ipc_shared_tracking_origin *itrack = - &ism->itracks[count++]; + struct ipc_shared_tracking_origin *itrack = &ism->itracks[count++]; memcpy(itrack->name, xtrack->name, sizeof(itrack->name)); itrack->type = xtrack->type; itrack->offset = xtrack->offset; @@ -250,24 +249,18 @@ init_shm(struct ipc_server *s) isdev->name = xdev->name; memcpy(isdev->str, xdev->str, sizeof(isdev->str)); - isdev->orientation_tracking_supported = - xdev->orientation_tracking_supported; - isdev->position_tracking_supported = - xdev->position_tracking_supported; + isdev->orientation_tracking_supported = xdev->orientation_tracking_supported; + isdev->position_tracking_supported = xdev->position_tracking_supported; isdev->device_type = xdev->device_type; isdev->hand_tracking_supported = xdev->hand_tracking_supported; // Is this a HMD? if (xdev->hmd != NULL) { - ism->hmd.views[0].display.w_pixels = - xdev->hmd->views[0].display.w_pixels; - ism->hmd.views[0].display.h_pixels = - xdev->hmd->views[0].display.h_pixels; + ism->hmd.views[0].display.w_pixels = xdev->hmd->views[0].display.w_pixels; + ism->hmd.views[0].display.h_pixels = xdev->hmd->views[0].display.h_pixels; ism->hmd.views[0].fov = xdev->hmd->views[0].fov; - ism->hmd.views[1].display.w_pixels = - xdev->hmd->views[1].display.w_pixels; - ism->hmd.views[1].display.h_pixels = - xdev->hmd->views[1].display.h_pixels; + ism->hmd.views[1].display.w_pixels = xdev->hmd->views[1].display.w_pixels; + ism->hmd.views[1].display.h_pixels = xdev->hmd->views[1].display.h_pixels; ism->hmd.views[1].fov = xdev->hmd->views[1].fov; } @@ -290,15 +283,13 @@ init_shm(struct ipc_server *s) // Bindings size_t binding_start = binding_index; for (size_t k = 0; k < xdev->num_binding_profiles; k++) { - handle_binding(ism, &xdev->binding_profiles[k], - &ism->binding_profiles[binding_index++], + handle_binding(ism, &xdev->binding_profiles[k], &ism->binding_profiles[binding_index++], &input_pair_index, &output_pair_index); } // Setup the 'offsets' and number of bindings. if (binding_start != binding_index) { - isdev->num_binding_profiles = - binding_index - binding_start; + isdev->num_binding_profiles = binding_index - binding_start; isdev->first_binding_profile_index = binding_start; } @@ -555,8 +546,7 @@ init_all(struct ipc_server *s) return -1; } - ret = xrt_instance_create_native_compositor(s->xinst, s->idevs[0].xdev, - &s->xcn); + ret = xrt_instance_create_native_compositor(s->xinst, s->idevs[0].xdev, &s->xcn); if (ret < 0) { teardown_all(s); return ret; @@ -668,8 +658,7 @@ find_event_slot(volatile struct ipc_client_state *ics) } static void -transition_overlay_visibility(volatile struct ipc_client_state *ics, - bool visible) +transition_overlay_visibility(volatile struct ipc_client_state *ics, bool visible) { uint32_t event_slot = find_event_slot(ics); uint64_t timestamp = os_monotonic_get_ns(); @@ -755,8 +744,7 @@ _update_projection_layer_depth(struct xrt_compositor *xc, struct xrt_swapchain *l_d_xcs = ics->xscs[l_d_xsci]; struct xrt_swapchain *r_d_xcs = ics->xscs[r_d_xsci]; - if (l_xcs == NULL || r_xcs == NULL || l_d_xcs == NULL || - r_d_xcs == NULL) { + if (l_xcs == NULL || r_xcs == NULL || l_d_xcs == NULL || r_d_xcs == NULL) { U_LOG_E("Invalid swap chain for projection layer."); return false; } @@ -769,8 +757,7 @@ _update_projection_layer_depth(struct xrt_compositor *xc, // Cast away volatile. struct xrt_layer_data *data = (struct xrt_layer_data *)&layer->data; - xrt_comp_layer_stereo_projection_depth(xc, xdev, l_xcs, r_xcs, l_d_xcs, - r_d_xcs, data); + xrt_comp_layer_stereo_projection_depth(xc, xdev, l_xcs, r_xcs, l_d_xcs, r_d_xcs, data); return true; } @@ -947,8 +934,7 @@ _update_layers(struct ipc_server *s, struct xrt_compositor *xc) } // sort the stack array - qsort(z_data, IPC_MAX_CLIENTS, sizeof(struct _z_sort_data), - _overlay_sort_func); + qsort(z_data, IPC_MAX_CLIENTS, sizeof(struct _z_sort_data), _overlay_sort_func); // render the layer stack for (uint32_t i = 0; i < IPC_MAX_CLIENTS; i++) { @@ -957,23 +943,19 @@ _update_layers(struct ipc_server *s, struct xrt_compositor *xc) continue; } - volatile struct ipc_client_state *ics = - &s->threads[zd->index].ics; + volatile struct ipc_client_state *ics = &s->threads[zd->index].ics; for (uint32_t j = 0; j < ics->render_state.num_layers; j++) { - volatile struct ipc_layer_entry *layer = - &ics->render_state.layers[j]; + volatile struct ipc_layer_entry *layer = &ics->render_state.layers[j]; switch (layer->data.type) { case XRT_LAYER_STEREO_PROJECTION: - if (!_update_projection_layer(xc, ics, layer, - i)) { + if (!_update_projection_layer(xc, ics, layer, i)) { return false; } break; case XRT_LAYER_STEREO_PROJECTION_DEPTH: - if (!_update_projection_layer_depth(xc, ics, - layer, i)) { + if (!_update_projection_layer_depth(xc, ics, layer, i)) { return false; } break; @@ -988,27 +970,21 @@ _update_layers(struct ipc_server *s, struct xrt_compositor *xc) } break; case XRT_LAYER_CYLINDER: - if (!_update_cylinder_layer(xc, ics, layer, - i)) { + if (!_update_cylinder_layer(xc, ics, layer, i)) { return false; } break; case XRT_LAYER_EQUIRECT1: - if (!_update_equirect1_layer(xc, ics, layer, - i)) { + if (!_update_equirect1_layer(xc, ics, layer, i)) { return false; } break; case XRT_LAYER_EQUIRECT2: - if (!_update_equirect2_layer(xc, ics, layer, - i)) { + if (!_update_equirect2_layer(xc, ics, layer, i)) { return false; } break; - default: - U_LOG_E("Unhandled layer type '%i'!", - layer->data.type); - break; + default: U_LOG_E("Unhandled layer type '%i'!", layer->data.type); break; } } } @@ -1031,8 +1007,7 @@ main_loop(struct ipc_server *s) uint64_t predicted_display_time; uint64_t predicted_display_period; - xrt_comp_wait_frame(xc, &frame_id, &predicted_display_time, - &predicted_display_period); + xrt_comp_wait_frame(xc, &frame_id, &predicted_display_time, &predicted_display_period); uint64_t now = os_monotonic_get_ns(); uint64_t diff = predicted_display_time - now; @@ -1041,10 +1016,8 @@ main_loop(struct ipc_server *s) // Broadcast the new timing information to the helpers. for (size_t i = 0; i < ARRAY_SIZE(s->threads); i++) { - u_rt_helper_new_sample( - (struct u_rt_helper *)&s->threads[i].ics.urth, - predicted_display_time, diff, - predicted_display_period); + u_rt_helper_new_sample((struct u_rt_helper *)&s->threads[i].ics.urth, predicted_display_time, + diff, predicted_display_period); } os_mutex_unlock(&s->global_state_lock); @@ -1055,8 +1028,7 @@ main_loop(struct ipc_server *s) _update_layers(s, xc); - xrt_comp_layer_commit(xc, frame_id, - XRT_GRAPHICS_SYNC_HANDLE_INVALID); + xrt_comp_layer_commit(xc, frame_id, XRT_GRAPHICS_SYNC_HANDLE_INVALID); #ifndef XRT_OS_ANDROID // Check polling last, so we know we have valid timing data. @@ -1069,9 +1041,7 @@ main_loop(struct ipc_server *s) static void -handle_overlay_client_events(volatile struct ipc_client_state *ics, - int active_id, - int prev_active_id) +handle_overlay_client_events(volatile struct ipc_client_state *ics, int active_id, int prev_active_id) { // this is an overlay session. if (ics->client_state.session_overlay) { @@ -1095,9 +1065,7 @@ handle_overlay_client_events(volatile struct ipc_client_state *ics, } static void -handle_focused_client_events(volatile struct ipc_client_state *ics, - int active_id, - int prev_active_id) +handle_focused_client_events(volatile struct ipc_client_state *ics, int active_id, int prev_active_id) { // if our prev active id is -1 and our cur active id is -1, we @@ -1176,11 +1144,9 @@ update_server_state(struct ipc_server *s) if (s->active_client_index >= 0) { - volatile struct ipc_client_state *ics = - &s->threads[s->active_client_index].ics; + volatile struct ipc_client_state *ics = &s->threads[s->active_client_index].ics; - if (ics->client_state.session_active && - s->active_client_index == s->last_active_client_index) { + if (ics->client_state.session_active && s->active_client_index == s->last_active_client_index) { os_mutex_unlock(&s->global_state_lock); return; } @@ -1201,8 +1167,7 @@ update_server_state(struct ipc_server *s) // do we have a fallback application? for (uint32_t i = 0; i < IPC_MAX_CLIENTS; i++) { volatile struct ipc_client_state *ics = &s->threads[i].ics; - if (ics->client_state.session_overlay == false && - ics->server_thread_index >= 0 && + if (ics->client_state.session_overlay == false && ics->server_thread_index >= 0 && ics->client_state.session_active) { fallback_active_application = i; set_idle = false; @@ -1212,10 +1177,8 @@ update_server_state(struct ipc_server *s) // if our currently-set active primary application is not // actually active/displayable, use the fallback application // instead. - volatile struct ipc_client_state *ics = - &s->threads[s->active_client_index].ics; - if (!(ics->client_state.session_overlay == false && - s->active_client_index >= 0 && + volatile struct ipc_client_state *ics = &s->threads[s->active_client_index].ics; + if (!(ics->client_state.session_overlay == false && s->active_client_index >= 0 && ics->client_state.session_active)) { s->active_client_index = fallback_active_application; } @@ -1232,13 +1195,9 @@ update_server_state(struct ipc_server *s) volatile struct ipc_client_state *ics = &s->threads[i].ics; if (ics->server_thread_index >= 0) { - handle_focused_client_events( - ics, s->active_client_index, - s->last_active_client_index); + handle_focused_client_events(ics, s->active_client_index, s->last_active_client_index); - handle_overlay_client_events( - ics, s->active_client_index, - s->last_active_client_index); + handle_overlay_client_events(ics, s->active_client_index, s->last_active_client_index); } } diff --git a/src/xrt/ipc/shared/ipc_protocol.h b/src/xrt/ipc/shared/ipc_protocol.h index a5559397d..c4c365d3d 100644 --- a/src/xrt/ipc/shared/ipc_protocol.h +++ b/src/xrt/ipc/shared/ipc_protocol.h @@ -230,8 +230,7 @@ struct ipc_shared_memory struct xrt_output outputs[IPC_SHARED_MAX_OUTPUTS]; - struct ipc_shared_binding_profile - binding_profiles[IPC_SHARED_MAX_BINDINGS]; + struct ipc_shared_binding_profile binding_profiles[IPC_SHARED_MAX_BINDINGS]; struct xrt_binding_input_pair input_pairs[IPC_SHARED_MAX_INPUTS]; struct xrt_binding_output_pair output_pairs[IPC_SHARED_MAX_OUTPUTS]; diff --git a/src/xrt/ipc/shared/ipc_shmem.c b/src/xrt/ipc/shared/ipc_shmem.c index e92aafaa7..f8177d126 100644 --- a/src/xrt/ipc/shared/ipc_shmem.c +++ b/src/xrt/ipc/shared/ipc_shmem.c @@ -57,8 +57,7 @@ xrt_result_t ipc_shmem_create(size_t size, xrt_shmem_handle_t *out_handle, void **out_map) { *out_handle = -1; - int fd = - shm_open(MONADO_SHMEM_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); + int fd = shm_open(MONADO_SHMEM_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd < 0) { return XRT_ERROR_IPC_FAILURE; } diff --git a/src/xrt/ipc/shared/ipc_utils.c b/src/xrt/ipc/shared/ipc_utils.c index d8cfcd397..88138b219 100644 --- a/src/xrt/ipc/shared/ipc_utils.c +++ b/src/xrt/ipc/shared/ipc_utils.c @@ -65,11 +65,10 @@ ipc_send(struct ipc_message_channel *imc, const void *data, size_t size) ssize_t ret = sendmsg(imc->socket_fd, &msg, MSG_NOSIGNAL); if (ret < 0) { int code = errno; - IPC_ERROR( - imc, - "ERROR: Sending plain message on socket %d failed with " - "error: '%i' '%s'", - (int)imc->socket_fd, code, strerror(code)); + IPC_ERROR(imc, + "ERROR: Sending plain message on socket %d failed with " + "error: '%i' '%s'", + (int)imc->socket_fd, code, strerror(code)); return XRT_ERROR_IPC_FAILURE; } @@ -97,19 +96,15 @@ ipc_receive(struct ipc_message_channel *imc, void *out_data, size_t size) if (len < 0) { int code = errno; - IPC_ERROR( - imc, - "ERROR: Receiving plain message on socket %d failed with " - "error: '%i' '%s'", - (int)imc->socket_fd, code, strerror(code)); + IPC_ERROR(imc, + "ERROR: Receiving plain message on socket %d failed with " + "error: '%i' '%s'", + (int)imc->socket_fd, code, strerror(code)); return XRT_ERROR_IPC_FAILURE; } if ((size_t)len != size) { - IPC_ERROR( - imc, - "recvmsg failed with error: wrong size %i, expected %i", - (int)len, (int)size); + IPC_ERROR(imc, "recvmsg failed with error: wrong size %i, expected %i", (int)len, (int)size); return XRT_ERROR_IPC_FAILURE; } @@ -122,11 +117,7 @@ union imcontrol_buf { }; xrt_result_t -ipc_receive_fds(struct ipc_message_channel *imc, - void *out_data, - size_t size, - int *out_handles, - uint32_t num_handles) +ipc_receive_fds(struct ipc_message_channel *imc, void *out_data, size_t size, int *out_handles, uint32_t num_handles) { assert(imc != NULL); assert(out_data != NULL); @@ -150,8 +141,7 @@ ipc_receive_fds(struct ipc_message_channel *imc, ssize_t len = recvmsg(imc->socket_fd, &msg, MSG_NOSIGNAL); if (len < 0) { - IPC_ERROR(imc, "recvmsg failed with error: %s", - strerror(errno)); + IPC_ERROR(imc, "recvmsg failed with error: %s", strerror(errno)); return XRT_ERROR_IPC_FAILURE; } @@ -170,11 +160,7 @@ ipc_receive_fds(struct ipc_message_channel *imc, } xrt_result_t -ipc_send_fds(struct ipc_message_channel *imc, - const void *data, - size_t size, - const int *handles, - uint32_t num_handles) +ipc_send_fds(struct ipc_message_channel *imc, const void *data, size_t size, const int *handles, uint32_t num_handles) { assert(imc != NULL); assert(data != NULL); @@ -207,11 +193,10 @@ ipc_send_fds(struct ipc_message_channel *imc, ssize_t ret = sendmsg(imc->socket_fd, &msg, MSG_NOSIGNAL); if (ret < 0) { - IPC_ERROR( - imc, - "ERROR: sending %d FDs on socket %d failed with error: " - "'%i' '%s'", - (int)num_handles, imc->socket_fd, errno, strerror(errno)); + IPC_ERROR(imc, + "ERROR: sending %d FDs on socket %d failed with error: " + "'%i' '%s'", + (int)num_handles, imc->socket_fd, errno, strerror(errno)); for (uint32_t i = 0; i < num_handles; i++) { IPC_ERROR(imc, "\tfd #%i: %i", i, handles[i]); } @@ -221,11 +206,8 @@ ipc_send_fds(struct ipc_message_channel *imc, } xrt_result_t -ipc_receive_handles_shmem(struct ipc_message_channel *imc, - void *out_data, - size_t size, - xrt_shmem_handle_t *out_handles, - uint32_t num_handles) +ipc_receive_handles_shmem( + struct ipc_message_channel *imc, void *out_data, size_t size, xrt_shmem_handle_t *out_handles, uint32_t num_handles) { return ipc_receive_fds(imc, out_data, size, out_handles, num_handles); } @@ -265,8 +247,7 @@ ipc_receive_handles_graphics_buffer(struct ipc_message_channel *imc, } bool failed = false; for (uint32_t i = 0; i < num_handles; ++i) { - int err = AHardwareBuffer_recvHandleFromUnixSocket( - imc->socket_fd, &(out_handles[i])); + int err = AHardwareBuffer_recvHandleFromUnixSocket(imc->socket_fd, &(out_handles[i])); if (err != 0) { failed = true; } @@ -288,8 +269,7 @@ ipc_send_handles_graphics_buffer(struct ipc_message_channel *imc, } bool failed = false; for (uint32_t i = 0; i < num_handles; ++i) { - int err = AHardwareBuffer_sendHandleToUnixSocket( - handles[i], imc->socket_fd); + int err = AHardwareBuffer_sendHandleToUnixSocket(handles[i], imc->socket_fd); if (err != 0) { failed = true; } @@ -350,8 +330,7 @@ ipc_receive_handles_graphics_sync(struct ipc_message_channel *imc, if (num_handles == 0) { return ipc_receive(imc, out_data, size); } else { - return ipc_receive_fds(imc, out_data, size, out_handles, - num_handles); + return ipc_receive_fds(imc, out_data, size, out_handles, num_handles); } } diff --git a/src/xrt/ipc/shared/ipc_utils.h b/src/xrt/ipc/shared/ipc_utils.h index e2aa24da3..49a13f9ba 100644 --- a/src/xrt/ipc/shared/ipc_utils.h +++ b/src/xrt/ipc/shared/ipc_utils.h @@ -92,11 +92,7 @@ ipc_receive(struct ipc_message_channel *imc, void *out_data, size_t size); * @public @memberof ipc_message_channel */ xrt_result_t -ipc_receive_fds(struct ipc_message_channel *imc, - void *out_data, - size_t size, - int *out_handles, - uint32_t num_handles); +ipc_receive_fds(struct ipc_message_channel *imc, void *out_data, size_t size, int *out_handles, uint32_t num_handles); /*! * Send a message along with file descriptors over the IPC channel. @@ -114,11 +110,7 @@ ipc_receive_fds(struct ipc_message_channel *imc, * @public @memberof ipc_message_channel */ xrt_result_t -ipc_send_fds(struct ipc_message_channel *imc, - const void *data, - size_t size, - const int *handles, - uint32_t num_handles); +ipc_send_fds(struct ipc_message_channel *imc, const void *data, size_t size, const int *handles, uint32_t num_handles); #endif // XRT_OS_UNIX /*! * @} diff --git a/src/xrt/state_trackers/gui/gui_common.h b/src/xrt/state_trackers/gui/gui_common.h index 51436b19b..015e3db02 100644 --- a/src/xrt/state_trackers/gui/gui_common.h +++ b/src/xrt/state_trackers/gui/gui_common.h @@ -124,9 +124,7 @@ gui_prober_teardown(struct gui_program *p); * @ingroup gui */ struct gui_ogl_texture * -gui_ogl_sink_create(const char *name, - struct xrt_frame_context *xfctx, - struct xrt_frame_sink **out_sink); +gui_ogl_sink_create(const char *name, struct xrt_frame_context *xfctx, struct xrt_frame_sink **out_sink); /*! * Update the texture to the latest received frame. diff --git a/src/xrt/state_trackers/gui/gui_ogl.c b/src/xrt/state_trackers/gui/gui_ogl.c index 4bb40fb21..cce444977 100644 --- a/src/xrt/state_trackers/gui/gui_ogl.c +++ b/src/xrt/state_trackers/gui/gui_ogl.c @@ -79,8 +79,7 @@ static void update_r8g8b8(struct gui_ogl_sink *s, GLint w, GLint h, uint8_t *data) { glBindTexture(GL_TEXTURE_2D, s->tex.id); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGB, - GL_UNSIGNED_BYTE, data); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, 0); } @@ -88,8 +87,7 @@ static void update_l8(struct gui_ogl_sink *s, GLint w, GLint h, uint8_t *data) { glBindTexture(GL_TEXTURE_2D, s->tex.id); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, - GL_UNSIGNED_BYTE, data); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, data); GLint swizzleMask[] = {GL_RED, GL_RED, GL_RED, GL_ONE}; glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); glBindTexture(GL_TEXTURE_2D, 0); @@ -140,9 +138,7 @@ gui_ogl_sink_update(struct gui_ogl_texture *tex) } struct gui_ogl_texture * -gui_ogl_sink_create(const char *name, - struct xrt_frame_context *xfctx, - struct xrt_frame_sink **out_sink) +gui_ogl_sink_create(const char *name, struct xrt_frame_context *xfctx, struct xrt_frame_sink **out_sink) { struct gui_ogl_sink *s = U_TYPED_CALLOC(struct gui_ogl_sink); int ret = 0; @@ -170,8 +166,7 @@ gui_ogl_sink_create(const char *name, GLint h = 1; struct xrt_colour_rgb_u8 pink = {255, 0, 255}; - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGB, - GL_UNSIGNED_BYTE, &pink.r); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, &pink.r); glBindTexture(GL_TEXTURE_2D, 0); diff --git a/src/xrt/state_trackers/gui/gui_scene_calibrate.c b/src/xrt/state_trackers/gui/gui_scene_calibrate.c index 128bf48ef..b14e36160 100644 --- a/src/xrt/state_trackers/gui/gui_scene_calibrate.c +++ b/src/xrt/state_trackers/gui/gui_scene_calibrate.c @@ -76,8 +76,7 @@ save_calibration(struct calibration_scene *cs) saved_header(cs); igSetNextItemWidth(115); - igInputText(".calibration", cs->filename, sizeof(cs->filename), 0, NULL, - NULL); + igInputText(".calibration", cs->filename, sizeof(cs->filename), 0, NULL, NULL); igSameLine(0.0f, 4.0f); static ImVec2 button_dims = {0, 0}; @@ -96,8 +95,7 @@ save_calibration(struct calibration_scene *cs) char tmp[sizeof(cs->filename) + 16]; snprintf(tmp, sizeof(tmp), "%s.calibration", cs->filename); - u_file_get_path_in_config_dir(tmp, cs->settings->calibration_path, - sizeof(cs->settings->calibration_path)); + u_file_get_path_in_config_dir(tmp, cs->settings->calibration_path, sizeof(cs->settings->calibration_path)); /* * @@ -111,28 +109,18 @@ save_calibration(struct calibration_scene *cs) cJSON_AddStringToObject(t, "camera_name", cs->settings->camera_name); cJSON_AddNumberToObject(t, "camera_mode", cs->settings->camera_mode); switch (cs->settings->camera_type) { - case XRT_SETTINGS_CAMERA_TYPE_REGULAR_MONO: - cJSON_AddStringToObject(t, "camera_type", "regular_mono"); - break; - case XRT_SETTINGS_CAMERA_TYPE_REGULAR_SBS: - cJSON_AddStringToObject(t, "camera_type", "regular_sbs"); - break; - case XRT_SETTINGS_CAMERA_TYPE_PS4: - cJSON_AddStringToObject(t, "camera_type", "ps4"); - break; - case XRT_SETTINGS_CAMERA_TYPE_LEAP_MOTION: - cJSON_AddStringToObject(t, "camera_type", "leap_motion"); - break; + case XRT_SETTINGS_CAMERA_TYPE_REGULAR_MONO: cJSON_AddStringToObject(t, "camera_type", "regular_mono"); break; + case XRT_SETTINGS_CAMERA_TYPE_REGULAR_SBS: cJSON_AddStringToObject(t, "camera_type", "regular_sbs"); break; + case XRT_SETTINGS_CAMERA_TYPE_PS4: cJSON_AddStringToObject(t, "camera_type", "ps4"); break; + case XRT_SETTINGS_CAMERA_TYPE_LEAP_MOTION: cJSON_AddStringToObject(t, "camera_type", "leap_motion"); break; } - cJSON_AddStringToObject(t, "calibration_path", - cs->settings->calibration_path); + cJSON_AddStringToObject(t, "calibration_path", cs->settings->calibration_path); char *str = cJSON_Print(root); U_LOG_D("%s", str); cJSON_Delete(root); - FILE *config_file = - u_file_open_file_in_config_dir("config_v0.json", "w"); + FILE *config_file = u_file_open_file_in_config_dir("config_v0.json", "w"); fprintf(config_file, "%s\n", str); fflush(config_file); fclose(config_file); @@ -197,8 +185,7 @@ render_progress(struct calibration_scene *cs) static const ImVec2 progress_dims = {150, 0}; if (cs->status.cooldown > 0) { // This progress bar intentionally counts down to 0. - float cooldown = (float)(cs->status.cooldown) / - (float)cs->params.num_cooldown_frames; + float cooldown = (float)(cs->status.cooldown) / (float)cs->params.num_cooldown_frames; igText("Move to a new position"); igProgressBar(cooldown, progress_dims, "Move to new position"); } else if (!cs->status.found) { @@ -210,22 +197,17 @@ render_progress(struct calibration_scene *cs) } else { // This progress bar counts up from zero before // capturing. - int waits_complete = - cs->params.num_wait_for - cs->status.waits_remaining; - float hold_completion = - (float)waits_complete / (float)cs->params.num_wait_for; + int waits_complete = cs->params.num_wait_for - cs->status.waits_remaining; + float hold_completion = (float)waits_complete / (float)cs->params.num_wait_for; if (cs->status.waits_remaining == 0) { igText("Capturing and processing!"); } else { - igText("Hold still! (%i/%i)", waits_complete, - cs->params.num_wait_for); + igText("Hold still! (%i/%i)", waits_complete, cs->params.num_wait_for); } igProgressBar(hold_completion, progress_dims, "Hold still!"); } - float capture_completion = ((float)cs->status.num_collected) / - (float)cs->params.num_collect_total; - igText("Overall progress: %i of %i frames captured", - cs->status.num_collected, cs->params.num_collect_total); + float capture_completion = ((float)cs->status.num_collected) / (float)cs->params.num_collect_total; + igText("Overall progress: %i of %i frames captured", cs->status.num_collected, cs->params.num_collect_total); igProgressBar(capture_completion, progress_dims, NULL); #else @@ -349,8 +331,7 @@ scene_render_select(struct gui_scene *scene, struct gui_program *p) struct xrt_frame_sink *raw = NULL; struct xrt_frame_sink *cali = NULL; - p->texs[p->num_texs++] = - gui_ogl_sink_create("Calibration", cs->xfctx, &rgb); + p->texs[p->num_texs++] = gui_ogl_sink_create("Calibration", cs->xfctx, &rgb); u_sink_create_to_r8g8b8_or_l8(cs->xfctx, rgb, &rgb); u_sink_queue_create(cs->xfctx, rgb, &rgb); @@ -358,8 +339,7 @@ scene_render_select(struct gui_scene *scene, struct gui_program *p) u_sink_create_to_r8g8b8_or_l8(cs->xfctx, raw, &raw); u_sink_queue_create(cs->xfctx, raw, &raw); - t_calibration_stereo_create(cs->xfctx, &cs->params, &cs->status, rgb, - &cali); + t_calibration_stereo_create(cs->xfctx, &cs->params, &cs->status, rgb, &cali); u_sink_split_create(cs->xfctx, raw, cali, &cali); u_sink_deinterleaver_create(cs->xfctx, cali, &cali); u_sink_queue_create(cs->xfctx, cali, &cali); @@ -369,13 +349,11 @@ scene_render_select(struct gui_scene *scene, struct gui_program *p) U_ZERO(&qp); qp.stereo_sbs = cs->params.stereo_sbs; qp.ps4_cam = cs->settings->camera_type == XRT_SETTINGS_CAMERA_TYPE_PS4; - qp.leap_motion = - cs->settings->camera_type == XRT_SETTINGS_CAMERA_TYPE_LEAP_MOTION; + qp.leap_motion = cs->settings->camera_type == XRT_SETTINGS_CAMERA_TYPE_LEAP_MOTION; u_sink_quirk_create(cs->xfctx, cali, &qp, &cali); // Now that we have setup a node graph, start it. - xrt_fs_stream_start(cs->xfs, cali, XRT_FS_CAPTURE_TYPE_CALIBRATION, - cs->settings->camera_mode); + xrt_fs_stream_start(cs->xfs, cali, XRT_FS_CAPTURE_TYPE_CALIBRATION, cs->settings->camera_mode); #else gui_scene_delete_me(p, &cs->base); #endif @@ -444,8 +422,7 @@ gui_scene_calibrate(struct gui_program *p, if (strcmp(xfs->name, "Leap Motion Controller") == 0) { cs->params.use_fisheye = true; cs->params.stereo_sbs = true; - cs->settings->camera_type = - XRT_SETTINGS_CAMERA_TYPE_LEAP_MOTION; + cs->settings->camera_type = XRT_SETTINGS_CAMERA_TYPE_LEAP_MOTION; snprintf(cs->filename, sizeof(cs->filename), "LeapMotion"); } @@ -463,8 +440,7 @@ gui_scene_calibrate(struct gui_program *p, if (valve || elp) { cs->params.use_fisheye = true; cs->params.stereo_sbs = true; - cs->settings->camera_type = - XRT_SETTINGS_CAMERA_TYPE_REGULAR_SBS; + cs->settings->camera_type = XRT_SETTINGS_CAMERA_TYPE_REGULAR_SBS; } #endif gui_scene_push_front(p, &cs->base); diff --git a/src/xrt/state_trackers/gui/gui_scene_debug.c b/src/xrt/state_trackers/gui/gui_scene_debug.c index 8f0cd044d..ff5dd712d 100644 --- a/src/xrt/state_trackers/gui/gui_scene_debug.c +++ b/src/xrt/state_trackers/gui/gui_scene_debug.c @@ -53,8 +53,7 @@ struct debug_scene */ static void -conv_rgb_f32_to_u8(struct xrt_colour_rgb_f32 *from, - struct xrt_colour_rgb_u8 *to) +conv_rgb_f32_to_u8(struct xrt_colour_rgb_f32 *from, struct xrt_colour_rgb_u8 *to) { to->r = (uint8_t)(from->r * 255.0f); to->g = (uint8_t)(from->g * 255.0f); @@ -62,8 +61,7 @@ conv_rgb_f32_to_u8(struct xrt_colour_rgb_f32 *from, } static void -conv_rgb_u8_to_f32(struct xrt_colour_rgb_u8 *from, - struct xrt_colour_rgb_f32 *to) +conv_rgb_u8_to_f32(struct xrt_colour_rgb_u8 *from, struct xrt_colour_rgb_f32 *to) { to->r = from->r / 255.0f; to->g = from->g / 255.0f; @@ -108,16 +106,15 @@ struct plot_state uint64_t now; }; -#define PLOT_HELPER(elm) \ - ImPlotPoint plot_##elm(void *ptr, int index) \ - { \ - struct plot_state *state = (struct plot_state *)ptr; \ - struct xrt_vec3 value; \ - uint64_t timestamp; \ - m_ff_vec3_f32_get(state->ff, index, &value, ×tamp); \ - ImPlotPoint point = {time_ns_to_s(state->now - timestamp), \ - value.elm}; \ - return point; \ +#define PLOT_HELPER(elm) \ + ImPlotPoint plot_##elm(void *ptr, int index) \ + { \ + struct plot_state *state = (struct plot_state *)ptr; \ + struct xrt_vec3 value; \ + uint64_t timestamp; \ + m_ff_vec3_f32_get(state->ff, index, &value, ×tamp); \ + ImPlotPoint point = {time_ns_to_s(state->now - timestamp), value.elm}; \ + return point; \ } PLOT_HELPER(x) @@ -159,8 +156,7 @@ on_ff_vec3_var(struct u_var_info *info, struct gui_program *p) ImPlotAxisFlags y3_flags = 0; ImVec2 size = {1024, 256}; - bool shown = ImPlot_BeginPlot(name, "time", "value", size, flags, - x_flags, y_flags, y2_flags, y3_flags); + bool shown = ImPlot_BeginPlot(name, "time", "value", size, flags, x_flags, y_flags, y2_flags, y3_flags); if (!shown) { return; } @@ -240,9 +236,8 @@ on_elem(struct u_var_info *info, void *priv) const float drag_speed = 0.2f; const float power = 1.0f; const ImVec2 dummy = {0, 0}; - ImGuiColorEditFlags flags = ImGuiColorEditFlags_NoInputs | - ImGuiColorEditFlags_NoLabel | - ImGuiColorEditFlags_PickerHueWheel; + ImGuiColorEditFlags flags = + ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_PickerHueWheel; (void)dummy; ImGuiInputTextFlags i_flags = ImGuiInputTextFlags_None; ImGuiInputTextFlags ro_i_flags = ImGuiInputTextFlags_ReadOnly; @@ -263,17 +258,10 @@ on_elem(struct u_var_info *info, void *priv) conv_rgb_f32_to_u8(&tmp, (struct xrt_colour_rgb_u8 *)ptr); break; } - case U_VAR_KIND_U8: - igDragScalar(name, ImGuiDataType_U8, ptr, drag_speed, NULL, - NULL, NULL, power); - break; - case U_VAR_KIND_I32: - igInputInt(name, (int *)ptr, 1, 10, i_flags); - break; + case U_VAR_KIND_U8: igDragScalar(name, ImGuiDataType_U8, ptr, drag_speed, NULL, NULL, NULL, power); break; + case U_VAR_KIND_I32: igInputInt(name, (int *)ptr, 1, 10, i_flags); break; case U_VAR_KIND_VEC3_I32: igInputInt3(name, (int *)ptr, i_flags); break; - case U_VAR_KIND_F32: - igInputFloat(name, (float *)ptr, 1, 10, "%+f", i_flags); - break; + case U_VAR_KIND_F32: igInputFloat(name, (float *)ptr, 1, 10, "%+f", i_flags); break; case U_VAR_KIND_F32_ARR: { struct u_var_f32_arr *f32_arr = ptr; int index = *f32_arr->index_ptr; @@ -286,8 +274,7 @@ on_elem(struct u_var_info *info, void *priv) float stats_min = FLT_MAX; float stats_max = FLT_MAX; - igPlotLinesFnFloatPtr(name, get_float_arr_val, arr, length, - index, NULL, stats_min, stats_max, + igPlotLinesFnFloatPtr(name, get_float_arr_val, arr, length, index, NULL, stats_min, stats_max, graph_size); break; } @@ -312,17 +299,12 @@ on_elem(struct u_var_info *info, void *priv) stats_max = arr[f]; } - igPlotTimings(name, get_float_arr_val, arr, length, index, NULL, - 0, stats_max, graph_size, - frametime_arr->reference_timing, - frametime_arr->center_reference_timing, - frametime_arr->range, frametime_arr->unit, - frametime_arr->dynamic_rescale); + igPlotTimings(name, get_float_arr_val, arr, length, index, NULL, 0, stats_max, graph_size, + frametime_arr->reference_timing, frametime_arr->center_reference_timing, + frametime_arr->range, frametime_arr->unit, frametime_arr->dynamic_rescale); break; } - case U_VAR_KIND_VEC3_F32: - igInputFloat3(name, (float *)ptr, "%+f", i_flags); - break; + case U_VAR_KIND_VEC3_F32: igInputFloat3(name, (float *)ptr, "%+f", i_flags); break; case U_VAR_KIND_POSE: { struct xrt_pose *pose = (struct xrt_pose *)ptr; char text[512]; @@ -332,44 +314,17 @@ on_elem(struct u_var_info *info, void *priv) handle_draggable_quat(text, &pose->orientation); break; } - case U_VAR_KIND_LOG_LEVEL: - igComboStr(name, (int *)ptr, - "Trace\0Debug\0Info\0Warn\0Error\0\0", 5); - break; + case U_VAR_KIND_LOG_LEVEL: igComboStr(name, (int *)ptr, "Trace\0Debug\0Info\0Warn\0Error\0\0", 5); break; case U_VAR_KIND_RO_TEXT: igText("%s: '%s'", name, (char *)ptr); break; - case U_VAR_KIND_RO_I32: - igInputScalar(name, ImGuiDataType_S32, ptr, NULL, NULL, NULL, - ro_i_flags); - break; - case U_VAR_KIND_RO_U32: - igInputScalar(name, ImGuiDataType_U32, ptr, NULL, NULL, NULL, - ro_i_flags); - break; - case U_VAR_KIND_RO_F32: - igInputScalar(name, ImGuiDataType_Float, ptr, NULL, NULL, "%+f", - ro_i_flags); - break; - case U_VAR_KIND_RO_I64: - igInputScalar(name, ImGuiDataType_S64, ptr, NULL, NULL, NULL, - ro_i_flags); - break; - case U_VAR_KIND_RO_U64: - igInputScalar(name, ImGuiDataType_S64, ptr, NULL, NULL, NULL, - ro_i_flags); - break; - case U_VAR_KIND_RO_F64: - igInputScalar(name, ImGuiDataType_Double, ptr, NULL, NULL, - "%+f", ro_i_flags); - break; - case U_VAR_KIND_RO_VEC3_I32: - igInputInt3(name, (int *)ptr, ro_i_flags); - break; - case U_VAR_KIND_RO_VEC3_F32: - igInputFloat3(name, (float *)ptr, "%+f", ro_i_flags); - break; - case U_VAR_KIND_RO_QUAT_F32: - igInputFloat4(name, (float *)ptr, "%+f", ro_i_flags); - break; + case U_VAR_KIND_RO_I32: igInputScalar(name, ImGuiDataType_S32, ptr, NULL, NULL, NULL, ro_i_flags); break; + case U_VAR_KIND_RO_U32: igInputScalar(name, ImGuiDataType_U32, ptr, NULL, NULL, NULL, ro_i_flags); break; + case U_VAR_KIND_RO_F32: igInputScalar(name, ImGuiDataType_Float, ptr, NULL, NULL, "%+f", ro_i_flags); break; + case U_VAR_KIND_RO_I64: igInputScalar(name, ImGuiDataType_S64, ptr, NULL, NULL, NULL, ro_i_flags); break; + case U_VAR_KIND_RO_U64: igInputScalar(name, ImGuiDataType_S64, ptr, NULL, NULL, NULL, ro_i_flags); break; + case U_VAR_KIND_RO_F64: igInputScalar(name, ImGuiDataType_Double, ptr, NULL, NULL, "%+f", ro_i_flags); break; + case U_VAR_KIND_RO_VEC3_I32: igInputInt3(name, (int *)ptr, ro_i_flags); break; + case U_VAR_KIND_RO_VEC3_F32: igInputFloat3(name, (float *)ptr, "%+f", ro_i_flags); break; + case U_VAR_KIND_RO_QUAT_F32: igInputFloat4(name, (float *)ptr, "%+f", ro_i_flags); break; case U_VAR_KIND_RO_FF_VEC3_F32: on_ff_vec3_var(info, state->p); break; case U_VAR_KIND_GUI_HEADER: { state->hidden = !igCollapsingHeaderBoolPtr(name, NULL, 0); diff --git a/src/xrt/state_trackers/gui/gui_scene_remote.c b/src/xrt/state_trackers/gui/gui_scene_remote.c index 82775b077..a5c67fdf0 100644 --- a/src/xrt/state_trackers/gui/gui_scene_remote.c +++ b/src/xrt/state_trackers/gui/gui_scene_remote.c @@ -53,9 +53,7 @@ const ImVec2 zero_dims = {0, 0}; #ifdef XRT_BUILD_DRIVER_REMOTE static void -handle_draggable_vec3_f32(const char *name, - struct xrt_vec3 *v, - const struct xrt_vec3 *reset) +handle_draggable_vec3_f32(const char *name, struct xrt_vec3 *v, const struct xrt_vec3 *reset) { float min = -256.0f; float max = 256.0f; @@ -72,9 +70,7 @@ handle_draggable_vec3_f32(const char *name, } static void -handle_draggable_quat(const char *name, - struct xrt_quat *q, - const struct xrt_quat *reset) +handle_draggable_quat(const char *name, struct xrt_quat *q, const struct xrt_quat *reset) { float min = -1.0f; float max = 1.0f; @@ -103,8 +99,7 @@ static bool handle_downable_button(const char *name) { igButton(name, zero_dims); - return igIsItemHovered(ImGuiHoveredFlags_RectOnly) && - igIsMouseDown(ImGuiMouseButton_Left); + return igIsItemHovered(ImGuiHoveredFlags_RectOnly) && igIsMouseDown(ImGuiMouseButton_Left); } static void @@ -197,55 +192,47 @@ render_cheat_menu(struct gui_remote *gr, struct gui_program *p) "d->left.angular_velocity.x = %ff;\n" "d->left.angular_velocity.y = %ff;\n" "d->left.angular_velocity.z = %ff;\n", - d->left.pose.position.x, d->left.pose.position.y, - d->left.pose.position.z, d->left.pose.orientation.x, - d->left.pose.orientation.y, d->left.pose.orientation.z, - d->left.pose.orientation.w, d->left.linear_velocity.x, - d->left.linear_velocity.y, d->left.linear_velocity.z, - d->left.angular_velocity.x, d->left.angular_velocity.y, + d->left.pose.position.x, d->left.pose.position.y, d->left.pose.position.z, + d->left.pose.orientation.x, d->left.pose.orientation.y, d->left.pose.orientation.z, + d->left.pose.orientation.w, d->left.linear_velocity.x, d->left.linear_velocity.y, + d->left.linear_velocity.z, d->left.angular_velocity.x, d->left.angular_velocity.y, d->left.angular_velocity.z); } } -#define POSE(prefix) \ - do { \ - handle_draggable_vec3_f32(#prefix ".pose.position", \ - &d->prefix.pose.position, \ - &r->prefix.pose.position); \ - handle_draggable_quat(#prefix ".pose.orientation", \ - &d->prefix.pose.orientation, \ - &r->prefix.pose.orientation); \ +#define POSE(prefix) \ + do { \ + handle_draggable_vec3_f32(#prefix ".pose.position", &d->prefix.pose.position, \ + &r->prefix.pose.position); \ + handle_draggable_quat(#prefix ".pose.orientation", &d->prefix.pose.orientation, \ + &r->prefix.pose.orientation); \ } while (false) -#define LIN_ANG(prefix) \ - do { \ - handle_draggable_vec3_f32(#prefix ".linear_velocity", \ - &d->prefix.linear_velocity, \ - &r->prefix.linear_velocity); \ - handle_draggable_vec3_f32(#prefix ".angular_velocity", \ - &d->prefix.angular_velocity, \ - &r->prefix.angular_velocity); \ +#define LIN_ANG(prefix) \ + do { \ + handle_draggable_vec3_f32(#prefix ".linear_velocity", &d->prefix.linear_velocity, \ + &r->prefix.linear_velocity); \ + handle_draggable_vec3_f32(#prefix ".angular_velocity", &d->prefix.angular_velocity, \ + &r->prefix.angular_velocity); \ } while (false) -#define BUTTONS(prefix) \ - do { \ - d->prefix.select = handle_downable_button("Select"); \ - igSameLine(0, 3); \ - d->prefix.menu = handle_downable_button("Menu"); \ - igSameLine(0, 3); \ - igCheckbox("Active", &d->prefix.active); \ +#define BUTTONS(prefix) \ + do { \ + d->prefix.select = handle_downable_button("Select"); \ + igSameLine(0, 3); \ + d->prefix.menu = handle_downable_button("Menu"); \ + igSameLine(0, 3); \ + igCheckbox("Active", &d->prefix.active); \ } while (false) -#define CURL(prefix, name, index) \ - igDragFloat(#prefix "." #name, &d->prefix.hand_curl[index], 0.01, 0.0, \ - 1.0, "%f", 0); -#define HAND(prefix) \ - do { \ - CURL(prefix, little, 0); \ - CURL(prefix, ring, 1); \ - CURL(prefix, middle, 2); \ - CURL(prefix, index, 3); \ - CURL(prefix, thumb, 4); \ +#define CURL(prefix, name, index) igDragFloat(#prefix "." #name, &d->prefix.hand_curl[index], 0.01, 0.0, 1.0, "%f", 0); +#define HAND(prefix) \ + do { \ + CURL(prefix, little, 0); \ + CURL(prefix, ring, 1); \ + CURL(prefix, middle, 2); \ + CURL(prefix, index, 3); \ + CURL(prefix, thumb, 4); \ } while (false) static void diff --git a/src/xrt/state_trackers/gui/gui_scene_video.c b/src/xrt/state_trackers/gui/gui_scene_video.c index b3c5002b7..8062276b4 100644 --- a/src/xrt/state_trackers/gui/gui_scene_video.c +++ b/src/xrt/state_trackers/gui/gui_scene_video.c @@ -59,14 +59,12 @@ on_video_device(struct xrt_prober *xp, } char buf[256] = {0}; - snprintf(buf, sizeof(buf), "%04x:%04x '%s' '%s'\n", pdev->vendor_id, - pdev->product_id, product, serial); + snprintf(buf, sizeof(buf), "%04x:%04x '%s' '%s'\n", pdev->vendor_id, pdev->product_id, product, serial); if (!igButton(buf, button_dims)) { return; } - snprintf(vs->settings->camera_name, sizeof(vs->settings->camera_name), - "%s", product); + snprintf(vs->settings->camera_name, sizeof(vs->settings->camera_name), "%s", product); vs->xfctx = U_TYPED_CALLOC(struct xrt_frame_context); xrt_prober_open_video_device(xp, pdev, vs->xfctx, &vs->xfs); @@ -78,8 +76,7 @@ render_mode(struct xrt_fs_mode *mode) { char tmp[512]; - snprintf(tmp, 512, "%ux%u: %s", mode->width, mode->height, - u_format_str(mode->format)); + snprintf(tmp, 512, "%ux%u: %s", mode->width, mode->height, u_format_str(mode->format)); return igButton(tmp, button_dims); } diff --git a/src/xrt/state_trackers/oxr/oxr_api_action.c b/src/xrt/state_trackers/oxr/oxr_api_action.c index ed00f65dd..aef248662 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_action.c +++ b/src/xrt/state_trackers/oxr/oxr_api_action.c @@ -34,41 +34,33 @@ oxr_xrSyncActions(XrSession session, const XrActionsSyncInfo *syncInfo) struct oxr_session *sess; struct oxr_logger log; OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrSyncActions"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, syncInfo, - XR_TYPE_ACTIONS_SYNC_INFO); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, syncInfo, XR_TYPE_ACTIONS_SYNC_INFO); if (syncInfo->countActiveActionSets == 0) { - return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, - "(syncInfo->countActiveActionSets == 0)"); + return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, "(syncInfo->countActiveActionSets == 0)"); } for (uint32_t i = 0; i < syncInfo->countActiveActionSets; i++) { struct oxr_action_set *act_set = NULL; - OXR_VERIFY_ACTIONSET_NOT_NULL( - &log, syncInfo->activeActionSets[i].actionSet, act_set); + OXR_VERIFY_ACTIONSET_NOT_NULL(&log, syncInfo->activeActionSets[i].actionSet, act_set); - XrResult res = oxr_verify_subaction_path_sync( - &log, sess->sys->inst, - syncInfo->activeActionSets[i].subactionPath, i); + XrResult res = oxr_verify_subaction_path_sync(&log, sess->sys->inst, + syncInfo->activeActionSets[i].subactionPath, i); if (res != XR_SUCCESS) { return res; } } - return oxr_action_sync_data(&log, sess, syncInfo->countActiveActionSets, - syncInfo->activeActionSets); + return oxr_action_sync_data(&log, sess, syncInfo->countActiveActionSets, syncInfo->activeActionSets); } XrResult -oxr_xrAttachSessionActionSets(XrSession session, - const XrSessionActionSetsAttachInfo *bindInfo) +oxr_xrAttachSessionActionSets(XrSession session, const XrSessionActionSetsAttachInfo *bindInfo) { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrAttachSessionActionSets"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, bindInfo, XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrAttachSessionActionSets"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, bindInfo, XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO); if (sess->act_set_attachments != NULL) { return oxr_error(&log, XR_ERROR_ACTIONSETS_ALREADY_ATTACHED, @@ -84,25 +76,20 @@ oxr_xrAttachSessionActionSets(XrSession session, for (uint32_t i = 0; i < bindInfo->countActionSets; i++) { struct oxr_action_set *act_set = NULL; - OXR_VERIFY_ACTIONSET_NOT_NULL(&log, bindInfo->actionSets[i], - act_set); + OXR_VERIFY_ACTIONSET_NOT_NULL(&log, bindInfo->actionSets[i], act_set); } return oxr_session_attach_action_sets(&log, sess, bindInfo); } XrResult -oxr_xrSuggestInteractionProfileBindings( - XrInstance instance, - const XrInteractionProfileSuggestedBinding *suggestedBindings) +oxr_xrSuggestInteractionProfileBindings(XrInstance instance, + const XrInteractionProfileSuggestedBinding *suggestedBindings) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrSuggestInteractionProfileBindings"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, suggestedBindings, - XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrSuggestInteractionProfileBindings"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, suggestedBindings, XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING); if (suggestedBindings->countSuggestedBindings == 0) { return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, @@ -116,11 +103,7 @@ oxr_xrSuggestInteractionProfileBindings( XrResult ret = oxr_path_get_string(&log, inst, ip, &str, &length); if (ret != XR_SUCCESS) { - oxr_error( - &log, ret, - "(suggestedBindings->countSuggestedBindings == 0x%08" PRIx64 - ") invalid path", - ip); + oxr_error(&log, ret, "(suggestedBindings->countSuggestedBindings == 0x%08" PRIx64 ") invalid path", ip); } // Used in the loop that verifies the suggested bindings paths. @@ -147,65 +130,55 @@ oxr_xrSuggestInteractionProfileBindings( } else if (ip == inst->path_cache.mndx_ball_on_a_stick_controller) { func = oxr_verify_mndx_ball_on_a_stick_controller_subpath; } else { - return oxr_error( - &log, XR_ERROR_PATH_UNSUPPORTED, - "(suggestedBindings->interactionProfile == \"%s\") is not " - "a supported interaction profile", - str); + return oxr_error(&log, XR_ERROR_PATH_UNSUPPORTED, + "(suggestedBindings->interactionProfile == \"%s\") is not " + "a supported interaction profile", + str); } for (size_t i = 0; i < suggestedBindings->countSuggestedBindings; i++) { - const XrActionSuggestedBinding *s = - &suggestedBindings->suggestedBindings[i]; + const XrActionSuggestedBinding *s = &suggestedBindings->suggestedBindings[i]; struct oxr_action *act; OXR_VERIFY_ACTION_NOT_NULL(&log, s->action, act); if (act->act_set->data->ever_attached) { - return oxr_error( - &log, XR_ERROR_ACTIONSETS_ALREADY_ATTACHED, - "(suggestedBindings->suggestedBindings[%zu]->" - "action) action '%s/%s' has already been attached", - i, act->act_set->data->name, act->data->name); + return oxr_error(&log, XR_ERROR_ACTIONSETS_ALREADY_ATTACHED, + "(suggestedBindings->suggestedBindings[%zu]->" + "action) action '%s/%s' has already been attached", + i, act->act_set->data->name, act->data->name); } - ret = - oxr_path_get_string(&log, inst, s->binding, &str, &length); + ret = oxr_path_get_string(&log, inst, s->binding, &str, &length); if (ret != XR_SUCCESS) { - return oxr_error( - &log, XR_ERROR_PATH_INVALID, - "(suggestedBindings->suggestedBindings[%zu]->" - "binding == %" PRIu64 ") is not a valid path", - i, s->binding); + return oxr_error(&log, XR_ERROR_PATH_INVALID, + "(suggestedBindings->suggestedBindings[%zu]->" + "binding == %" PRIu64 ") is not a valid path", + i, s->binding); } if (!func(str, length)) { - return oxr_error( - &log, XR_ERROR_PATH_UNSUPPORTED, - "(suggestedBindings->suggestedBindings[%zu]->" - "binding == \"%s\") is not a valid path", - i, str); + return oxr_error(&log, XR_ERROR_PATH_UNSUPPORTED, + "(suggestedBindings->suggestedBindings[%zu]->" + "binding == \"%s\") is not a valid path", + i, str); } } - return oxr_action_suggest_interaction_profile_bindings( - &log, inst, suggestedBindings); + return oxr_action_suggest_interaction_profile_bindings(&log, inst, suggestedBindings); } XrResult -oxr_xrGetCurrentInteractionProfile( - XrSession session, - XrPath topLevelUserPath, - XrInteractionProfileState *interactionProfile) +oxr_xrGetCurrentInteractionProfile(XrSession session, + XrPath topLevelUserPath, + XrInteractionProfileState *interactionProfile) { struct oxr_instance *inst = NULL; struct oxr_session *sess = NULL; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrGetCurrentInteractionProfile"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, interactionProfile, - XR_TYPE_INTERACTION_PROFILE_STATE); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrGetCurrentInteractionProfile"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, interactionProfile, XR_TYPE_INTERACTION_PROFILE_STATE); // Short hand. inst = sess->sys->inst; @@ -217,16 +190,14 @@ oxr_xrGetCurrentInteractionProfile( } if (!oxr_path_is_valid(&log, inst, topLevelUserPath)) { - return oxr_error( - &log, XR_ERROR_PATH_INVALID, - "(topLevelUserPath == %zu) Is not a valid path", - topLevelUserPath); + return oxr_error(&log, XR_ERROR_PATH_INVALID, "(topLevelUserPath == %zu) Is not a valid path", + topLevelUserPath); } bool fail = true; -#define COMPUTE_FAIL(X) \ - if (topLevelUserPath == inst->path_cache.X) { \ - fail = false; \ +#define COMPUTE_FAIL(X) \ + if (topLevelUserPath == inst->path_cache.X) { \ + fail = false; \ } OXR_FOR_EACH_SUBACTION_PATH(COMPUTE_FAIL) @@ -243,33 +214,28 @@ oxr_xrGetCurrentInteractionProfile( } /* XXX: How do we return XR_SESSION_LOSS_PENDING here? */ - return oxr_action_get_current_interaction_profile( - &log, sess, topLevelUserPath, interactionProfile); + return oxr_action_get_current_interaction_profile(&log, sess, topLevelUserPath, interactionProfile); } XrResult -oxr_xrGetInputSourceLocalizedName( - XrSession session, - const XrInputSourceLocalizedNameGetInfo *getInfo, - uint32_t bufferCapacityInput, - uint32_t *bufferCountOutput, - char *buffer) +oxr_xrGetInputSourceLocalizedName(XrSession session, + const XrInputSourceLocalizedNameGetInfo *getInfo, + uint32_t bufferCapacityInput, + uint32_t *bufferCountOutput, + char *buffer) { struct oxr_instance *inst = NULL; struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrGetInputSourceLocalizedName"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, getInfo, XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrGetInputSourceLocalizedName"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO); // Short hand. inst = sess->sys->inst; if (sess->act_set_attachments == NULL) { - return oxr_error( - &log, XR_ERROR_ACTIONSET_NOT_ATTACHED, - "ActionSet(s) have not been attached to this session"); + return oxr_error(&log, XR_ERROR_ACTIONSET_NOT_ATTACHED, + "ActionSet(s) have not been attached to this session"); } if (getInfo->sourcePath == XR_NULL_PATH) { @@ -279,33 +245,25 @@ oxr_xrGetInputSourceLocalizedName( } if (!oxr_path_is_valid(&log, inst, getInfo->sourcePath)) { - return oxr_error( - &log, XR_ERROR_PATH_INVALID, - "(getInfo->sourcePath == %zu) Is not a valid path", - getInfo->sourcePath); + return oxr_error(&log, XR_ERROR_PATH_INVALID, "(getInfo->sourcePath == %zu) Is not a valid path", + getInfo->sourcePath); } - const XrInputSourceLocalizedNameFlags all = - XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT | - XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT | - XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT; + const XrInputSourceLocalizedNameFlags all = XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT | + XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT | + XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT; if ((getInfo->whichComponents & ~all) != 0) { - return oxr_error( - &log, XR_ERROR_VALIDATION_FAILURE, - "(getInfo->whichComponents == %08zx) contains invalid bits", - getInfo->whichComponents); + return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, + "(getInfo->whichComponents == %08zx) contains invalid bits", getInfo->whichComponents); } if (getInfo->whichComponents == 0) { - return oxr_error( - &log, XR_ERROR_VALIDATION_FAILURE, - "(getInfo->whichComponents == 0) can not be zero"); + return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, "(getInfo->whichComponents == 0) can not be zero"); } - return oxr_action_get_input_source_localized_name( - &log, sess, getInfo, bufferCapacityInput, bufferCountOutput, - buffer); + return oxr_action_get_input_source_localized_name(&log, sess, getInfo, bufferCapacityInput, bufferCountOutput, + buffer); } @@ -316,9 +274,7 @@ oxr_xrGetInputSourceLocalizedName( */ XrResult -oxr_xrCreateActionSet(XrInstance instance, - const XrActionSetCreateInfo *createInfo, - XrActionSet *actionSet) +oxr_xrCreateActionSet(XrInstance instance, const XrActionSetCreateInfo *createInfo, XrActionSet *actionSet) { struct oxr_action_set *act_set = NULL; struct oxr_instance *inst = NULL; @@ -326,13 +282,10 @@ oxr_xrCreateActionSet(XrInstance instance, struct oxr_logger log; int h_ret; XrResult ret; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrCreateActionSet"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, - XR_TYPE_ACTION_SET_CREATE_INFO); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrCreateActionSet"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_ACTION_SET_CREATE_INFO); OXR_VERIFY_ARG_NOT_NULL(&log, actionSet); - OXR_VERIFY_ARG_SINGLE_LEVEL_FIXED_LENGTH_PATH( - &log, createInfo->actionSetName); + OXR_VERIFY_ARG_SINGLE_LEVEL_FIXED_LENGTH_PATH(&log, createInfo->actionSetName); OXR_VERIFY_ARG_LOCALIZED_NAME(&log, createInfo->localizedActionSetName); @@ -340,17 +293,13 @@ oxr_xrCreateActionSet(XrInstance instance, * Dup checks. */ - h_ret = u_hashset_find_c_str(inst->action_sets.name_store, - createInfo->actionSetName, &d); + h_ret = u_hashset_find_c_str(inst->action_sets.name_store, createInfo->actionSetName, &d); if (h_ret >= 0) { - return oxr_error( - &log, XR_ERROR_NAME_DUPLICATED, - "(createInfo->actionSetName == '%s') is duplicated", - createInfo->actionSetName); + return oxr_error(&log, XR_ERROR_NAME_DUPLICATED, "(createInfo->actionSetName == '%s') is duplicated", + createInfo->actionSetName); } - h_ret = u_hashset_find_c_str(inst->action_sets.loc_store, - createInfo->localizedActionSetName, &d); + h_ret = u_hashset_find_c_str(inst->action_sets.loc_store, createInfo->localizedActionSetName, &d); if (h_ret >= 0) { return oxr_error(&log, XR_ERROR_LOCALIZED_NAME_DUPLICATED, "(createInfo->localizedActionSetName == '%s') " @@ -378,8 +327,7 @@ oxr_xrDestroyActionSet(XrActionSet actionSet) { struct oxr_action_set *act_set; struct oxr_logger log; - OXR_VERIFY_ACTIONSET_AND_INIT_LOG(&log, actionSet, act_set, - "xrDestroyActionSet"); + OXR_VERIFY_ACTIONSET_AND_INIT_LOG(&log, actionSet, act_set, "xrDestroyActionSet"); return oxr_handle_destroy(&log, &act_set->handle); } @@ -392,9 +340,7 @@ oxr_xrDestroyActionSet(XrActionSet actionSet) */ XrResult -oxr_xrCreateAction(XrActionSet actionSet, - const XrActionCreateInfo *createInfo, - XrAction *action) +oxr_xrCreateAction(XrActionSet actionSet, const XrActionCreateInfo *createInfo, XrAction *action) { struct oxr_action_set *act_set; struct u_hashset_item *d = NULL; @@ -403,26 +349,21 @@ oxr_xrCreateAction(XrActionSet actionSet, XrResult ret; int h_ret; - OXR_VERIFY_ACTIONSET_AND_INIT_LOG(&log, actionSet, act_set, - "xrCreateAction"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, - XR_TYPE_ACTION_CREATE_INFO); - OXR_VERIFY_ARG_SINGLE_LEVEL_FIXED_LENGTH_PATH(&log, - createInfo->actionName); + OXR_VERIFY_ACTIONSET_AND_INIT_LOG(&log, actionSet, act_set, "xrCreateAction"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_ACTION_CREATE_INFO); + OXR_VERIFY_ARG_SINGLE_LEVEL_FIXED_LENGTH_PATH(&log, createInfo->actionName); OXR_VERIFY_ARG_LOCALIZED_NAME(&log, createInfo->localizedActionName); OXR_VERIFY_ARG_NOT_NULL(&log, action); if (act_set->data->ever_attached) { - return oxr_error( - &log, XR_ERROR_ACTIONSETS_ALREADY_ATTACHED, - "(actionSet) has been attached and is now immutable"); + return oxr_error(&log, XR_ERROR_ACTIONSETS_ALREADY_ATTACHED, + "(actionSet) has been attached and is now immutable"); } struct oxr_instance *inst = act_set->inst; - ret = oxr_verify_subaction_paths_create( - &log, inst, createInfo->countSubactionPaths, - createInfo->subactionPaths, "createInfo->subactionPaths"); + ret = oxr_verify_subaction_paths_create(&log, inst, createInfo->countSubactionPaths, createInfo->subactionPaths, + "createInfo->subactionPaths"); if (ret != XR_SUCCESS) { return ret; } @@ -432,17 +373,13 @@ oxr_xrCreateAction(XrActionSet actionSet, * Dup checks. */ - h_ret = u_hashset_find_c_str(act_set->data->actions.name_store, - createInfo->actionName, &d); + h_ret = u_hashset_find_c_str(act_set->data->actions.name_store, createInfo->actionName, &d); if (h_ret >= 0) { - return oxr_error( - &log, XR_ERROR_NAME_DUPLICATED, - "(createInfo->actionName == '%s') is duplicated", - createInfo->actionName); + return oxr_error(&log, XR_ERROR_NAME_DUPLICATED, "(createInfo->actionName == '%s') is duplicated", + createInfo->actionName); } - h_ret = u_hashset_find_c_str(act_set->data->actions.loc_store, - createInfo->localizedActionName, &d); + h_ret = u_hashset_find_c_str(act_set->data->actions.loc_store, createInfo->localizedActionName, &d); if (h_ret >= 0) { return oxr_error(&log, XR_ERROR_LOCALIZED_NAME_DUPLICATED, "(createInfo->localizedActionName == '%s') " @@ -476,132 +413,102 @@ oxr_xrDestroyAction(XrAction action) } XrResult -oxr_xrGetActionStateBoolean(XrSession session, - const XrActionStateGetInfo *getInfo, - XrActionStateBoolean *data) +oxr_xrGetActionStateBoolean(XrSession session, const XrActionStateGetInfo *getInfo, XrActionStateBoolean *data) { struct oxr_session *sess = NULL; struct oxr_action *act = NULL; struct oxr_sub_paths sub_paths = {0}; struct oxr_logger log; XrResult ret; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrGetActionStateBoolean"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, data, - XR_TYPE_ACTION_STATE_BOOLEAN); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, - XR_TYPE_ACTION_STATE_GET_INFO); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrGetActionStateBoolean"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, data, XR_TYPE_ACTION_STATE_BOOLEAN); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, XR_TYPE_ACTION_STATE_GET_INFO); OXR_VERIFY_ACTION_NOT_NULL(&log, getInfo->action, act); if (act->data->action_type != XR_ACTION_TYPE_BOOLEAN_INPUT) { - return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, - "Not created with boolean type"); + return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, "Not created with boolean type"); } - ret = oxr_verify_subaction_path_get( - &log, act->act_set->inst, getInfo->subactionPath, - &act->data->sub_paths, &sub_paths, "getInfo->subactionPath"); + ret = oxr_verify_subaction_path_get(&log, act->act_set->inst, getInfo->subactionPath, &act->data->sub_paths, + &sub_paths, "getInfo->subactionPath"); if (ret != XR_SUCCESS) { return ret; } - return oxr_action_get_boolean(&log, sess, act->act_key, sub_paths, - data); + return oxr_action_get_boolean(&log, sess, act->act_key, sub_paths, data); } XrResult -oxr_xrGetActionStateFloat(XrSession session, - const XrActionStateGetInfo *getInfo, - XrActionStateFloat *data) +oxr_xrGetActionStateFloat(XrSession session, const XrActionStateGetInfo *getInfo, XrActionStateFloat *data) { struct oxr_session *sess = NULL; struct oxr_action *act = NULL; struct oxr_sub_paths sub_paths = {0}; struct oxr_logger log; XrResult ret; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrGetActionStateFloat"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, data, - XR_TYPE_ACTION_STATE_FLOAT); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, - XR_TYPE_ACTION_STATE_GET_INFO); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrGetActionStateFloat"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, data, XR_TYPE_ACTION_STATE_FLOAT); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, XR_TYPE_ACTION_STATE_GET_INFO); OXR_VERIFY_ACTION_NOT_NULL(&log, getInfo->action, act); if (act->data->action_type != XR_ACTION_TYPE_FLOAT_INPUT) { - return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, - "Not created with float type"); + return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, "Not created with float type"); } - ret = oxr_verify_subaction_path_get( - &log, act->act_set->inst, getInfo->subactionPath, - &act->data->sub_paths, &sub_paths, "getInfo->subactionPath"); + ret = oxr_verify_subaction_path_get(&log, act->act_set->inst, getInfo->subactionPath, &act->data->sub_paths, + &sub_paths, "getInfo->subactionPath"); if (ret != XR_SUCCESS) { return ret; } - return oxr_action_get_vector1f(&log, sess, act->act_key, sub_paths, - data); + return oxr_action_get_vector1f(&log, sess, act->act_key, sub_paths, data); } XrResult -oxr_xrGetActionStateVector2f(XrSession session, - const XrActionStateGetInfo *getInfo, - XrActionStateVector2f *data) +oxr_xrGetActionStateVector2f(XrSession session, const XrActionStateGetInfo *getInfo, XrActionStateVector2f *data) { struct oxr_session *sess = NULL; struct oxr_action *act = NULL; struct oxr_sub_paths sub_paths = {0}; struct oxr_logger log; XrResult ret; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrGetActionStateVector2f"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, data, - XR_TYPE_ACTION_STATE_VECTOR2F); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, - XR_TYPE_ACTION_STATE_GET_INFO); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrGetActionStateVector2f"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, data, XR_TYPE_ACTION_STATE_VECTOR2F); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, XR_TYPE_ACTION_STATE_GET_INFO); OXR_VERIFY_ACTION_NOT_NULL(&log, getInfo->action, act); if (act->data->action_type != XR_ACTION_TYPE_VECTOR2F_INPUT) { - return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, - "Not created with float[2] type"); + return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, "Not created with float[2] type"); } - ret = oxr_verify_subaction_path_get( - &log, act->act_set->inst, getInfo->subactionPath, - &act->data->sub_paths, &sub_paths, "getInfo->subactionPath"); + ret = oxr_verify_subaction_path_get(&log, act->act_set->inst, getInfo->subactionPath, &act->data->sub_paths, + &sub_paths, "getInfo->subactionPath"); if (ret != XR_SUCCESS) { return ret; } - return oxr_action_get_vector2f(&log, sess, act->act_key, sub_paths, - data); + return oxr_action_get_vector2f(&log, sess, act->act_key, sub_paths, data); } XrResult -oxr_xrGetActionStatePose(XrSession session, - const XrActionStateGetInfo *getInfo, - XrActionStatePose *data) +oxr_xrGetActionStatePose(XrSession session, const XrActionStateGetInfo *getInfo, XrActionStatePose *data) { struct oxr_session *sess = NULL; struct oxr_action *act = NULL; struct oxr_sub_paths sub_paths = {0}; struct oxr_logger log; XrResult ret; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrGetActionStatePose"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrGetActionStatePose"); OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, data, XR_TYPE_ACTION_STATE_POSE); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, - XR_TYPE_ACTION_STATE_GET_INFO); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, XR_TYPE_ACTION_STATE_GET_INFO); OXR_VERIFY_ACTION_NOT_NULL(&log, getInfo->action, act); if (act->data->action_type != XR_ACTION_TYPE_POSE_INPUT) { - return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, - "Not created with pose type"); + return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, "Not created with pose type"); } - ret = oxr_verify_subaction_path_get( - &log, act->act_set->inst, getInfo->subactionPath, - &act->data->sub_paths, &sub_paths, "getInfo->subactionPath"); + ret = oxr_verify_subaction_path_get(&log, act->act_set->inst, getInfo->subactionPath, &act->data->sub_paths, + &sub_paths, "getInfo->subactionPath"); if (ret != XR_SUCCESS) { return ret; } @@ -610,21 +517,17 @@ oxr_xrGetActionStatePose(XrSession session, } XrResult -oxr_xrEnumerateBoundSourcesForAction( - XrSession session, - const XrBoundSourcesForActionEnumerateInfo *enumerateInfo, - uint32_t sourceCapacityInput, - uint32_t *sourceCountOutput, - XrPath *sources) +oxr_xrEnumerateBoundSourcesForAction(XrSession session, + const XrBoundSourcesForActionEnumerateInfo *enumerateInfo, + uint32_t sourceCapacityInput, + uint32_t *sourceCountOutput, + XrPath *sources) { struct oxr_session *sess = NULL; struct oxr_action *act = NULL; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrEnumerateBoundSourcesForAction"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, enumerateInfo, - XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrEnumerateBoundSourcesForAction"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, enumerateInfo, XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO); OXR_VERIFY_ACTION_NOT_NULL(&log, enumerateInfo->action, act); if (sess->act_set_attachments == NULL) { @@ -633,9 +536,8 @@ oxr_xrEnumerateBoundSourcesForAction( "been called on this session."); } - return oxr_action_enumerate_bound_sources(&log, sess, act->act_key, - sourceCapacityInput, - sourceCountOutput, sources); + return oxr_action_enumerate_bound_sources(&log, sess, act->act_key, sourceCapacityInput, sourceCountOutput, + sources); } @@ -655,57 +557,45 @@ oxr_xrApplyHapticFeedback(XrSession session, struct oxr_sub_paths sub_paths = {0}; struct oxr_logger log; XrResult ret; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrApplyHapticFeedback"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, hapticActionInfo, - XR_TYPE_HAPTIC_ACTION_INFO); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, hapticEvent, - XR_TYPE_HAPTIC_VIBRATION); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrApplyHapticFeedback"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, hapticActionInfo, XR_TYPE_HAPTIC_ACTION_INFO); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, hapticEvent, XR_TYPE_HAPTIC_VIBRATION); OXR_VERIFY_ACTION_NOT_NULL(&log, hapticActionInfo->action, act); - ret = oxr_verify_subaction_path_get( - &log, act->act_set->inst, hapticActionInfo->subactionPath, - &act->data->sub_paths, &sub_paths, "getInfo->subactionPath"); + ret = oxr_verify_subaction_path_get(&log, act->act_set->inst, hapticActionInfo->subactionPath, + &act->data->sub_paths, &sub_paths, "getInfo->subactionPath"); if (ret != XR_SUCCESS) { return ret; } if (act->data->action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT) { - return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, - "Not created with output vibration type"); + return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, "Not created with output vibration type"); } - return oxr_action_apply_haptic_feedback(&log, sess, act->act_key, - sub_paths, hapticEvent); + return oxr_action_apply_haptic_feedback(&log, sess, act->act_key, sub_paths, hapticEvent); } XrResult -oxr_xrStopHapticFeedback(XrSession session, - const XrHapticActionInfo *hapticActionInfo) +oxr_xrStopHapticFeedback(XrSession session, const XrHapticActionInfo *hapticActionInfo) { struct oxr_session *sess = NULL; struct oxr_action *act = NULL; struct oxr_sub_paths sub_paths = {0}; struct oxr_logger log; XrResult ret; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrStopHapticFeedback"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, hapticActionInfo, - XR_TYPE_HAPTIC_ACTION_INFO); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrStopHapticFeedback"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, hapticActionInfo, XR_TYPE_HAPTIC_ACTION_INFO); OXR_VERIFY_ACTION_NOT_NULL(&log, hapticActionInfo->action, act); - ret = oxr_verify_subaction_path_get( - &log, act->act_set->inst, hapticActionInfo->subactionPath, - &act->data->sub_paths, &sub_paths, "getInfo->subactionPath"); + ret = oxr_verify_subaction_path_get(&log, act->act_set->inst, hapticActionInfo->subactionPath, + &act->data->sub_paths, &sub_paths, "getInfo->subactionPath"); if (ret != XR_SUCCESS) { return ret; } if (act->data->action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT) { - return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, - "Not created with output vibration type"); + return oxr_error(&log, XR_ERROR_ACTION_TYPE_MISMATCH, "Not created with output vibration type"); } - return oxr_action_stop_haptic_feedback(&log, sess, act->act_key, - sub_paths); + return oxr_action_stop_haptic_feedback(&log, sess, act->act_key, sub_paths); } diff --git a/src/xrt/state_trackers/oxr/oxr_api_debug.c b/src/xrt/state_trackers/oxr/oxr_api_debug.c index 2a7ef1d13..738533983 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_debug.c +++ b/src/xrt/state_trackers/oxr/oxr_api_debug.c @@ -16,32 +16,27 @@ XrResult -oxr_xrSetDebugUtilsObjectNameEXT(XrInstance instance, - const XrDebugUtilsObjectNameInfoEXT *nameInfo) +oxr_xrSetDebugUtilsObjectNameEXT(XrInstance instance, const XrDebugUtilsObjectNameInfoEXT *nameInfo) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrSetDebugUtilsObjectNameEXT"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrSetDebugUtilsObjectNameEXT"); OXR_VERIFY_EXTENSION(&log, inst, EXT_debug_utils); return oxr_error(&log, XR_ERROR_RUNTIME_FAILURE, " not implemented"); } XrResult -oxr_xrCreateDebugUtilsMessengerEXT( - XrInstance instance, - const XrDebugUtilsMessengerCreateInfoEXT *createInfo, - XrDebugUtilsMessengerEXT *messenger) +oxr_xrCreateDebugUtilsMessengerEXT(XrInstance instance, + const XrDebugUtilsMessengerCreateInfoEXT *createInfo, + XrDebugUtilsMessengerEXT *messenger) { struct oxr_instance *inst; struct oxr_debug_messenger *mssngr; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrCreateDebugUtilsMessengerEXT"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrCreateDebugUtilsMessengerEXT"); OXR_VERIFY_EXTENSION(&log, inst, EXT_debug_utils); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, createInfo, XR_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT); OXR_VERIFY_ARG_NOT_NULL(&log, messenger); XrResult ret = oxr_create_messenger(&log, inst, createInfo, &mssngr); @@ -59,24 +54,21 @@ oxr_xrDestroyDebugUtilsMessengerEXT(XrDebugUtilsMessengerEXT messenger) { struct oxr_debug_messenger *mssngr; struct oxr_logger log; - OXR_VERIFY_MESSENGER_AND_INIT_LOG(&log, messenger, mssngr, - "xrDestroyDebugUtilsMessengerEXT"); + OXR_VERIFY_MESSENGER_AND_INIT_LOG(&log, messenger, mssngr, "xrDestroyDebugUtilsMessengerEXT"); OXR_VERIFY_EXTENSION(&log, mssngr->inst, EXT_debug_utils); return oxr_handle_destroy(&log, &mssngr->handle); } XrResult -oxr_xrSubmitDebugUtilsMessageEXT( - XrInstance instance, - XrDebugUtilsMessageSeverityFlagsEXT messageSeverity, - XrDebugUtilsMessageTypeFlagsEXT messageTypes, - const XrDebugUtilsMessengerCallbackDataEXT *callbackData) +oxr_xrSubmitDebugUtilsMessageEXT(XrInstance instance, + XrDebugUtilsMessageSeverityFlagsEXT messageSeverity, + XrDebugUtilsMessageTypeFlagsEXT messageTypes, + const XrDebugUtilsMessengerCallbackDataEXT *callbackData) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrSubmitDebugUtilsMessageEXT"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrSubmitDebugUtilsMessageEXT"); OXR_VERIFY_EXTENSION(&log, inst, EXT_debug_utils); oxr_warn(&log, " not fully implemented"); @@ -84,13 +76,11 @@ oxr_xrSubmitDebugUtilsMessageEXT( } XrResult -oxr_xrSessionBeginDebugUtilsLabelRegionEXT( - XrSession session, const XrDebugUtilsLabelEXT *labelInfo) +oxr_xrSessionBeginDebugUtilsLabelRegionEXT(XrSession session, const XrDebugUtilsLabelEXT *labelInfo) { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG( - &log, session, sess, "xrSessionBeginDebugUtilsLabelRegionEXT"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrSessionBeginDebugUtilsLabelRegionEXT"); OXR_VERIFY_EXTENSION(&log, sess->sys->inst, EXT_debug_utils); return oxr_error(&log, XR_ERROR_RUNTIME_FAILURE, " not implemented"); @@ -101,21 +91,18 @@ oxr_xrSessionEndDebugUtilsLabelRegionEXT(XrSession session) { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrSessionEndDebugUtilsLabelRegionEXT"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrSessionEndDebugUtilsLabelRegionEXT"); OXR_VERIFY_EXTENSION(&log, sess->sys->inst, EXT_debug_utils); return oxr_error(&log, XR_ERROR_RUNTIME_FAILURE, " not implemented"); } XrResult -oxr_xrSessionInsertDebugUtilsLabelEXT(XrSession session, - const XrDebugUtilsLabelEXT *labelInfo) +oxr_xrSessionInsertDebugUtilsLabelEXT(XrSession session, const XrDebugUtilsLabelEXT *labelInfo) { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrSessionInsertDebugUtilsLabelEXT"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrSessionInsertDebugUtilsLabelEXT"); OXR_VERIFY_EXTENSION(&log, sess->sys->inst, EXT_debug_utils); return oxr_error(&log, XR_ERROR_RUNTIME_FAILURE, " not implemented"); diff --git a/src/xrt/state_trackers/oxr/oxr_api_funcs.h b/src/xrt/state_trackers/oxr/oxr_api_funcs.h index 7658e1a9b..e91d08161 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_funcs.h +++ b/src/xrt/state_trackers/oxr/oxr_api_funcs.h @@ -35,9 +35,7 @@ extern "C" { //! OpenXR API function @ep{xrGetInstanceProcAddr} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetInstanceProcAddr(XrInstance instance, - const char *name, - PFN_xrVoidFunction *function); +oxr_xrGetInstanceProcAddr(XrInstance instance, const char *name, PFN_xrVoidFunction *function); //! OpenXR API function @ep{xrEnumerateApiLayerProperties} XRAPI_ATTR XrResult XRAPI_CALL @@ -61,8 +59,7 @@ oxr_xrEnumerateInstanceExtensionProperties(const char *layerName, //! OpenXR API function @ep{xrCreateInstance} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrCreateInstance(const XrInstanceCreateInfo *createInfo, - XrInstance *instance); +oxr_xrCreateInstance(const XrInstanceCreateInfo *createInfo, XrInstance *instance); //! OpenXR API function @ep{xrDestroyInstance} XRAPI_ATTR XrResult XRAPI_CALL @@ -70,8 +67,7 @@ oxr_xrDestroyInstance(XrInstance instance); //! OpenXR API function @ep{xrGetInstanceProperties} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetInstanceProperties(XrInstance instance, - XrInstanceProperties *instanceProperties); +oxr_xrGetInstanceProperties(XrInstance instance, XrInstanceProperties *instanceProperties); //! OpenXR API function @ep{xrPollEvent} XRAPI_ATTR XrResult XRAPI_CALL @@ -79,15 +75,11 @@ oxr_xrPollEvent(XrInstance instance, XrEventDataBuffer *eventData); //! OpenXR API function @ep{xrResultToString} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrResultToString(XrInstance instance, - XrResult value, - char buffer[XR_MAX_RESULT_STRING_SIZE]); +oxr_xrResultToString(XrInstance instance, XrResult value, char buffer[XR_MAX_RESULT_STRING_SIZE]); //! OpenXR API function @ep{xrStructureTypeToString} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrStructureTypeToString(XrInstance instance, - XrStructureType value, - char buffer[XR_MAX_STRUCTURE_NAME_SIZE]); +oxr_xrStructureTypeToString(XrInstance instance, XrStructureType value, char buffer[XR_MAX_STRUCTURE_NAME_SIZE]); //! OpenXR API function @ep{xrStringToPath} XRAPI_ATTR XrResult XRAPI_CALL @@ -95,23 +87,16 @@ oxr_xrStringToPath(XrInstance instance, const char *pathString, XrPath *path); //! OpenXR API function @ep{xrPathToString} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrPathToString(XrInstance instance, - XrPath path, - uint32_t bufferCapacityInput, - uint32_t *bufferCountOutput, - char *buffer); +oxr_xrPathToString( + XrInstance instance, XrPath path, uint32_t bufferCapacityInput, uint32_t *bufferCountOutput, char *buffer); //! OpenXR API function @ep{xrConvertTimespecTimeToTimeKHR} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrConvertTimespecTimeToTimeKHR(XrInstance instance, - const struct timespec *timespecTime, - XrTime *time); +oxr_xrConvertTimespecTimeToTimeKHR(XrInstance instance, const struct timespec *timespecTime, XrTime *time); //! OpenXR API function @ep{xrConvertTimeToTimespecTimeKHR} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrConvertTimeToTimespecTimeKHR(XrInstance instance, - XrTime time, - struct timespec *timespecTime); +oxr_xrConvertTimeToTimespecTimeKHR(XrInstance instance, XrTime time, struct timespec *timespecTime); /* * @@ -121,69 +106,59 @@ oxr_xrConvertTimeToTimespecTimeKHR(XrInstance instance, //! OpenXR API function @ep{xrGetSystem} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetSystem(XrInstance instance, - const XrSystemGetInfo *getInfo, - XrSystemId *systemId); +oxr_xrGetSystem(XrInstance instance, const XrSystemGetInfo *getInfo, XrSystemId *systemId); //! OpenXR API function @ep{xrGetSystemProperties} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetSystemProperties(XrInstance instance, - XrSystemId systemId, - XrSystemProperties *properties); +oxr_xrGetSystemProperties(XrInstance instance, XrSystemId systemId, XrSystemProperties *properties); //! OpenXR API function @ep{xrEnumerateViewConfigurations} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrEnumerateViewConfigurations( - XrInstance instance, - XrSystemId systemId, - uint32_t viewConfigurationTypeCapacityInput, - uint32_t *viewConfigurationTypeCountOutput, - XrViewConfigurationType *viewConfigurationTypes); +oxr_xrEnumerateViewConfigurations(XrInstance instance, + XrSystemId systemId, + uint32_t viewConfigurationTypeCapacityInput, + uint32_t *viewConfigurationTypeCountOutput, + XrViewConfigurationType *viewConfigurationTypes); //! OpenXR API function @ep{xrGetViewConfigurationProperties} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetViewConfigurationProperties( - XrInstance instance, - XrSystemId systemId, - XrViewConfigurationType viewConfigurationType, - XrViewConfigurationProperties *configurationProperties); +oxr_xrGetViewConfigurationProperties(XrInstance instance, + XrSystemId systemId, + XrViewConfigurationType viewConfigurationType, + XrViewConfigurationProperties *configurationProperties); //! OpenXR API function @ep{xrEnumerateViewConfigurationViews} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrEnumerateViewConfigurationViews( - XrInstance instance, - XrSystemId systemId, - XrViewConfigurationType viewConfigurationType, - uint32_t viewCapacityInput, - uint32_t *viewCountOutput, - XrViewConfigurationView *views); +oxr_xrEnumerateViewConfigurationViews(XrInstance instance, + XrSystemId systemId, + XrViewConfigurationType viewConfigurationType, + uint32_t viewCapacityInput, + uint32_t *viewCountOutput, + XrViewConfigurationView *views); //! OpenXR API function @ep{xrEnumerateEnvironmentBlendModes} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrEnumerateEnvironmentBlendModes( - XrInstance instance, - XrSystemId systemId, - XrViewConfigurationType viewConfigurationType, - uint32_t environmentBlendModeCapacityInput, - uint32_t *environmentBlendModeCountOutput, - XrEnvironmentBlendMode *environmentBlendModes); +oxr_xrEnumerateEnvironmentBlendModes(XrInstance instance, + XrSystemId systemId, + XrViewConfigurationType viewConfigurationType, + uint32_t environmentBlendModeCapacityInput, + uint32_t *environmentBlendModeCountOutput, + XrEnvironmentBlendMode *environmentBlendModes); #ifdef XR_USE_GRAPHICS_API_OPENGL //! OpenXR API function @ep{xrGetOpenGLGraphicsRequirementsKHR} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetOpenGLGraphicsRequirementsKHR( - XrInstance instance, - XrSystemId systemId, - XrGraphicsRequirementsOpenGLKHR *graphicsRequirements); +oxr_xrGetOpenGLGraphicsRequirementsKHR(XrInstance instance, + XrSystemId systemId, + XrGraphicsRequirementsOpenGLKHR *graphicsRequirements); #endif #ifdef XR_USE_GRAPHICS_API_OPENGL_ES //! OpenXR API function @ep{xrGetOpenGLESGraphicsRequirementsKHR} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetOpenGLESGraphicsRequirementsKHR( - XrInstance instance, - XrSystemId systemId, - XrGraphicsRequirementsOpenGLESKHR *graphicsRequirements); +oxr_xrGetOpenGLESGraphicsRequirementsKHR(XrInstance instance, + XrSystemId systemId, + XrGraphicsRequirementsOpenGLESKHR *graphicsRequirements); #endif #ifdef XR_USE_GRAPHICS_API_VULKAN @@ -212,24 +187,21 @@ oxr_xrGetVulkanGraphicsDeviceKHR(XrInstance instance, //! OpenXR API function @ep{xrGetVulkanGraphicsDeviceKHR} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetVulkanGraphicsDevice2KHR( - XrInstance instance, - const XrVulkanGraphicsDeviceGetInfoKHR *getInfo, - VkPhysicalDevice *vkPhysicalDevice); +oxr_xrGetVulkanGraphicsDevice2KHR(XrInstance instance, + const XrVulkanGraphicsDeviceGetInfoKHR *getInfo, + VkPhysicalDevice *vkPhysicalDevice); //! OpenXR API function @ep{xrGetVulkanGraphicsRequirementsKHR} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetVulkanGraphicsRequirementsKHR( - XrInstance instance, - XrSystemId systemId, - XrGraphicsRequirementsVulkanKHR *graphicsRequirements); +oxr_xrGetVulkanGraphicsRequirementsKHR(XrInstance instance, + XrSystemId systemId, + XrGraphicsRequirementsVulkanKHR *graphicsRequirements); //! OpenXR API function @ep{xrGetVulkanGraphicsRequirements2KHR} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetVulkanGraphicsRequirements2KHR( - XrInstance instance, - XrSystemId systemId, - XrGraphicsRequirementsVulkan2KHR *graphicsRequirements); +oxr_xrGetVulkanGraphicsRequirements2KHR(XrInstance instance, + XrSystemId systemId, + XrGraphicsRequirementsVulkan2KHR *graphicsRequirements); //! OpenXR API function @ep{xrCreateVulkanInstanceKHR} XRAPI_ATTR XrResult XRAPI_CALL @@ -255,9 +227,7 @@ oxr_xrCreateVulkanDeviceKHR(XrInstance instance, //! OpenXR API function @ep{xrCreateSession} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrCreateSession(XrInstance instance, - const XrSessionCreateInfo *createInfo, - XrSession *session); +oxr_xrCreateSession(XrInstance instance, const XrSessionCreateInfo *createInfo, XrSession *session); //! OpenXR API function @ep{xrDestroySession} XRAPI_ATTR XrResult XRAPI_CALL @@ -273,9 +243,7 @@ oxr_xrEndSession(XrSession session); //! OpenXR API function @ep{xrWaitFrame} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrWaitFrame(XrSession session, - const XrFrameWaitInfo *frameWaitInfo, - XrFrameState *frameState); +oxr_xrWaitFrame(XrSession session, const XrFrameWaitInfo *frameWaitInfo, XrFrameState *frameState); //! OpenXR API function @ep{xrBeginFrame} XRAPI_ATTR XrResult XRAPI_CALL @@ -319,12 +287,11 @@ oxr_xrPerfSettingsSetPerformanceLevelEXT(XrSession session, #ifdef OXR_HAVE_EXT_thermal_query //! OpenXR API function @ep{xrThermalGetTemperatureTrendEXT} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrThermalGetTemperatureTrendEXT( - XrSession session, - XrPerfSettingsDomainEXT domain, - XrPerfSettingsNotificationLevelEXT *notificationLevel, - float *tempHeadroom, - float *tempSlope); +oxr_xrThermalGetTemperatureTrendEXT(XrSession session, + XrPerfSettingsDomainEXT domain, + XrPerfSettingsNotificationLevelEXT *notificationLevel, + float *tempHeadroom, + float *tempSlope); #endif // OXR_HAVE_EXT_thermal_query @@ -343,22 +310,15 @@ oxr_xrEnumerateReferenceSpaces(XrSession session, //! OpenXR API function @ep{xrGetReferenceSpaceBoundsRect} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetReferenceSpaceBoundsRect(XrSession session, - XrReferenceSpaceType referenceSpaceType, - XrExtent2Df *bounds); +oxr_xrGetReferenceSpaceBoundsRect(XrSession session, XrReferenceSpaceType referenceSpaceType, XrExtent2Df *bounds); //! OpenXR API function @ep{xrCreateReferenceSpace} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrCreateReferenceSpace(XrSession session, - const XrReferenceSpaceCreateInfo *createInfo, - XrSpace *space); +oxr_xrCreateReferenceSpace(XrSession session, const XrReferenceSpaceCreateInfo *createInfo, XrSpace *space); //! OpenXR API function @ep{xrLocateSpace} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrLocateSpace(XrSpace space, - XrSpace baseSpace, - XrTime time, - XrSpaceLocation *location); +oxr_xrLocateSpace(XrSpace space, XrSpace baseSpace, XrTime time, XrSpaceLocation *location); //! OpenXR API function @ep{xrDestroySpace} XRAPI_ATTR XrResult XRAPI_CALL @@ -380,9 +340,7 @@ oxr_xrEnumerateSwapchainFormats(XrSession session, //! OpenXR API function @ep{xrCreateSwapchain} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrCreateSwapchain(XrSession session, - const XrSwapchainCreateInfo *createInfo, - XrSwapchain *swapchain); +oxr_xrCreateSwapchain(XrSession session, const XrSwapchainCreateInfo *createInfo, XrSwapchain *swapchain); //! OpenXR API function @ep{xrDestroySwapchain} XRAPI_ATTR XrResult XRAPI_CALL @@ -397,19 +355,15 @@ oxr_xrEnumerateSwapchainImages(XrSwapchain swapchain, //! OpenXR API function @ep{xrAcquireSwapchainImage} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrAcquireSwapchainImage(XrSwapchain swapchain, - const XrSwapchainImageAcquireInfo *acquireInfo, - uint32_t *index); +oxr_xrAcquireSwapchainImage(XrSwapchain swapchain, const XrSwapchainImageAcquireInfo *acquireInfo, uint32_t *index); //! OpenXR API function @ep{xrWaitSwapchainImage} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrWaitSwapchainImage(XrSwapchain swapchain, - const XrSwapchainImageWaitInfo *waitInfo); +oxr_xrWaitSwapchainImage(XrSwapchain swapchain, const XrSwapchainImageWaitInfo *waitInfo); //! OpenXR API function @ep{xrReleaseSwapchainImage} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrReleaseSwapchainImage(XrSwapchain swapchain, - const XrSwapchainImageReleaseInfo *releaseInfo); +oxr_xrReleaseSwapchainImage(XrSwapchain swapchain, const XrSwapchainImageReleaseInfo *releaseInfo); /* @@ -420,15 +374,13 @@ oxr_xrReleaseSwapchainImage(XrSwapchain swapchain, //! OpenXR API function @ep{xrSetDebugUtilsObjectNameEXT} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrSetDebugUtilsObjectNameEXT(XrInstance instance, - const XrDebugUtilsObjectNameInfoEXT *nameInfo); +oxr_xrSetDebugUtilsObjectNameEXT(XrInstance instance, const XrDebugUtilsObjectNameInfoEXT *nameInfo); //! OpenXR API function @ep{xrCreateDebugUtilsMessengerEXT} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrCreateDebugUtilsMessengerEXT( - XrInstance instance, - const XrDebugUtilsMessengerCreateInfoEXT *createInfo, - XrDebugUtilsMessengerEXT *messenger); +oxr_xrCreateDebugUtilsMessengerEXT(XrInstance instance, + const XrDebugUtilsMessengerCreateInfoEXT *createInfo, + XrDebugUtilsMessengerEXT *messenger); //! OpenXR API function @ep{xrDestroyDebugUtilsMessengerEXT} XRAPI_ATTR XrResult XRAPI_CALL @@ -436,16 +388,14 @@ oxr_xrDestroyDebugUtilsMessengerEXT(XrDebugUtilsMessengerEXT messenger); //! OpenXR API function @ep{xrSubmitDebugUtilsMessageEXT} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrSubmitDebugUtilsMessageEXT( - XrInstance instance, - XrDebugUtilsMessageSeverityFlagsEXT messageSeverity, - XrDebugUtilsMessageTypeFlagsEXT messageTypes, - const XrDebugUtilsMessengerCallbackDataEXT *callbackData); +oxr_xrSubmitDebugUtilsMessageEXT(XrInstance instance, + XrDebugUtilsMessageSeverityFlagsEXT messageSeverity, + XrDebugUtilsMessageTypeFlagsEXT messageTypes, + const XrDebugUtilsMessengerCallbackDataEXT *callbackData); //! OpenXR API function @ep{xrSessionBeginDebugUtilsLabelRegionEXT} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrSessionBeginDebugUtilsLabelRegionEXT( - XrSession session, const XrDebugUtilsLabelEXT *labelInfo); +oxr_xrSessionBeginDebugUtilsLabelRegionEXT(XrSession session, const XrDebugUtilsLabelEXT *labelInfo); //! OpenXR API function @ep{xrSessionEndDebugUtilsLabelRegionEXT} XRAPI_ATTR XrResult XRAPI_CALL @@ -453,8 +403,7 @@ oxr_xrSessionEndDebugUtilsLabelRegionEXT(XrSession session); //! OpenXR API function @ep{xrSessionInsertDebugUtilsLabelEXT} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrSessionInsertDebugUtilsLabelEXT(XrSession session, - const XrDebugUtilsLabelEXT *labelInfo); +oxr_xrSessionInsertDebugUtilsLabelEXT(XrSession session, const XrDebugUtilsLabelEXT *labelInfo); /* @@ -465,15 +414,11 @@ oxr_xrSessionInsertDebugUtilsLabelEXT(XrSession session, //! OpenXR API function @ep{xrCreateActionSpace} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrCreateActionSpace(XrSession session, - const XrActionSpaceCreateInfo *createInfo, - XrSpace *space); +oxr_xrCreateActionSpace(XrSession session, const XrActionSpaceCreateInfo *createInfo, XrSpace *space); //! OpenXR API function @ep{xrCreateActionSet} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrCreateActionSet(XrInstance instance, - const XrActionSetCreateInfo *createInfo, - XrActionSet *actionSet); +oxr_xrCreateActionSet(XrInstance instance, const XrActionSetCreateInfo *createInfo, XrActionSet *actionSet); //! OpenXR API function @ep{xrDestroyActionSet} XRAPI_ATTR XrResult XRAPI_CALL @@ -481,9 +426,7 @@ oxr_xrDestroyActionSet(XrActionSet actionSet); //! OpenXR API function @ep{xrCreateAction} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrCreateAction(XrActionSet actionSet, - const XrActionCreateInfo *createInfo, - XrAction *action); +oxr_xrCreateAction(XrActionSet actionSet, const XrActionCreateInfo *createInfo, XrAction *action); //! OpenXR API function @ep{xrDestroyAction} XRAPI_ATTR XrResult XRAPI_CALL @@ -491,45 +434,34 @@ oxr_xrDestroyAction(XrAction action); //! OpenXR API function @ep{xrSuggestInteractionProfileBindings} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrSuggestInteractionProfileBindings( - XrInstance instance, - const XrInteractionProfileSuggestedBinding *suggestedBindings); +oxr_xrSuggestInteractionProfileBindings(XrInstance instance, + const XrInteractionProfileSuggestedBinding *suggestedBindings); //! OpenXR API function @ep{xrAttachSessionActionSets} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrAttachSessionActionSets(XrSession session, - const XrSessionActionSetsAttachInfo *bindInfo); +oxr_xrAttachSessionActionSets(XrSession session, const XrSessionActionSetsAttachInfo *bindInfo); //! OpenXR API function @ep{xrGetCurrentInteractionProfile} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetCurrentInteractionProfile( - XrSession session, - XrPath topLevelUserPath, - XrInteractionProfileState *interactionProfile); +oxr_xrGetCurrentInteractionProfile(XrSession session, + XrPath topLevelUserPath, + XrInteractionProfileState *interactionProfile); //! OpenXR API function @ep{xrGetActionStateBoolean} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetActionStateBoolean(XrSession session, - const XrActionStateGetInfo *getInfo, - XrActionStateBoolean *data); +oxr_xrGetActionStateBoolean(XrSession session, const XrActionStateGetInfo *getInfo, XrActionStateBoolean *data); //! OpenXR API function @ep{xrGetActionStateFloat} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetActionStateFloat(XrSession session, - const XrActionStateGetInfo *getInfo, - XrActionStateFloat *data); +oxr_xrGetActionStateFloat(XrSession session, const XrActionStateGetInfo *getInfo, XrActionStateFloat *data); //! OpenXR API function @ep{xrGetActionStateVector2f} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetActionStateVector2f(XrSession session, - const XrActionStateGetInfo *getInfo, - XrActionStateVector2f *data); +oxr_xrGetActionStateVector2f(XrSession session, const XrActionStateGetInfo *getInfo, XrActionStateVector2f *data); //! OpenXR API function @ep{xrGetActionStatePose} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetActionStatePose(XrSession session, - const XrActionStateGetInfo *getInfo, - XrActionStatePose *data); +oxr_xrGetActionStatePose(XrSession session, const XrActionStateGetInfo *getInfo, XrActionStatePose *data); //! OpenXR API function @ep{xrSyncActions} XRAPI_ATTR XrResult XRAPI_CALL @@ -537,21 +469,19 @@ oxr_xrSyncActions(XrSession session, const XrActionsSyncInfo *syncInfo); //! OpenXR API function @ep{xrEnumerateBoundSourcesForAction} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrEnumerateBoundSourcesForAction( - XrSession session, - const XrBoundSourcesForActionEnumerateInfo *enumerateInfo, - uint32_t sourceCapacityInput, - uint32_t *sourceCountOutput, - XrPath *sources); +oxr_xrEnumerateBoundSourcesForAction(XrSession session, + const XrBoundSourcesForActionEnumerateInfo *enumerateInfo, + uint32_t sourceCapacityInput, + uint32_t *sourceCountOutput, + XrPath *sources); //! OpenXR API function @ep{xrGetInputSourceLocalizedName} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrGetInputSourceLocalizedName( - XrSession session, - const XrInputSourceLocalizedNameGetInfo *getInfo, - uint32_t bufferCapacityInput, - uint32_t *bufferCountOutput, - char *buffer); +oxr_xrGetInputSourceLocalizedName(XrSession session, + const XrInputSourceLocalizedNameGetInfo *getInfo, + uint32_t bufferCapacityInput, + uint32_t *bufferCountOutput, + char *buffer); //! OpenXR API function @ep{xrApplyHapticFeedback} XRAPI_ATTR XrResult XRAPI_CALL @@ -561,8 +491,7 @@ oxr_xrApplyHapticFeedback(XrSession session, //! OpenXR API function @ep{xrStopHapticFeedback} XRAPI_ATTR XrResult XRAPI_CALL -oxr_xrStopHapticFeedback(XrSession session, - const XrHapticActionInfo *hapticActionInfo); +oxr_xrStopHapticFeedback(XrSession session, const XrHapticActionInfo *hapticActionInfo); //! OpenXR API function @ep{xrCreateHandTrackerEXT} XRAPI_ATTR XrResult XRAPI_CALL diff --git a/src/xrt/state_trackers/oxr/oxr_api_instance.c b/src/xrt/state_trackers/oxr/oxr_api_instance.c index 76448c090..02bda85f1 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_instance.c +++ b/src/xrt/state_trackers/oxr/oxr_api_instance.c @@ -29,11 +29,9 @@ #include -#define MAKE_EXTENSION_PROPERTIES(mixed_case, all_caps) \ - {XR_TYPE_EXTENSION_PROPERTIES, NULL, XR_##all_caps##_EXTENSION_NAME, \ - XR_##mixed_case##_SPEC_VERSION}, -static const XrExtensionProperties extension_properties[] = { - OXR_EXTENSION_SUPPORT_GENERATE(MAKE_EXTENSION_PROPERTIES)}; +#define MAKE_EXTENSION_PROPERTIES(mixed_case, all_caps) \ + {XR_TYPE_EXTENSION_PROPERTIES, NULL, XR_##all_caps##_EXTENSION_NAME, XR_##mixed_case##_SPEC_VERSION}, +static const XrExtensionProperties extension_properties[] = {OXR_EXTENSION_SUPPORT_GENERATE(MAKE_EXTENSION_PROPERTIES)}; XrResult oxr_xrEnumerateInstanceExtensionProperties(const char *layerName, @@ -44,48 +42,39 @@ oxr_xrEnumerateInstanceExtensionProperties(const char *layerName, struct oxr_logger log; oxr_log_init(&log, "xrEnumerateInstanceExtensionProperties"); - OXR_TWO_CALL_HELPER(&log, propertyCapacityInput, propertyCountOutput, - properties, ARRAY_SIZE(extension_properties), - extension_properties, XR_SUCCESS); + OXR_TWO_CALL_HELPER(&log, propertyCapacityInput, propertyCountOutput, properties, + ARRAY_SIZE(extension_properties), extension_properties, XR_SUCCESS); } #ifdef XRT_OS_ANDROID static XrResult -oxr_check_android_extensions(struct oxr_logger *log, - const XrInstanceCreateInfo *createInfo) +oxr_check_android_extensions(struct oxr_logger *log, const XrInstanceCreateInfo *createInfo) { bool foundAndroidExtension = false; for (uint32_t i = 0; i < createInfo->enabledExtensionCount; ++i) { - if (strcmp(createInfo->enabledExtensionNames[i], - XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME) == - 0) { + if (strcmp(createInfo->enabledExtensionNames[i], XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME) == 0) { foundAndroidExtension = true; break; } } if (!foundAndroidExtension) { - return oxr_error( - log, XR_ERROR_INITIALIZATION_FAILED, - "(createInfo->enabledExtensionNames) " - "Mandatory platform-specific " - "extension" - " " XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME - " not specified"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, + "(createInfo->enabledExtensionNames) " + "Mandatory platform-specific " + "extension" + " " XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME " not specified"); } { // Verify that it exists and is populated. - XrInstanceCreateInfoAndroidKHR const *createInfoAndroid = - OXR_GET_INPUT_FROM_CHAIN( - createInfo, XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR, - XrInstanceCreateInfoAndroidKHR); + XrInstanceCreateInfoAndroidKHR const *createInfoAndroid = OXR_GET_INPUT_FROM_CHAIN( + createInfo, XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR, XrInstanceCreateInfoAndroidKHR); if (createInfoAndroid == NULL) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(createInfo->next...) " - "Did not find XrInstanceCreateInfoAndroidKHR in " - "chain"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(createInfo->next...) " + "Did not find XrInstanceCreateInfoAndroidKHR in " + "chain"); } if (createInfoAndroid->applicationVM == NULL) { return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, @@ -93,10 +82,9 @@ oxr_check_android_extensions(struct oxr_logger *log, "applicationVM must be populated"); } if (createInfoAndroid->applicationActivity == NULL) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(createInfo->next...->applicationActivity) " - "applicationActivity must be populated"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(createInfo->next...->applicationActivity) " + "applicationActivity must be populated"); } } return XR_SUCCESS; @@ -104,49 +92,42 @@ oxr_check_android_extensions(struct oxr_logger *log, #endif // XRT_OS_ANDROID XrResult -oxr_xrCreateInstance(const XrInstanceCreateInfo *createInfo, - XrInstance *out_instance) +oxr_xrCreateInstance(const XrInstanceCreateInfo *createInfo, XrInstance *out_instance) { XrResult ret; struct oxr_logger log; oxr_log_init(&log, "xrCreateInstance"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, - XR_TYPE_INSTANCE_CREATE_INFO); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_INSTANCE_CREATE_INFO); const uint32_t major = XR_VERSION_MAJOR(XR_CURRENT_API_VERSION); const uint32_t minor = XR_VERSION_MINOR(XR_CURRENT_API_VERSION); #if 0 const uint32_t patch = XR_VERSION_PATCH(XR_CURRENT_API_VERSION); #endif - if (createInfo->applicationInfo.apiVersion < - XR_MAKE_VERSION(major, minor, 0)) { - return oxr_error( - &log, XR_ERROR_API_VERSION_UNSUPPORTED, - "(createInfo->applicationInfo.apiVersion) " - "Cannot satisfy request for version less than %d.%d.%d", - major, minor, 0); + if (createInfo->applicationInfo.apiVersion < XR_MAKE_VERSION(major, minor, 0)) { + return oxr_error(&log, XR_ERROR_API_VERSION_UNSUPPORTED, + "(createInfo->applicationInfo.apiVersion) " + "Cannot satisfy request for version less than %d.%d.%d", + major, minor, 0); } /* * This is a slight fib, to let us approximately run things between 1.0 * and 2.0 */ - if (createInfo->applicationInfo.apiVersion >= - XR_MAKE_VERSION(2, 0, 0)) { - return oxr_error( - &log, XR_ERROR_API_VERSION_UNSUPPORTED, - "(createInfo->applicationInfo.apiVersion) " - "Cannot satisfy request for version: too high"); + if (createInfo->applicationInfo.apiVersion >= XR_MAKE_VERSION(2, 0, 0)) { + return oxr_error(&log, XR_ERROR_API_VERSION_UNSUPPORTED, + "(createInfo->applicationInfo.apiVersion) " + "Cannot satisfy request for version: too high"); } /* * Check that all extension names are recognized, so oxr_instance_create * doesn't need to check for bad extension names. */ -#define CHECK_EXT_NAME(mixed_case, all_caps) \ - if (strcmp(createInfo->enabledExtensionNames[i], \ - XR_##all_caps##_EXTENSION_NAME) == 0) { \ - continue; \ +#define CHECK_EXT_NAME(mixed_case, all_caps) \ + if (strcmp(createInfo->enabledExtensionNames[i], XR_##all_caps##_EXTENSION_NAME) == 0) { \ + continue; \ } for (uint32_t i = 0; i < createInfo->enabledExtensionCount; ++i) { OXR_EXTENSION_SUPPORT_GENERATE(CHECK_EXT_NAME) @@ -181,20 +162,17 @@ oxr_xrDestroyInstance(XrInstance instance) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrDestroyInstance"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrDestroyInstance"); return oxr_handle_destroy(&log, &inst->handle); } XrResult -oxr_xrGetInstanceProperties(XrInstance instance, - XrInstanceProperties *instanceProperties) +oxr_xrGetInstanceProperties(XrInstance instance, XrInstanceProperties *instanceProperties) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetInstanceProperties"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetInstanceProperties"); return oxr_instance_get_properties(&log, inst, instanceProperties); } @@ -211,22 +189,19 @@ oxr_xrPollEvent(XrInstance instance, XrEventDataBuffer *eventData) } XrResult -oxr_xrResultToString(XrInstance instance, - XrResult value, - char buffer[XR_MAX_RESULT_STRING_SIZE]) +oxr_xrResultToString(XrInstance instance, XrResult value, char buffer[XR_MAX_RESULT_STRING_SIZE]) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrResultToString"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrResultToString"); -#define MAKE_RESULT_CASE(VAL, _) \ +#define MAKE_RESULT_CASE(VAL, _) \ case VAL: strncpy(buffer, #VAL, XR_MAX_RESULT_STRING_SIZE); break; switch (value) { XR_LIST_ENUM_XrResult(MAKE_RESULT_CASE); default: - snprintf(buffer, XR_MAX_RESULT_STRING_SIZE, "XR_UNKNOWN_%s_%d", - value < 0 ? "FAILURE" : "SUCCESS", value); + snprintf(buffer, XR_MAX_RESULT_STRING_SIZE, "XR_UNKNOWN_%s_%d", value < 0 ? "FAILURE" : "SUCCESS", + value); } buffer[XR_MAX_RESULT_STRING_SIZE - 1] = '\0'; @@ -234,22 +209,17 @@ oxr_xrResultToString(XrInstance instance, } XrResult -oxr_xrStructureTypeToString(XrInstance instance, - XrStructureType value, - char buffer[XR_MAX_STRUCTURE_NAME_SIZE]) +oxr_xrStructureTypeToString(XrInstance instance, XrStructureType value, char buffer[XR_MAX_STRUCTURE_NAME_SIZE]) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrStructureTypeToString"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrStructureTypeToString"); -#define MAKE_TYPE_CASE(VAL, _) \ +#define MAKE_TYPE_CASE(VAL, _) \ case VAL: strncpy(buffer, #VAL, XR_MAX_RESULT_STRING_SIZE); break; switch (value) { XR_LIST_ENUM_XrStructureType(MAKE_TYPE_CASE); - default: - snprintf(buffer, XR_MAX_RESULT_STRING_SIZE, - "XR_UNKNOWN_STRUCTURE_TYPE_%d", value); + default: snprintf(buffer, XR_MAX_RESULT_STRING_SIZE, "XR_UNKNOWN_STRUCTURE_TYPE_%d", value); } buffer[XR_MAX_RESULT_STRING_SIZE - 1] = '\0'; @@ -257,24 +227,20 @@ oxr_xrStructureTypeToString(XrInstance instance, } XrResult -oxr_xrStringToPath(XrInstance instance, - const char *pathString, - XrPath *out_path) +oxr_xrStringToPath(XrInstance instance, const char *pathString, XrPath *out_path) { struct oxr_instance *inst; struct oxr_logger log; XrResult ret; XrPath path; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrStringToPath"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrStringToPath"); ret = oxr_verify_full_path_c(&log, pathString, "pathString"); if (ret != XR_SUCCESS) { return ret; } - ret = oxr_path_get_or_create(&log, inst, pathString, strlen(pathString), - &path); + ret = oxr_path_get_or_create(&log, inst, pathString, strlen(pathString), &path); if (ret != XR_SUCCESS) { return ret; } @@ -285,11 +251,8 @@ oxr_xrStringToPath(XrInstance instance, } XrResult -oxr_xrPathToString(XrInstance instance, - XrPath path, - uint32_t bufferCapacityInput, - uint32_t *bufferCountOutput, - char *buffer) +oxr_xrPathToString( + XrInstance instance, XrPath path, uint32_t bufferCapacityInput, uint32_t *bufferCountOutput, char *buffer) { struct oxr_instance *inst; struct oxr_logger log; @@ -297,11 +260,9 @@ oxr_xrPathToString(XrInstance instance, size_t length; XrResult ret; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrPathToString"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrPathToString"); if (path == XR_NULL_PATH) { - return oxr_error(&log, XR_ERROR_PATH_INVALID, - "(path == XR_NULL_PATH)"); + return oxr_error(&log, XR_ERROR_PATH_INVALID, "(path == XR_NULL_PATH)"); } ret = oxr_path_get_string(&log, inst, path, &str, &length); @@ -312,8 +273,7 @@ oxr_xrPathToString(XrInstance instance, // Length is the number of valid characters, not including the // null termination character (but a extra null byte is always // reserved). - OXR_TWO_CALL_HELPER(&log, bufferCapacityInput, bufferCountOutput, - buffer, length + 1, str, XR_SUCCESS); + OXR_TWO_CALL_HELPER(&log, bufferCapacityInput, bufferCountOutput, buffer, length + 1, str, XR_SUCCESS); return XR_SUCCESS; } @@ -321,43 +281,33 @@ oxr_xrPathToString(XrInstance instance, // ---- XR_KHR_convert_timespec_time extension #ifdef XR_USE_TIMESPEC XrResult -oxr_xrConvertTimespecTimeToTimeKHR(XrInstance instance, - const struct timespec *timespecTime, - XrTime *time) +oxr_xrConvertTimespecTimeToTimeKHR(XrInstance instance, const struct timespec *timespecTime, XrTime *time) { //! @todo do we need to check and see if this extension was //! enabled first? struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrConvertTimespecTimeToTimeKHR"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrConvertTimespecTimeToTimeKHR"); OXR_VERIFY_EXTENSION(&log, inst, KHR_convert_timespec_time); OXR_VERIFY_ARG_NOT_NULL(&log, timespecTime); OXR_VERIFY_ARG_NOT_NULL(&log, time); - return oxr_instance_convert_timespec_to_time(&log, inst, timespecTime, - time); + return oxr_instance_convert_timespec_to_time(&log, inst, timespecTime, time); } XrResult -oxr_xrConvertTimeToTimespecTimeKHR(XrInstance instance, - XrTime time, - struct timespec *timespecTime) +oxr_xrConvertTimeToTimespecTimeKHR(XrInstance instance, XrTime time, struct timespec *timespecTime) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrConvertTimeToTimespecTimeKHR"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrConvertTimeToTimespecTimeKHR"); OXR_VERIFY_EXTENSION(&log, inst, KHR_convert_timespec_time); OXR_VERIFY_ARG_NOT_NULL(&log, timespecTime); if (time <= (XrTime)0) { - return oxr_error(&log, XR_ERROR_TIME_INVALID, - "(time == %" PRIi64 ") is not a valid time.", - time); + return oxr_error(&log, XR_ERROR_TIME_INVALID, "(time == %" PRIi64 ") is not a valid time.", time); } - return oxr_instance_convert_time_to_timespec(&log, inst, time, - timespecTime); + return oxr_instance_convert_time_to_timespec(&log, inst, time, timespecTime); } #endif // XR_USE_TIMESPEC diff --git a/src/xrt/state_trackers/oxr/oxr_api_negotiate.c b/src/xrt/state_trackers/oxr/oxr_api_negotiate.c index b7bea3033..91b27ab73 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_negotiate.c +++ b/src/xrt/state_trackers/oxr/oxr_api_negotiate.c @@ -25,24 +25,22 @@ DEBUG_GET_ONCE_BOOL_OPTION(negotiate, "OXR_DEBUG_NEGOTIATE", false) -#define PRINT_NEGOTIATE(...) \ - do { \ - if (debug_get_bool_option_negotiate()) { \ - fprintf(stderr, __VA_ARGS__); \ - } \ +#define PRINT_NEGOTIATE(...) \ + do { \ + if (debug_get_bool_option_negotiate()) { \ + fprintf(stderr, __VA_ARGS__); \ + } \ } while (false) #ifdef _WIN32 __declspec(dllexport) XRAPI_ATTR XrResult XRAPI_CALL - xrNegotiateLoaderRuntimeInterface( - const XrNegotiateLoaderInfo *loaderInfo, - XrNegotiateRuntimeRequest *runtimeRequest); + xrNegotiateLoaderRuntimeInterface(const XrNegotiateLoaderInfo *loaderInfo, + XrNegotiateRuntimeRequest *runtimeRequest); #endif XRAPI_ATTR XrResult XRAPI_CALL -xrNegotiateLoaderRuntimeInterface(const XrNegotiateLoaderInfo *loaderInfo, - XrNegotiateRuntimeRequest *runtimeRequest) +xrNegotiateLoaderRuntimeInterface(const XrNegotiateLoaderInfo *loaderInfo, XrNegotiateRuntimeRequest *runtimeRequest) { PRINT_NEGOTIATE("xrNegotiateLoaderRuntimeInterface\n"); @@ -55,10 +53,8 @@ xrNegotiateLoaderRuntimeInterface(const XrNegotiateLoaderInfo *loaderInfo, } // Make sure that we understand the structs passed to this function. - if (runtimeRequest->structType != - XR_LOADER_INTERFACE_STRUCT_RUNTIME_REQUEST || - runtimeRequest->structVersion != - XR_CURRENT_LOADER_RUNTIME_VERSION || + if (runtimeRequest->structType != XR_LOADER_INTERFACE_STRUCT_RUNTIME_REQUEST || + runtimeRequest->structVersion != XR_CURRENT_LOADER_RUNTIME_VERSION || runtimeRequest->structSize != sizeof(XrNegotiateRuntimeRequest)) { PRINT_NEGOTIATE("\truntimeRequest bad!\n"); return XR_ERROR_INITIALIZATION_FAILED; @@ -70,8 +66,7 @@ xrNegotiateLoaderRuntimeInterface(const XrNegotiateLoaderInfo *loaderInfo, uint32_t requested_min_major = loaderInfo->minInterfaceVersion; uint32_t requested_max_major = loaderInfo->maxInterfaceVersion; - if (supported_major > requested_max_major || - supported_major < requested_min_major) { + if (supported_major > requested_max_major || supported_major < requested_min_major) { PRINT_NEGOTIATE( "\tXRT - OpenXR doesn't support requested version %d <= " "%d <= %d\n", @@ -80,8 +75,7 @@ xrNegotiateLoaderRuntimeInterface(const XrNegotiateLoaderInfo *loaderInfo, } runtimeRequest->getInstanceProcAddr = oxr_xrGetInstanceProcAddr; - runtimeRequest->runtimeInterfaceVersion = - XR_CURRENT_LOADER_RUNTIME_VERSION; + runtimeRequest->runtimeInterfaceVersion = XR_CURRENT_LOADER_RUNTIME_VERSION; runtimeRequest->runtimeApiVersion = XR_CURRENT_API_VERSION; PRINT_NEGOTIATE("\tall ok!\n"); @@ -110,13 +104,13 @@ oxr_xrEnumerateApiLayerProperties(uint32_t propertyCapacityInput, * * Use for functions that should be unconditionally available. */ -#define ENTRY(funcName) \ - do { \ - if (strcmp(name, #funcName) == 0) { \ - PFN_##funcName ret = &oxr_##funcName; \ - *out_function = (PFN_xrVoidFunction)(ret); \ - return XR_SUCCESS; \ - } \ +#define ENTRY(funcName) \ + do { \ + if (strcmp(name, #funcName) == 0) { \ + PFN_##funcName ret = &oxr_##funcName; \ + *out_function = (PFN_xrVoidFunction)(ret); \ + return XR_SUCCESS; \ + } \ } while (false) /*! @@ -125,16 +119,16 @@ oxr_xrEnumerateApiLayerProperties(uint32_t propertyCapacityInput, * * Checks the extra condition to e.g. find out if the extension is enabled */ -#define ENTRY_IF(funcName, extraCondition, message) \ - do { \ - if (strcmp(name, #funcName) == 0) { \ - if (extraCondition) { \ - PFN_##funcName ret = &oxr_##funcName; \ - *out_function = (PFN_xrVoidFunction)(ret); \ - return XR_SUCCESS; \ - } \ - return XR_ERROR_FUNCTION_UNSUPPORTED; \ - } \ +#define ENTRY_IF(funcName, extraCondition, message) \ + do { \ + if (strcmp(name, #funcName) == 0) { \ + if (extraCondition) { \ + PFN_##funcName ret = &oxr_##funcName; \ + *out_function = (PFN_xrVoidFunction)(ret); \ + return XR_SUCCESS; \ + } \ + return XR_ERROR_FUNCTION_UNSUPPORTED; \ + } \ } while (false) /*! @@ -146,17 +140,13 @@ oxr_xrEnumerateApiLayerProperties(uint32_t propertyCapacityInput, * Pass the function name and the (mixed-case) extension name without the * leading XR_. */ -#define ENTRY_IF_EXT(funcName, short_ext_name) \ - ENTRY_IF(funcName, inst->extensions.short_ext_name, \ - "Required extension XR_" #short_ext_name " not enabled") +#define ENTRY_IF_EXT(funcName, short_ext_name) \ + ENTRY_IF(funcName, inst->extensions.short_ext_name, "Required extension XR_" #short_ext_name " not enabled") /*! * Handle a non-null instance pointer. */ static XrResult -handle_non_null(struct oxr_instance *inst, - struct oxr_logger *log, - const char *name, - PFN_xrVoidFunction *out_function) +handle_non_null(struct oxr_instance *inst, struct oxr_logger *log, const char *name, PFN_xrVoidFunction *out_function) { ENTRY(xrGetInstanceProcAddr); ENTRY(xrEnumerateInstanceExtensionProperties); @@ -223,8 +213,7 @@ handle_non_null(struct oxr_instance *inst, #endif // OXR_HAVE_KHR_convert_timespec_time #ifdef OXR_HAVE_EXT_performance_settings - ENTRY_IF_EXT(xrPerfSettingsSetPerformanceLevelEXT, - EXT_performance_settings); + ENTRY_IF_EXT(xrPerfSettingsSetPerformanceLevelEXT, EXT_performance_settings); #endif // OXR_HAVE_EXT_performance_settings #ifdef OXR_HAVE_EXT_thermal_query @@ -252,8 +241,7 @@ handle_non_null(struct oxr_instance *inst, #endif // OXR_HAVE_KHR_opengl_enable #ifdef OXR_HAVE_KHR_opengl_es_enable - ENTRY_IF_EXT(xrGetOpenGLESGraphicsRequirementsKHR, - KHR_opengl_es_enable); + ENTRY_IF_EXT(xrGetOpenGLESGraphicsRequirementsKHR, KHR_opengl_es_enable); #endif // OXR_HAVE_KHR_opengl_es_enable #ifdef OXR_HAVE_KHR_vulkan_enable @@ -282,9 +270,7 @@ handle_non_null(struct oxr_instance *inst, * Special case a null instance pointer. */ static XrResult -handle_null(struct oxr_logger *log, - const char *name, - PFN_xrVoidFunction *out_function) +handle_null(struct oxr_logger *log, const char *name, PFN_xrVoidFunction *out_function) { ENTRY(xrCreateInstance); ENTRY(xrEnumerateInstanceExtensionProperties); @@ -294,14 +280,11 @@ handle_null(struct oxr_logger *log, * This is fine to log, since there should not be other * null-instance calls. */ - return oxr_error(log, XR_ERROR_FUNCTION_UNSUPPORTED, "(name = \"%s\")", - name); + return oxr_error(log, XR_ERROR_FUNCTION_UNSUPPORTED, "(name = \"%s\")", name); } XrResult -oxr_xrGetInstanceProcAddr(XrInstance instance, - const char *name, - PFN_xrVoidFunction *function) +oxr_xrGetInstanceProcAddr(XrInstance instance, const char *name, PFN_xrVoidFunction *function) { struct oxr_logger log; @@ -314,7 +297,6 @@ oxr_xrGetInstanceProcAddr(XrInstance instance, } struct oxr_instance *inst; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetInstanceProcAddr"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetInstanceProcAddr"); return handle_non_null(inst, &log, name, function); } diff --git a/src/xrt/state_trackers/oxr/oxr_api_session.c b/src/xrt/state_trackers/oxr/oxr_api_session.c index 4247e78c8..aa0699ca5 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_session.c +++ b/src/xrt/state_trackers/oxr/oxr_api_session.c @@ -26,16 +26,13 @@ #include "oxr_chain.h" XrResult -oxr_xrCreateSession(XrInstance instance, - const XrSessionCreateInfo *createInfo, - XrSession *out_session) +oxr_xrCreateSession(XrInstance instance, const XrSessionCreateInfo *createInfo, XrSession *out_session) { XrResult ret; struct oxr_instance *inst; struct oxr_session *sess, **link; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrCreateSession"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrCreateSession"); ret = oxr_verify_XrSessionCreateInfo(&log, inst, createInfo); if (ret != XR_SUCCESS) { @@ -65,8 +62,7 @@ oxr_xrDestroySession(XrSession session) struct oxr_session *sess, **link; struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrDestroySession"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrDestroySession"); /* Remove from session list */ inst = sess->sys->inst; @@ -85,10 +81,8 @@ oxr_xrBeginSession(XrSession session, const XrSessionBeginInfo *beginInfo) struct oxr_session *sess; struct oxr_logger log; OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrBeginSession"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, beginInfo, - XR_TYPE_SESSION_BEGIN_INFO); - OXR_VERIFY_VIEW_CONFIG_TYPE(&log, sess->sys->inst, - beginInfo->primaryViewConfigurationType); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, beginInfo, XR_TYPE_SESSION_BEGIN_INFO); + OXR_VERIFY_VIEW_CONFIG_TYPE(&log, sess->sys->inst, beginInfo->primaryViewConfigurationType); return oxr_session_begin(&log, sess, beginInfo); } @@ -104,15 +98,12 @@ oxr_xrEndSession(XrSession session) } XrResult -oxr_xrWaitFrame(XrSession session, - const XrFrameWaitInfo *frameWaitInfo, - XrFrameState *frameState) +oxr_xrWaitFrame(XrSession session, const XrFrameWaitInfo *frameWaitInfo, XrFrameState *frameState) { struct oxr_session *sess; struct oxr_logger log; OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrWaitFrame"); - OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(&log, frameWaitInfo, - XR_TYPE_FRAME_WAIT_INFO); + OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(&log, frameWaitInfo, XR_TYPE_FRAME_WAIT_INFO); OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, frameState, XR_TYPE_FRAME_STATE); OXR_VERIFY_ARG_NOT_NULL(&log, frameState); @@ -126,8 +117,7 @@ oxr_xrBeginFrame(XrSession session, const XrFrameBeginInfo *frameBeginInfo) struct oxr_logger log; OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrBeginFrame"); // NULL explicitly allowed here because it's a basically empty struct. - OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(&log, frameBeginInfo, - XR_TYPE_FRAME_BEGIN_INFO); + OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(&log, frameBeginInfo, XR_TYPE_FRAME_BEGIN_INFO); return oxr_session_frame_begin(&log, sess); } @@ -138,8 +128,7 @@ oxr_xrEndFrame(XrSession session, const XrFrameEndInfo *frameEndInfo) struct oxr_session *sess; struct oxr_logger log; OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrEndFrame"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, frameEndInfo, - XR_TYPE_FRAME_END_INFO); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, frameEndInfo, XR_TYPE_FRAME_END_INFO); return oxr_session_frame_end(&log, sess, frameEndInfo); } @@ -149,8 +138,7 @@ oxr_xrRequestExitSession(XrSession session) { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrRequestExitSession"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrRequestExitSession"); return oxr_session_request_exit(&log, sess); } @@ -167,8 +155,7 @@ oxr_xrLocateViews(XrSession session, struct oxr_space *spc; struct oxr_logger log; OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrLocateViews"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, viewLocateInfo, - XR_TYPE_VIEW_LOCATE_INFO); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, viewLocateInfo, XR_TYPE_VIEW_LOCATE_INFO); OXR_VERIFY_SPACE_NOT_NULL(&log, viewLocateInfo->space, spc); OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, viewState, XR_TYPE_VIEW_STATE); @@ -178,8 +165,7 @@ oxr_xrLocateViews(XrSession session, OXR_VERIFY_ARG_NOT_NULL(&log, views); } - return oxr_session_views(&log, sess, viewLocateInfo, viewState, - viewCapacityInput, viewCountOutput, views); + return oxr_session_views(&log, sess, viewLocateInfo, viewState, viewCapacityInput, viewCountOutput, views); } @@ -200,8 +186,7 @@ oxr_xrGetVisibilityMaskKHR(XrSession session, { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrGetVisibilityMaskKHR"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrGetVisibilityMaskKHR"); return oxr_error(&log, XR_ERROR_HANDLE_INVALID, "Not implemented"); } @@ -224,8 +209,7 @@ oxr_xrPerfSettingsSetPerformanceLevelEXT(XrSession session, { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrPerfSettingsSetPerformanceLevelEXT"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrPerfSettingsSetPerformanceLevelEXT"); return oxr_error(&log, XR_ERROR_HANDLE_INVALID, "Not implemented"); } @@ -242,17 +226,15 @@ oxr_xrPerfSettingsSetPerformanceLevelEXT(XrSession session, #ifdef XR_EXT_thermal_query XrResult -oxr_xrThermalGetTemperatureTrendEXT( - XrSession session, - XrPerfSettingsDomainEXT domain, - XrPerfSettingsNotificationLevelEXT *notificationLevel, - float *tempHeadroom, - float *tempSlope) +oxr_xrThermalGetTemperatureTrendEXT(XrSession session, + XrPerfSettingsDomainEXT domain, + XrPerfSettingsNotificationLevelEXT *notificationLevel, + float *tempHeadroom, + float *tempSlope) { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrThermalGetTemperatureTrendEXT"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrThermalGetTemperatureTrendEXT"); return oxr_error(&log, XR_ERROR_HANDLE_INVALID, "Not implemented"); } @@ -280,13 +262,11 @@ oxr_hand_tracker_create(struct oxr_logger *log, struct oxr_hand_tracker **out_hand_tracker) { if (!oxr_system_get_hand_tracking_support(log, sess->sys->inst)) { - return oxr_error(log, XR_ERROR_FEATURE_UNSUPPORTED, - "System does not support hand tracking"); + return oxr_error(log, XR_ERROR_FEATURE_UNSUPPORTED, "System does not support hand tracking"); } struct oxr_hand_tracker *hand_tracker = NULL; - OXR_ALLOCATE_HANDLE_OR_RETURN(log, hand_tracker, OXR_XR_DEBUG_HTRACKER, - oxr_hand_tracker_destroy_cb, + OXR_ALLOCATE_HANDLE_OR_RETURN(log, hand_tracker, OXR_XR_DEBUG_HTRACKER, oxr_hand_tracker_destroy_cb, &sess->handle); hand_tracker->sess = sess; @@ -304,11 +284,9 @@ oxr_hand_tracker_create(struct oxr_logger *log, for (uint32_t j = 0; j < xdev->num_inputs; j++) { struct xrt_input *input = &xdev->inputs[j]; - if ((input->name == - XRT_INPUT_GENERIC_HAND_TRACKING_LEFT && + if ((input->name == XRT_INPUT_GENERIC_HAND_TRACKING_LEFT && createInfo->hand == XR_HAND_LEFT_EXT) || - (input->name == - XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT && + (input->name == XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT && createInfo->hand == XR_HAND_RIGHT_EXT)) { hand_tracker->xdev = xdev; hand_tracker->input_name = input->name; @@ -335,23 +313,18 @@ oxr_xrCreateHandTrackerEXT(XrSession session, struct oxr_session *sess = NULL; struct oxr_logger log; XrResult ret; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrCreateHandTrackerEXT"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, - XR_TYPE_HAND_TRACKER_CREATE_INFO_EXT); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrCreateHandTrackerEXT"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_HAND_TRACKER_CREATE_INFO_EXT); OXR_VERIFY_ARG_NOT_NULL(&log, handTracker); OXR_VERIFY_EXTENSION(&log, sess->sys->inst, EXT_hand_tracking); - if (createInfo->hand != XR_HAND_LEFT_EXT && - createInfo->hand != XR_HAND_RIGHT_EXT) { - return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, - "Invalid hand value %d\n", createInfo->hand); + if (createInfo->hand != XR_HAND_LEFT_EXT && createInfo->hand != XR_HAND_RIGHT_EXT) { + return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, "Invalid hand value %d\n", createInfo->hand); } if (createInfo->handJointSet != XR_HAND_JOINT_SET_DEFAULT_EXT) { - return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, - "Invalid handJointSet value %d\n", + return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, "Invalid handJointSet value %d\n", createInfo->handJointSet); } @@ -370,8 +343,7 @@ oxr_xrDestroyHandTrackerEXT(XrHandTrackerEXT handTracker) { struct oxr_hand_tracker *hand_tracker; struct oxr_logger log; - OXR_VERIFY_HAND_TRACKER_AND_INIT_LOG(&log, handTracker, hand_tracker, - "xrDestroyHandTrackerEXT"); + OXR_VERIFY_HAND_TRACKER_AND_INIT_LOG(&log, handTracker, hand_tracker, "xrDestroyHandTrackerEXT"); return oxr_handle_destroy(&log, &hand_tracker->handle); } @@ -384,33 +356,26 @@ oxr_xrLocateHandJointsEXT(XrHandTrackerEXT handTracker, struct oxr_hand_tracker *hand_tracker; struct oxr_space *spc; struct oxr_logger log; - OXR_VERIFY_HAND_TRACKER_AND_INIT_LOG(&log, handTracker, hand_tracker, - "xrLocateHandJointsEXT"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, locateInfo, - XR_TYPE_HAND_JOINTS_LOCATE_INFO_EXT); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, locations, - XR_TYPE_HAND_JOINT_LOCATIONS_EXT); + OXR_VERIFY_HAND_TRACKER_AND_INIT_LOG(&log, handTracker, hand_tracker, "xrLocateHandJointsEXT"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, locateInfo, XR_TYPE_HAND_JOINTS_LOCATE_INFO_EXT); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, locations, XR_TYPE_HAND_JOINT_LOCATIONS_EXT); OXR_VERIFY_SPACE_NOT_NULL(&log, locateInfo->baseSpace, spc); if (locateInfo->time <= (XrTime)0) { - return oxr_error(&log, XR_ERROR_TIME_INVALID, - "(time == %" PRIi64 ") is not a valid time.", + return oxr_error(&log, XR_ERROR_TIME_INVALID, "(time == %" PRIi64 ") is not a valid time.", locateInfo->time); } if (hand_tracker->hand_joint_set == XR_HAND_JOINT_SET_DEFAULT_EXT) { if (locations->jointCount != XR_HAND_JOINT_COUNT_EXT) { - return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, - "joint count must be %d, not %d\n", - XR_HAND_JOINT_COUNT_EXT, - locations->jointCount); + return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, "joint count must be %d, not %d\n", + XR_HAND_JOINT_COUNT_EXT, locations->jointCount); } }; - XrHandJointVelocitiesEXT *vel = OXR_GET_OUTPUT_FROM_CHAIN( - locations, XR_TYPE_HAND_JOINT_VELOCITIES_EXT, - XrHandJointVelocitiesEXT); + XrHandJointVelocitiesEXT *vel = + OXR_GET_OUTPUT_FROM_CHAIN(locations, XR_TYPE_HAND_JOINT_VELOCITIES_EXT, XrHandJointVelocitiesEXT); if (vel) { if (vel->jointCount <= 0) { return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, @@ -418,21 +383,17 @@ oxr_xrLocateHandJointsEXT(XrHandTrackerEXT handTracker, "must be >0, is %d\n", vel->jointCount); } - if (hand_tracker->hand_joint_set == - XR_HAND_JOINT_SET_DEFAULT_EXT) { + if (hand_tracker->hand_joint_set == XR_HAND_JOINT_SET_DEFAULT_EXT) { if (vel->jointCount != XR_HAND_JOINT_COUNT_EXT) { - return oxr_error( - &log, XR_ERROR_VALIDATION_FAILURE, - "XrHandJointVelocitiesEXT joint count must " - "be %d, not %d\n", - XR_HAND_JOINT_COUNT_EXT, - locations->jointCount); + return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, + "XrHandJointVelocitiesEXT joint count must " + "be %d, not %d\n", + XR_HAND_JOINT_COUNT_EXT, locations->jointCount); } } } - return oxr_session_hand_joints(&log, hand_tracker, locateInfo, - locations); + return oxr_session_hand_joints(&log, hand_tracker, locateInfo, locations); } #endif diff --git a/src/xrt/state_trackers/oxr/oxr_api_space.c b/src/xrt/state_trackers/oxr/oxr_api_space.c index 96f3831ef..abd65c4ca 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_space.c +++ b/src/xrt/state_trackers/oxr/oxr_api_space.c @@ -26,23 +26,18 @@ XrResult -oxr_xrCreateActionSpace(XrSession session, - const XrActionSpaceCreateInfo *createInfo, - XrSpace *space) +oxr_xrCreateActionSpace(XrSession session, const XrActionSpaceCreateInfo *createInfo, XrSpace *space) { struct oxr_session *sess; struct oxr_action *act; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrCreateActionSpace"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, - XR_TYPE_ACTION_SPACE_CREATE_INFO); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrCreateActionSpace"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_ACTION_SPACE_CREATE_INFO); OXR_VERIFY_POSE(&log, createInfo->poseInActionSpace); OXR_VERIFY_ACTION_NOT_NULL(&log, createInfo->action, act); struct oxr_space *spc; - XrResult ret = - oxr_space_action_create(&log, sess, act->act_key, createInfo, &spc); + XrResult ret = oxr_space_action_create(&log, sess, act->act_key, createInfo, &spc); if (ret != XR_SUCCESS) { return ret; } @@ -66,23 +61,18 @@ oxr_xrEnumerateReferenceSpaces(XrSession session, { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrEnumerateReferenceSpaces"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrEnumerateReferenceSpaces"); - OXR_TWO_CALL_HELPER(&log, spaceCapacityInput, spaceCountOutput, spaces, - ARRAY_SIZE(session_spaces), session_spaces, - oxr_session_success_result(sess)); + OXR_TWO_CALL_HELPER(&log, spaceCapacityInput, spaceCountOutput, spaces, ARRAY_SIZE(session_spaces), + session_spaces, oxr_session_success_result(sess)); } XrResult -oxr_xrGetReferenceSpaceBoundsRect(XrSession session, - XrReferenceSpaceType referenceSpaceType, - XrExtent2Df *bounds) +oxr_xrGetReferenceSpaceBoundsRect(XrSession session, XrReferenceSpaceType referenceSpaceType, XrExtent2Df *bounds) { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrGetReferenceSpaceBoundsRect"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrGetReferenceSpaceBoundsRect"); OXR_VERIFY_ARG_NOT_NULL(&log, bounds); @@ -105,18 +95,14 @@ oxr_xrGetReferenceSpaceBoundsRect(XrSession session, } XrResult -oxr_xrCreateReferenceSpace(XrSession session, - const XrReferenceSpaceCreateInfo *createInfo, - XrSpace *out_space) +oxr_xrCreateReferenceSpace(XrSession session, const XrReferenceSpaceCreateInfo *createInfo, XrSpace *out_space) { XrResult ret; struct oxr_session *sess; struct oxr_space *spc = NULL; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrCreateReferenceSpace"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, - XR_TYPE_REFERENCE_SPACE_CREATE_INFO); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrCreateReferenceSpace"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_REFERENCE_SPACE_CREATE_INFO); OXR_VERIFY_POSE(&log, createInfo->poseInReferenceSpace); ret = oxr_space_reference_create(&log, sess, createInfo, &spc); @@ -130,26 +116,19 @@ oxr_xrCreateReferenceSpace(XrSession session, } XrResult -oxr_xrLocateSpace(XrSpace space, - XrSpace baseSpace, - XrTime time, - XrSpaceLocation *location) +oxr_xrLocateSpace(XrSpace space, XrSpace baseSpace, XrTime time, XrSpaceLocation *location) { struct oxr_space *spc; struct oxr_space *baseSpc; struct oxr_logger log; OXR_VERIFY_SPACE_AND_INIT_LOG(&log, space, spc, "xrLocateSpace"); OXR_VERIFY_SPACE_NOT_NULL(&log, baseSpace, baseSpc); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, location, - XR_TYPE_SPACE_LOCATION); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, location, XR_TYPE_SPACE_LOCATION); - OXR_VERIFY_ARG_TYPE_CAN_BE_NULL( - &log, ((XrSpaceVelocity *)location->next), XR_TYPE_SPACE_VELOCITY); + OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(&log, ((XrSpaceVelocity *)location->next), XR_TYPE_SPACE_VELOCITY); if (time <= (XrTime)0) { - return oxr_error(&log, XR_ERROR_TIME_INVALID, - "(time == %" PRIi64 ") is not a valid time.", - time); + return oxr_error(&log, XR_ERROR_TIME_INVALID, "(time == %" PRIi64 ") is not a valid time.", time); } return oxr_space_locate(&log, spc, baseSpc, time, location); diff --git a/src/xrt/state_trackers/oxr/oxr_api_swapchain.c b/src/xrt/state_trackers/oxr/oxr_api_swapchain.c index bcce3592c..22e58c71b 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_swapchain.c +++ b/src/xrt/state_trackers/oxr/oxr_api_swapchain.c @@ -32,30 +32,23 @@ oxr_xrEnumerateSwapchainFormats(XrSession session, { struct oxr_session *sess; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrEnumerateSwapchainFormats"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrEnumerateSwapchainFormats"); - return oxr_session_enumerate_formats(&log, sess, formatCapacityInput, - formatCountOutput, formats); + return oxr_session_enumerate_formats(&log, sess, formatCapacityInput, formatCountOutput, formats); } XrResult -oxr_xrCreateSwapchain(XrSession session, - const XrSwapchainCreateInfo *createInfo, - XrSwapchain *out_swapchain) +oxr_xrCreateSwapchain(XrSession session, const XrSwapchainCreateInfo *createInfo, XrSwapchain *out_swapchain) { XrResult ret; struct oxr_session *sess; struct oxr_swapchain *sc; struct oxr_logger log; - OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, - "xrCreateSwapchain"); + OXR_VERIFY_SESSION_AND_INIT_LOG(&log, session, sess, "xrCreateSwapchain"); if (sess->compositor == NULL) { - return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, - "Is illegal in headless sessions"); + return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, "Is illegal in headless sessions"); } - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, - XR_TYPE_SWAPCHAIN_CREATE_INFO); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_SWAPCHAIN_CREATE_INFO); OXR_VERIFY_ARG_NOT_NULL(&log, out_swapchain); // Save people from shooting themselves in the foot. @@ -80,8 +73,7 @@ oxr_xrCreateSwapchain(XrSession session, if ((createInfo->usageFlags & ~flags) != 0) { return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, - "(createInfo->usageFlags == 0x08%" PRIx64 - ") contains invalid flags", + "(createInfo->usageFlags == 0x08%" PRIx64 ") contains invalid flags", createInfo->usageFlags); } @@ -100,8 +92,7 @@ oxr_xrDestroySwapchain(XrSwapchain swapchain) { struct oxr_swapchain *sc; struct oxr_logger log; - OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, - "xrDestroySwapchain"); + OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, "xrDestroySwapchain"); return oxr_handle_destroy(&log, &sc->handle); } @@ -114,8 +105,7 @@ oxr_xrEnumerateSwapchainImages(XrSwapchain swapchain, { struct oxr_swapchain *sc; struct oxr_logger log; - OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, - "xrEnumerateSwapchainImages"); + OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, "xrEnumerateSwapchainImages"); struct xrt_swapchain *xsc = sc->swapchain; if (imageCountOutput != NULL) { @@ -125,54 +115,42 @@ oxr_xrEnumerateSwapchainImages(XrSwapchain swapchain, return XR_SUCCESS; } if (imageCapacityInput < xsc->num_images) { - return oxr_error(&log, XR_ERROR_SIZE_INSUFFICIENT, - "(imageCapacityInput == %u)", - imageCapacityInput); + return oxr_error(&log, XR_ERROR_SIZE_INSUFFICIENT, "(imageCapacityInput == %u)", imageCapacityInput); } return sc->enumerate_images(&log, sc, xsc->num_images, images); } XrResult -oxr_xrAcquireSwapchainImage(XrSwapchain swapchain, - const XrSwapchainImageAcquireInfo *acquireInfo, - uint32_t *index) +oxr_xrAcquireSwapchainImage(XrSwapchain swapchain, const XrSwapchainImageAcquireInfo *acquireInfo, uint32_t *index) { struct oxr_swapchain *sc; struct oxr_logger log; - OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, - "xrAcquireSwapchainImage"); - OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(&log, acquireInfo, - XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO); + OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, "xrAcquireSwapchainImage"); + OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(&log, acquireInfo, XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO); OXR_VERIFY_ARG_NOT_NULL(&log, index); return sc->acquire_image(&log, sc, acquireInfo, index); } XrResult -oxr_xrWaitSwapchainImage(XrSwapchain swapchain, - const XrSwapchainImageWaitInfo *waitInfo) +oxr_xrWaitSwapchainImage(XrSwapchain swapchain, const XrSwapchainImageWaitInfo *waitInfo) { struct oxr_swapchain *sc; struct oxr_logger log; - OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, - "xrWaitSwapchainImage"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, waitInfo, - XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO); + OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, "xrWaitSwapchainImage"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, waitInfo, XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO); return sc->wait_image(&log, sc, waitInfo); } XrResult -oxr_xrReleaseSwapchainImage(XrSwapchain swapchain, - const XrSwapchainImageReleaseInfo *releaseInfo) +oxr_xrReleaseSwapchainImage(XrSwapchain swapchain, const XrSwapchainImageReleaseInfo *releaseInfo) { struct oxr_swapchain *sc; struct oxr_logger log; - OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, - "xrReleaseSwapchainImage"); - OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(&log, releaseInfo, - XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO); + OXR_VERIFY_SWAPCHAIN_AND_INIT_LOG(&log, swapchain, sc, "xrReleaseSwapchainImage"); + OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(&log, releaseInfo, XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO); return sc->release_image(&log, sc, releaseInfo); } diff --git a/src/xrt/state_trackers/oxr/oxr_api_system.c b/src/xrt/state_trackers/oxr/oxr_api_system.c index 792dff918..c898e278b 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_system.c +++ b/src/xrt/state_trackers/oxr/oxr_api_system.c @@ -28,35 +28,30 @@ /*! * A helper define that verifies the systemId. */ -#define OXR_VERIFY_SYSTEM_AND_GET(log, inst, sysId, system) \ - struct oxr_system *system = NULL; \ - do { \ - XrResult ret = \ - oxr_system_get_by_id(log, inst, sysId, &system); \ - if (ret != XR_SUCCESS) { \ - return ret; \ - } \ - assert(system != NULL); \ +#define OXR_VERIFY_SYSTEM_AND_GET(log, inst, sysId, system) \ + struct oxr_system *system = NULL; \ + do { \ + XrResult ret = oxr_system_get_by_id(log, inst, sysId, &system); \ + if (ret != XR_SUCCESS) { \ + return ret; \ + } \ + assert(system != NULL); \ } while (false) XrResult -oxr_xrGetSystem(XrInstance instance, - const XrSystemGetInfo *getInfo, - XrSystemId *systemId) +oxr_xrGetSystem(XrInstance instance, const XrSystemGetInfo *getInfo, XrSystemId *systemId) { struct oxr_instance *inst; struct oxr_logger log; OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetSystem"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, - XR_TYPE_SYSTEM_GET_INFO); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, XR_TYPE_SYSTEM_GET_INFO); OXR_VERIFY_ARG_NOT_NULL(&log, systemId); struct oxr_system *selected = NULL; struct oxr_system *systems[1] = {&inst->system}; uint32_t num_systems = 1; - XrResult ret = oxr_system_select(&log, systems, num_systems, - getInfo->formFactor, &selected); + XrResult ret = oxr_system_select(&log, systems, num_systems, getInfo->formFactor, &selected); if (ret != XR_SUCCESS) { return ret; } @@ -67,106 +62,88 @@ oxr_xrGetSystem(XrInstance instance, } XrResult -oxr_xrGetSystemProperties(XrInstance instance, - XrSystemId systemId, - XrSystemProperties *properties) +oxr_xrGetSystemProperties(XrInstance instance, XrSystemId systemId, XrSystemProperties *properties) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetSystemProperties"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, properties, - XR_TYPE_SYSTEM_PROPERTIES); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetSystemProperties"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, properties, XR_TYPE_SYSTEM_PROPERTIES); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); return oxr_system_get_properties(&log, sys, properties); } XrResult -oxr_xrEnumerateViewConfigurations( - XrInstance instance, - XrSystemId systemId, - uint32_t viewConfigurationTypeCapacityInput, - uint32_t *viewConfigurationTypeCountOutput, - XrViewConfigurationType *viewConfigurationTypes) +oxr_xrEnumerateViewConfigurations(XrInstance instance, + XrSystemId systemId, + uint32_t viewConfigurationTypeCapacityInput, + uint32_t *viewConfigurationTypeCountOutput, + XrViewConfigurationType *viewConfigurationTypes) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrEnumerateViewConfigurations"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrEnumerateViewConfigurations"); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); - return oxr_system_enumerate_view_confs( - &log, sys, viewConfigurationTypeCapacityInput, - viewConfigurationTypeCountOutput, viewConfigurationTypes); + return oxr_system_enumerate_view_confs(&log, sys, viewConfigurationTypeCapacityInput, + viewConfigurationTypeCountOutput, viewConfigurationTypes); } XrResult -oxr_xrEnumerateEnvironmentBlendModes( - XrInstance instance, - XrSystemId systemId, - XrViewConfigurationType viewConfigurationType, - uint32_t environmentBlendModeCapacityInput, - uint32_t *environmentBlendModeCountOutput, - XrEnvironmentBlendMode *environmentBlendModes) +oxr_xrEnumerateEnvironmentBlendModes(XrInstance instance, + XrSystemId systemId, + XrViewConfigurationType viewConfigurationType, + uint32_t environmentBlendModeCapacityInput, + uint32_t *environmentBlendModeCountOutput, + XrEnvironmentBlendMode *environmentBlendModes) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrEnumerateEnvironmentBlendModes"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrEnumerateEnvironmentBlendModes"); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); OXR_VERIFY_VIEW_CONFIG_TYPE(&log, inst, viewConfigurationType); if (viewConfigurationType != sys->view_config_type) { - return oxr_error(&log, - XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED, + return oxr_error(&log, XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED, "(viewConfigurationType == 0x%08x) " "unsupported view configuration type", viewConfigurationType); } - return oxr_system_enumerate_blend_modes( - &log, sys, viewConfigurationType, environmentBlendModeCapacityInput, - environmentBlendModeCountOutput, environmentBlendModes); + return oxr_system_enumerate_blend_modes(&log, sys, viewConfigurationType, environmentBlendModeCapacityInput, + environmentBlendModeCountOutput, environmentBlendModes); } XrResult -oxr_xrGetViewConfigurationProperties( - XrInstance instance, - XrSystemId systemId, - XrViewConfigurationType viewConfigurationType, - XrViewConfigurationProperties *configurationProperties) +oxr_xrGetViewConfigurationProperties(XrInstance instance, + XrSystemId systemId, + XrViewConfigurationType viewConfigurationType, + XrViewConfigurationProperties *configurationProperties) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetViewConfigurationProperties"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, configurationProperties, - XR_TYPE_VIEW_CONFIGURATION_PROPERTIES); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetViewConfigurationProperties"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, configurationProperties, XR_TYPE_VIEW_CONFIGURATION_PROPERTIES); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); - return oxr_system_get_view_conf_properties( - &log, sys, viewConfigurationType, configurationProperties); + return oxr_system_get_view_conf_properties(&log, sys, viewConfigurationType, configurationProperties); } XrResult -oxr_xrEnumerateViewConfigurationViews( - XrInstance instance, - XrSystemId systemId, - XrViewConfigurationType viewConfigurationType, - uint32_t viewCapacityInput, - uint32_t *viewCountOutput, - XrViewConfigurationView *views) +oxr_xrEnumerateViewConfigurationViews(XrInstance instance, + XrSystemId systemId, + XrViewConfigurationType viewConfigurationType, + uint32_t viewCapacityInput, + uint32_t *viewCountOutput, + XrViewConfigurationView *views) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrEnumerateViewConfigurationViews"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrEnumerateViewConfigurationViews"); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); - return oxr_system_enumerate_view_conf_views( - &log, sys, viewConfigurationType, viewCapacityInput, - viewCountOutput, views); + return oxr_system_enumerate_view_conf_views(&log, sys, viewConfigurationType, viewCapacityInput, + viewCountOutput, views); } @@ -179,28 +156,22 @@ oxr_xrEnumerateViewConfigurationViews( #ifdef XR_USE_GRAPHICS_API_OPENGL_ES XrResult -oxr_xrGetOpenGLESGraphicsRequirementsKHR( - XrInstance instance, - XrSystemId systemId, - XrGraphicsRequirementsOpenGLESKHR *graphicsRequirements) +oxr_xrGetOpenGLESGraphicsRequirementsKHR(XrInstance instance, + XrSystemId systemId, + XrGraphicsRequirementsOpenGLESKHR *graphicsRequirements) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG( - &log, instance, inst, "xrGetOpenGLESGraphicsRequirementsKHR"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, graphicsRequirements, - XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetOpenGLESGraphicsRequirementsKHR"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, graphicsRequirements, XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); struct xrt_api_requirements ver; xrt_gfx_gles_get_versions(&ver); - graphicsRequirements->minApiVersionSupported = - XR_MAKE_VERSION(ver.min_major, ver.min_minor, ver.min_patch); - graphicsRequirements->maxApiVersionSupported = - XR_MAKE_VERSION(ver.max_major, ver.max_minor, ver.max_patch); + graphicsRequirements->minApiVersionSupported = XR_MAKE_VERSION(ver.min_major, ver.min_minor, ver.min_patch); + graphicsRequirements->maxApiVersionSupported = XR_MAKE_VERSION(ver.max_major, ver.max_minor, ver.max_patch); sys->gotten_requirements = true; @@ -219,28 +190,22 @@ oxr_xrGetOpenGLESGraphicsRequirementsKHR( #ifdef XR_USE_GRAPHICS_API_OPENGL XrResult -oxr_xrGetOpenGLGraphicsRequirementsKHR( - XrInstance instance, - XrSystemId systemId, - XrGraphicsRequirementsOpenGLKHR *graphicsRequirements) +oxr_xrGetOpenGLGraphicsRequirementsKHR(XrInstance instance, + XrSystemId systemId, + XrGraphicsRequirementsOpenGLKHR *graphicsRequirements) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetOpenGLGraphicsRequirementsKHR"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, graphicsRequirements, - XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetOpenGLGraphicsRequirementsKHR"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, graphicsRequirements, XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); struct xrt_api_requirements ver; xrt_gfx_gl_get_versions(&ver); - graphicsRequirements->minApiVersionSupported = - XR_MAKE_VERSION(ver.min_major, ver.min_minor, ver.min_patch); - graphicsRequirements->maxApiVersionSupported = - XR_MAKE_VERSION(ver.max_major, ver.max_minor, ver.max_patch); + graphicsRequirements->minApiVersionSupported = XR_MAKE_VERSION(ver.min_major, ver.min_minor, ver.min_patch); + graphicsRequirements->maxApiVersionSupported = XR_MAKE_VERSION(ver.max_major, ver.max_minor, ver.max_patch); sys->gotten_requirements = true; @@ -267,12 +232,10 @@ oxr_xrGetVulkanInstanceExtensionsKHR(XrInstance instance, { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetVulkanInstanceExtensionsKHR"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetVulkanInstanceExtensionsKHR"); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); - return oxr_vk_get_instance_exts(&log, sys, namesCapacityInput, - namesCountOutput, namesString); + return oxr_vk_get_instance_exts(&log, sys, namesCapacityInput, namesCountOutput, namesString); } XrResult @@ -284,12 +247,10 @@ oxr_xrGetVulkanDeviceExtensionsKHR(XrInstance instance, { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetVulkanDeviceExtensionsKHR"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetVulkanDeviceExtensionsKHR"); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); - return oxr_vk_get_device_exts(&log, sys, namesCapacityInput, - namesCountOutput, namesString); + return oxr_vk_get_device_exts(&log, sys, namesCapacityInput, namesCountOutput, namesString); } // NOLINTNEXTLINE // don't remove the forward decl. @@ -304,71 +265,56 @@ oxr_xrGetVulkanGraphicsDeviceKHR(XrInstance instance, { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetVulkanGraphicsDeviceKHR"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetVulkanGraphicsDeviceKHR"); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); OXR_VERIFY_ARG_NOT_NULL(&log, vkPhysicalDevice); - return oxr_vk_get_physical_device(&log, inst, sys, vkInstance, - vkGetInstanceProcAddr, - vkPhysicalDevice); + return oxr_vk_get_physical_device(&log, inst, sys, vkInstance, vkGetInstanceProcAddr, vkPhysicalDevice); } XrResult -oxr_xrGetVulkanGraphicsDevice2KHR( - XrInstance instance, - const XrVulkanGraphicsDeviceGetInfoKHR *getInfo, - VkPhysicalDevice *vkPhysicalDevice) +oxr_xrGetVulkanGraphicsDevice2KHR(XrInstance instance, + const XrVulkanGraphicsDeviceGetInfoKHR *getInfo, + VkPhysicalDevice *vkPhysicalDevice) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetVulkanGraphicsDeviceKHR"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, getInfo, XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetVulkanGraphicsDeviceKHR"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, getInfo, XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, getInfo->systemId, sys); OXR_VERIFY_ARG_NOT_NULL(&log, vkPhysicalDevice); - return oxr_vk_get_physical_device( - &log, inst, sys, getInfo->vulkanInstance, vkGetInstanceProcAddr, - vkPhysicalDevice); + return oxr_vk_get_physical_device(&log, inst, sys, getInfo->vulkanInstance, vkGetInstanceProcAddr, + vkPhysicalDevice); } XrResult -oxr_xrGetVulkanGraphicsRequirementsKHR( - XrInstance instance, - XrSystemId systemId, - XrGraphicsRequirementsVulkanKHR *graphicsRequirements) +oxr_xrGetVulkanGraphicsRequirementsKHR(XrInstance instance, + XrSystemId systemId, + XrGraphicsRequirementsVulkanKHR *graphicsRequirements) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetVulkanGraphicsRequirementsKHR"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetVulkanGraphicsRequirementsKHR"); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, graphicsRequirements, - XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, graphicsRequirements, XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR); return oxr_vk_get_requirements(&log, sys, graphicsRequirements); } XrResult -oxr_xrGetVulkanGraphicsRequirements2KHR( - XrInstance instance, - XrSystemId systemId, - XrGraphicsRequirementsVulkan2KHR *graphicsRequirements) +oxr_xrGetVulkanGraphicsRequirements2KHR(XrInstance instance, + XrSystemId systemId, + XrGraphicsRequirementsVulkan2KHR *graphicsRequirements) { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetVulkanGraphicsRequirementsKHR"); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetVulkanGraphicsRequirementsKHR"); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, systemId, sys); /* XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN2_KHR aliased to * XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR */ - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, graphicsRequirements, - XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, graphicsRequirements, XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR); return oxr_vk_get_requirements(&log, sys, graphicsRequirements); } @@ -381,10 +327,8 @@ oxr_xrCreateVulkanInstanceKHR(XrInstance instance, { struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrCreateVulkanInstanceKHR"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL( - &log, createInfo, XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrCreateVulkanInstanceKHR"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, createInfo->systemId, sys); OXR_VERIFY_ARG_NOT_NULL(&log, createInfo->pfnGetInstanceProcAddr); @@ -395,15 +339,13 @@ oxr_xrCreateVulkanInstanceKHR(XrInstance instance, // createInfo->vulkanAllocator can be NULL - if (createInfo->vulkanCreateInfo->sType != - VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO) { + if (createInfo->vulkanCreateInfo->sType != VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO) { return oxr_error(&log, XR_ERROR_VALIDATION_FAILURE, "createInfo->vulkanCreateInfo->sType must be " "VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO"); } - return oxr_vk_create_vulkan_instance(&log, sys, createInfo, - vulkanInstance, vulkanResult); + return oxr_vk_create_vulkan_instance(&log, sys, createInfo, vulkanInstance, vulkanResult); } XrResult @@ -415,10 +357,8 @@ oxr_xrCreateVulkanDeviceKHR(XrInstance instance, struct oxr_instance *inst; struct oxr_logger log; - OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, - "xrGetVulkanGraphicsDeviceKHR"); - OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, - XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR); + OXR_VERIFY_INSTANCE_AND_INIT_LOG(&log, instance, inst, "xrGetVulkanGraphicsDeviceKHR"); + OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(&log, createInfo, XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR); OXR_VERIFY_SYSTEM_AND_GET(&log, inst, createInfo->systemId, sys); OXR_VERIFY_ARG_ZERO(&log, createInfo->createFlags); @@ -432,17 +372,14 @@ oxr_xrCreateVulkanDeviceKHR(XrInstance instance, //! @todo require xrCreateVulkanInstanceKHR to be called in the spec OXR_VERIFY_ARG_NOT_NULL(&log, sys->vulkan_enable2_instance); - if (sys->vulkan_enable2_physical_device != - createInfo->vulkanPhysicalDevice) { - return oxr_error( - &log, XR_ERROR_HANDLE_INVALID, - "createInfo->vulkanPhysicalDevice must be the device " - "returned by xrGetVulkanGraphicsDeviceKHR"); + if (sys->vulkan_enable2_physical_device != createInfo->vulkanPhysicalDevice) { + return oxr_error(&log, XR_ERROR_HANDLE_INVALID, + "createInfo->vulkanPhysicalDevice must be the device " + "returned by xrGetVulkanGraphicsDeviceKHR"); } // createInfo->vulkanAllocator can be NULL - return oxr_vk_create_vulkan_device(&log, sys, createInfo, vulkanDevice, - vulkanResult); + return oxr_vk_create_vulkan_device(&log, sys, createInfo, vulkanDevice, vulkanResult); } #endif diff --git a/src/xrt/state_trackers/oxr/oxr_api_verify.h b/src/xrt/state_trackers/oxr/oxr_api_verify.h index 9bb80f53f..e242d83f0 100644 --- a/src/xrt/state_trackers/oxr/oxr_api_verify.h +++ b/src/xrt/state_trackers/oxr/oxr_api_verify.h @@ -14,41 +14,32 @@ extern "C" { #endif -#define _OXR_VERIFY_AND_SET_AND_INIT(log, thing, new_thing, oxr_thing, THING, \ - name, lookup) \ - do { \ - oxr_log_init(log, name); \ - if (thing == XR_NULL_HANDLE) { \ - return oxr_error(log, XR_ERROR_HANDLE_INVALID, \ - "(" #thing " == NULL)"); \ - } \ - new_thing = (struct oxr_thing *)((uintptr_t)thing); \ - if (new_thing->handle.debug != OXR_XR_DEBUG_##THING) { \ - return oxr_error(log, XR_ERROR_HANDLE_INVALID, \ - "(" #thing " == %p)", \ - (void *)new_thing); \ - } \ - if (new_thing->handle.state != OXR_HANDLE_STATE_LIVE) { \ - return oxr_error(log, XR_ERROR_HANDLE_INVALID, \ - "(" #thing " == %p) state == %s", \ - (void *)new_thing, \ - oxr_handle_state_to_string( \ - new_thing->handle.state)); \ - } \ - oxr_log_set_instance(log, lookup); \ +#define _OXR_VERIFY_AND_SET_AND_INIT(log, thing, new_thing, oxr_thing, THING, name, lookup) \ + do { \ + oxr_log_init(log, name); \ + if (thing == XR_NULL_HANDLE) { \ + return oxr_error(log, XR_ERROR_HANDLE_INVALID, "(" #thing " == NULL)"); \ + } \ + new_thing = (struct oxr_thing *)((uintptr_t)thing); \ + if (new_thing->handle.debug != OXR_XR_DEBUG_##THING) { \ + return oxr_error(log, XR_ERROR_HANDLE_INVALID, "(" #thing " == %p)", (void *)new_thing); \ + } \ + if (new_thing->handle.state != OXR_HANDLE_STATE_LIVE) { \ + return oxr_error(log, XR_ERROR_HANDLE_INVALID, "(" #thing " == %p) state == %s", \ + (void *)new_thing, oxr_handle_state_to_string(new_thing->handle.state)); \ + } \ + oxr_log_set_instance(log, lookup); \ } while (0) -#define _OXR_VERIFY_SET(log, arg, new_arg, oxr_thing, THING) \ - do { \ - if (arg == XR_NULL_HANDLE) { \ - return oxr_error(log, XR_ERROR_HANDLE_INVALID, \ - "(" #arg " == NULL)"); \ - } \ - new_arg = (struct oxr_thing *)((uintptr_t)arg); \ - if (new_arg->handle.debug != OXR_XR_DEBUG_##THING) { \ - return oxr_error(log, XR_ERROR_HANDLE_INVALID, \ - "(" #arg " == %p)", (void *)new_arg); \ - } \ +#define _OXR_VERIFY_SET(log, arg, new_arg, oxr_thing, THING) \ + do { \ + if (arg == XR_NULL_HANDLE) { \ + return oxr_error(log, XR_ERROR_HANDLE_INVALID, "(" #arg " == NULL)"); \ + } \ + new_arg = (struct oxr_thing *)((uintptr_t)arg); \ + if (new_arg->handle.debug != OXR_XR_DEBUG_##THING) { \ + return oxr_error(log, XR_ERROR_HANDLE_INVALID, "(" #arg " == %p)", (void *)new_arg); \ + } \ } while (0) @@ -89,13 +80,12 @@ extern "C" { * * mixed_case_name should be the extension name without the XR_ prefix. */ -#define OXR_VERIFY_EXTENSION(log, inst, mixed_case_name) \ - do { \ - if (!(inst)->extensions.mixed_case_name) { \ - return oxr_error((log), XR_ERROR_FUNCTION_UNSUPPORTED, \ - "Requires XR_" #mixed_case_name \ - " extension enabled"); \ - } \ +#define OXR_VERIFY_EXTENSION(log, inst, mixed_case_name) \ + do { \ + if (!(inst)->extensions.mixed_case_name) { \ + return oxr_error((log), XR_ERROR_FUNCTION_UNSUPPORTED, \ + "Requires XR_" #mixed_case_name " extension enabled"); \ + } \ } while (false) /*! @@ -103,108 +93,92 @@ extern "C" { * * mixed_case_name should be the extension name without the XR_ prefix. */ -#define OXR_VERIFY_EXTENSIONS_OR(log, inst, mixed_case_name1, \ - mixed_case_name2) \ - do { \ - if (!(inst)->extensions.mixed_case_name1 && \ - !(inst)->extensions.mixed_case_name2) { \ - return oxr_error((log), XR_ERROR_FUNCTION_UNSUPPORTED, \ - "Requires XR_" #mixed_case_name1 \ - "or XR_" #mixed_case_name2 \ - " extension enabled"); \ - } \ +#define OXR_VERIFY_EXTENSIONS_OR(log, inst, mixed_case_name1, mixed_case_name2) \ + do { \ + if (!(inst)->extensions.mixed_case_name1 && !(inst)->extensions.mixed_case_name2) { \ + return oxr_error((log), XR_ERROR_FUNCTION_UNSUPPORTED, \ + "Requires XR_" #mixed_case_name1 "or XR_" #mixed_case_name2 \ + " extension enabled"); \ + } \ } while (false) -#define OXR_VERIFY_ARG_NOT_NULL(log, arg) \ - do { \ - if (arg == NULL) { \ - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, \ - "(" #arg " == NULL)"); \ - } \ +#define OXR_VERIFY_ARG_NOT_NULL(log, arg) \ + do { \ + if (arg == NULL) { \ + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(" #arg " == NULL)"); \ + } \ } while (false) -#define OXR_VERIFY_ARG_NOT_ZERO(log, arg) \ - do { \ - if (arg == 0) { \ - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, \ - "(" #arg " == 0) must be non-zero"); \ - } \ +#define OXR_VERIFY_ARG_NOT_ZERO(log, arg) \ + do { \ + if (arg == 0) { \ + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(" #arg " == 0) must be non-zero"); \ + } \ } while (false) -#define OXR_VERIFY_ARG_ZERO(log, arg) \ - do { \ - if (arg != 0) { \ - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, \ - "(" #arg " == 0) must be zero"); \ - } \ +#define OXR_VERIFY_ARG_ZERO(log, arg) \ + do { \ + if (arg != 0) { \ + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(" #arg " == 0) must be zero"); \ + } \ } while (false) -#define OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(log, arg, type_enum) \ - do { \ - if (arg != NULL && arg->type != type_enum) { \ - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, \ - "(" #arg "->type == %u)", arg->type); \ - } \ +#define OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(log, arg, type_enum) \ + do { \ + if (arg != NULL && arg->type != type_enum) { \ + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(" #arg "->type == %u)", arg->type); \ + } \ } while (false) -#define OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(log, arg, type_enum) \ - do { \ - if (arg == NULL) { \ - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, \ - "(" #arg " == NULL)"); \ - } \ - OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(log, arg, type_enum); \ +#define OXR_VERIFY_ARG_TYPE_AND_NOT_NULL(log, arg, type_enum) \ + do { \ + if (arg == NULL) { \ + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(" #arg " == NULL)"); \ + } \ + OXR_VERIFY_ARG_TYPE_CAN_BE_NULL(log, arg, type_enum); \ } while (false) -#define OXR_VERIFY_SUBACTION_PATHS(log, count, paths) \ - do { \ - if (count > 0 && paths == NULL) { \ - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, \ - "(" #count \ - ") is not zero but " #paths \ - " is NULL"); \ - } \ +#define OXR_VERIFY_SUBACTION_PATHS(log, count, paths) \ + do { \ + if (count > 0 && paths == NULL) { \ + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, \ + "(" #count ") is not zero but " #paths " is NULL"); \ + } \ } while (false) -#define OXR_VERIFY_ARG_SINGLE_LEVEL_FIXED_LENGTH_PATH(log, path) \ - do { \ - XrResult verify_ret = oxr_verify_fixed_size_single_level_path( \ - log, path, ARRAY_SIZE(path), #path); \ - if (verify_ret != XR_SUCCESS) { \ - return verify_ret; \ - } \ +#define OXR_VERIFY_ARG_SINGLE_LEVEL_FIXED_LENGTH_PATH(log, path) \ + do { \ + XrResult verify_ret = oxr_verify_fixed_size_single_level_path(log, path, ARRAY_SIZE(path), #path); \ + if (verify_ret != XR_SUCCESS) { \ + return verify_ret; \ + } \ } while (false) -#define OXR_VERIFY_ARG_LOCALIZED_NAME(log, string) \ - do { \ - XrResult verify_ret = oxr_verify_localized_name( \ - log, string, ARRAY_SIZE(string), #string); \ - if (verify_ret != XR_SUCCESS) { \ - return verify_ret; \ - } \ +#define OXR_VERIFY_ARG_LOCALIZED_NAME(log, string) \ + do { \ + XrResult verify_ret = oxr_verify_localized_name(log, string, ARRAY_SIZE(string), #string); \ + if (verify_ret != XR_SUCCESS) { \ + return verify_ret; \ + } \ } while (false) -#define OXR_VERIFY_POSE(log, p) \ - do { \ - if (!math_quat_validate((struct xrt_quat *)&p.orientation)) { \ - return oxr_error(log, XR_ERROR_POSE_INVALID, \ - "(" #p \ - ".orientation) is not a valid quat"); \ - } \ - \ - if (!math_vec3_validate((struct xrt_vec3 *)&p.position)) { \ - return oxr_error(log, XR_ERROR_POSE_INVALID, \ - "(" #p ".position) is not valid"); \ - } \ +#define OXR_VERIFY_POSE(log, p) \ + do { \ + if (!math_quat_validate((struct xrt_quat *)&p.orientation)) { \ + return oxr_error(log, XR_ERROR_POSE_INVALID, "(" #p ".orientation) is not a valid quat"); \ + } \ + \ + if (!math_vec3_validate((struct xrt_vec3 *)&p.position)) { \ + return oxr_error(log, XR_ERROR_POSE_INVALID, "(" #p ".position) is not valid"); \ + } \ } while (false) -#define OXR_VERIFY_VIEW_CONFIG_TYPE(log, inst, view_conf) \ - do { \ - XrResult verify_ret = oxr_verify_view_config_type( \ - log, inst, view_conf, #view_conf); \ - if (verify_ret != XR_SUCCESS) { \ - return verify_ret; \ - } \ +#define OXR_VERIFY_VIEW_CONFIG_TYPE(log, inst, view_conf) \ + do { \ + XrResult verify_ret = oxr_verify_view_config_type(log, inst, view_conf, #view_conf); \ + if (verify_ret != XR_SUCCESS) { \ + return verify_ret; \ + } \ } while (false) @@ -215,9 +189,7 @@ extern "C" { */ XrResult -oxr_verify_full_path_c(struct oxr_logger *log, - const char *path, - const char *name); +oxr_verify_full_path_c(struct oxr_logger *log, const char *path, const char *name); /*! * Verify a full path. @@ -225,28 +197,19 @@ oxr_verify_full_path_c(struct oxr_logger *log, * Length not including zero terminator character but must be there. */ XrResult -oxr_verify_full_path(struct oxr_logger *log, - const char *path, - size_t length, - const char *name); +oxr_verify_full_path(struct oxr_logger *log, const char *path, size_t length, const char *name); /*! * Verify a single path level that sits inside of a fixed sized array. */ XrResult -oxr_verify_fixed_size_single_level_path(struct oxr_logger *, - const char *path, - uint32_t array_size, - const char *name); +oxr_verify_fixed_size_single_level_path(struct oxr_logger *, const char *path, uint32_t array_size, const char *name); /*! * Verify an arbitrary UTF-8 string that sits inside of a fixed sized array. */ XrResult -oxr_verify_localized_name(struct oxr_logger *, - const char *string, - uint32_t array_size, - const char *name); +oxr_verify_localized_name(struct oxr_logger *, const char *string, uint32_t array_size, const char *name); /*! * Verify a set of subaction paths for action creation. @@ -262,10 +225,7 @@ oxr_verify_subaction_paths_create(struct oxr_logger *log, * Verify a set of subaction paths for action sync. */ XrResult -oxr_verify_subaction_path_sync(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath path, - uint32_t index); +oxr_verify_subaction_path_sync(struct oxr_logger *log, struct oxr_instance *inst, XrPath path, uint32_t index); /*! * Verify a set of subaction paths for action state get. @@ -285,32 +245,26 @@ oxr_verify_view_config_type(struct oxr_logger *log, const char *view_conf_name); XrResult -oxr_verify_XrSessionCreateInfo(struct oxr_logger *, - const struct oxr_instance *, - const XrSessionCreateInfo *); +oxr_verify_XrSessionCreateInfo(struct oxr_logger *, const struct oxr_instance *, const XrSessionCreateInfo *); #if defined(XR_USE_PLATFORM_XLIB) && defined(XR_USE_GRAPHICS_API_OPENGL) XrResult -oxr_verify_XrGraphicsBindingOpenGLXlibKHR( - struct oxr_logger *, const XrGraphicsBindingOpenGLXlibKHR *); +oxr_verify_XrGraphicsBindingOpenGLXlibKHR(struct oxr_logger *, const XrGraphicsBindingOpenGLXlibKHR *); #endif // defined(XR_USE_PLATFORM_XLIB) && defined(XR_USE_GRAPHICS_API_OPENGL) #if defined(XR_USE_GRAPHICS_API_VULKAN) XrResult -oxr_verify_XrGraphicsBindingVulkanKHR(struct oxr_logger *, - const XrGraphicsBindingVulkanKHR *); +oxr_verify_XrGraphicsBindingVulkanKHR(struct oxr_logger *, const XrGraphicsBindingVulkanKHR *); #endif // defined(XR_USE_GRAPHICS_API_VULKAN) #if defined(XR_USE_PLATFORM_EGL) && defined(XR_USE_GRAPHICS_API_OPENGL) XrResult -oxr_verify_XrGraphicsBindingEGLMNDX(struct oxr_logger *log, - const XrGraphicsBindingEGLMNDX *next); +oxr_verify_XrGraphicsBindingEGLMNDX(struct oxr_logger *log, const XrGraphicsBindingEGLMNDX *next); #endif // defined(XR_USE_PLATFORM_EGL) && defined(XR_USE_GRAPHICS_API_OPENGL) #if defined(XR_USE_PLATFORM_ANDROID) && defined(XR_USE_GRAPHICS_API_OPENGL_ES) XrResult -oxr_verify_XrGraphicsBindingOpenGLESAndroidKHR( - struct oxr_logger *, const XrGraphicsBindingOpenGLESAndroidKHR *); +oxr_verify_XrGraphicsBindingOpenGLESAndroidKHR(struct oxr_logger *, const XrGraphicsBindingOpenGLESAndroidKHR *); #endif // defined(XR_USE_PLATFORM_ANDROID) && // defined(XR_USE_GRAPHICS_API_OPENGL_ES) diff --git a/src/xrt/state_trackers/oxr/oxr_binding.c b/src/xrt/state_trackers/oxr/oxr_binding.c index 8795e1e3e..c1b69001c 100644 --- a/src/xrt/state_trackers/oxr/oxr_binding.c +++ b/src/xrt/state_trackers/oxr/oxr_binding.c @@ -75,8 +75,7 @@ interaction_profile_find_or_create(struct oxr_logger *log, templ = &profiles[x]; XrPath t_path = XR_NULL_PATH; - oxr_path_get_or_create(log, inst, templ->path, - strlen(templ->path), &t_path); + oxr_path_get_or_create(log, inst, templ->path, strlen(templ->path), &t_path); if (t_path == path) { break; } @@ -88,8 +87,7 @@ interaction_profile_find_or_create(struct oxr_logger *log, return false; } - struct oxr_interaction_profile *p = - U_TYPED_CALLOC(struct oxr_interaction_profile); + struct oxr_interaction_profile *p = U_TYPED_CALLOC(struct oxr_interaction_profile); p->xname = templ->name; p->num_bindings = templ->num_bindings; @@ -109,9 +107,7 @@ interaction_profile_find_or_create(struct oxr_logger *log, } // Add to the list of currently created interaction profiles. - U_ARRAY_REALLOC_OR_FREE(inst->profiles, - struct oxr_interaction_profile *, - (inst->num_profiles + 1)); + U_ARRAY_REALLOC_OR_FREE(inst->profiles, struct oxr_interaction_profile *, (inst->num_profiles + 1)); inst->profiles[inst->num_profiles++] = p; *out_p = p; @@ -138,10 +134,7 @@ reset_all_keys(struct oxr_binding *bindings, size_t num_bindings) } static void -add_key_to_matching_bindings(struct oxr_binding *bindings, - size_t num_bindings, - XrPath path, - uint32_t key) +add_key_to_matching_bindings(struct oxr_binding *bindings, size_t num_bindings, XrPath path, uint32_t key) { for (size_t x = 0; x < num_bindings; x++) { struct oxr_binding *b = &bindings[x]; @@ -161,10 +154,8 @@ add_key_to_matching_bindings(struct oxr_binding *bindings, } U_ARRAY_REALLOC_OR_FREE(b->keys, uint32_t, (b->num_keys + 1)); - U_ARRAY_REALLOC_OR_FREE(b->preferred_binding_path_index, - uint32_t, (b->num_keys + 1)); - b->preferred_binding_path_index[b->num_keys] = - preferred_path_index; + U_ARRAY_REALLOC_OR_FREE(b->preferred_binding_path_index, uint32_t, (b->num_keys + 1)); + b->preferred_binding_path_index[b->num_keys] = preferred_path_index; b->keys[b->num_keys++] = key; } } @@ -230,11 +221,10 @@ get_sub_path_str(enum oxr_sub_action_path sub_path) } static XrPath -get_interaction_bound_to_sub_path(struct oxr_session *sess, - enum oxr_sub_action_path sub_path) +get_interaction_bound_to_sub_path(struct oxr_session *sess, enum oxr_sub_action_path sub_path) { switch (sub_path) { -#define OXR_PATH_MEMBER(lower, CAP, _) \ +#define OXR_PATH_MEMBER(lower, CAP, _) \ case OXR_SUB_ACTION_PATH_##CAP: return sess->lower; OXR_FOR_EACH_VALID_SUBACTION_PATH_DETAILED(OXR_PATH_MEMBER) @@ -307,8 +297,7 @@ oxr_find_profile_for_device(struct oxr_logger *log, // clang-format on return; case XRT_DEVICE_DAYDREAM: - interaction_profile_find( - log, inst, inst->path_cache.khr_simple_controller, out_p); + interaction_profile_find(log, inst, inst->path_cache.khr_simple_controller, out_p); return; case XRT_DEVICE_SIMPLE_CONTROLLER: // clang-format off @@ -403,10 +392,9 @@ oxr_binding_destroy_all(struct oxr_logger *log, struct oxr_instance *inst) */ XrResult -oxr_action_suggest_interaction_profile_bindings( - struct oxr_logger *log, - struct oxr_instance *inst, - const XrInteractionProfileSuggestedBinding *suggestedBindings) +oxr_action_suggest_interaction_profile_bindings(struct oxr_logger *log, + struct oxr_instance *inst, + const XrInteractionProfileSuggestedBinding *suggestedBindings) { struct oxr_interaction_profile *p = NULL; @@ -426,24 +414,20 @@ oxr_action_suggest_interaction_profile_bindings( reset_all_keys(bindings, num_bindings); for (size_t i = 0; i < suggestedBindings->countSuggestedBindings; i++) { - const XrActionSuggestedBinding *s = - &suggestedBindings->suggestedBindings[i]; - struct oxr_action *act = - XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_action *, s->action); + const XrActionSuggestedBinding *s = &suggestedBindings->suggestedBindings[i]; + struct oxr_action *act = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_action *, s->action); - add_key_to_matching_bindings(bindings, num_bindings, s->binding, - act->act_key); + add_key_to_matching_bindings(bindings, num_bindings, s->binding, act->act_key); } return XR_SUCCESS; } XrResult -oxr_action_get_current_interaction_profile( - struct oxr_logger *log, - struct oxr_session *sess, - XrPath topLevelUserPath, - XrInteractionProfileState *interactionProfile) +oxr_action_get_current_interaction_profile(struct oxr_logger *log, + struct oxr_session *sess, + XrPath topLevelUserPath, + XrInteractionProfileState *interactionProfile) { struct oxr_instance *inst = sess->sys->inst; @@ -452,36 +436,33 @@ oxr_action_get_current_interaction_profile( "xrAttachSessionActionSets has not been " "called on this session."); } -#define IDENTIFY_TOP_LEVEL_PATH(X) \ - if (topLevelUserPath == inst->path_cache.X) { \ - interactionProfile->interactionProfile = sess->X; \ +#define IDENTIFY_TOP_LEVEL_PATH(X) \ + if (topLevelUserPath == inst->path_cache.X) { \ + interactionProfile->interactionProfile = sess->X; \ } else OXR_FOR_EACH_VALID_SUBACTION_PATH(IDENTIFY_TOP_LEVEL_PATH) { // else clause - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Top level path not handled?!"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Top level path not handled?!"); } #undef IDENTIFY_TOP_LEVEL_PATH return XR_SUCCESS; } XrResult -oxr_action_get_input_source_localized_name( - struct oxr_logger *log, - struct oxr_session *sess, - const XrInputSourceLocalizedNameGetInfo *getInfo, - uint32_t bufferCapacityInput, - uint32_t *bufferCountOutput, - char *buffer) +oxr_action_get_input_source_localized_name(struct oxr_logger *log, + struct oxr_session *sess, + const XrInputSourceLocalizedNameGetInfo *getInfo, + uint32_t bufferCapacityInput, + uint32_t *bufferCountOutput, + char *buffer) { char temp[1024] = {0}; ssize_t current = 0; enum oxr_sub_action_path sub_path = 0; - if (!get_sub_path_from_path(log, sess->sys->inst, getInfo->sourcePath, - &sub_path)) { + if (!get_sub_path_from_path(log, sess->sys->inst, getInfo->sourcePath, &sub_path)) { return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(getInfo->sourcePath) doesn't start with a " "valid sub_path"); @@ -499,39 +480,32 @@ oxr_action_get_input_source_localized_name( struct oxr_interaction_profile *oip = NULL; interaction_profile_find_or_create(log, sess->sys->inst, path, &oip); if (oip == NULL) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "no interaction profile found"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "no interaction profile found"); } // Add which hand to use. - if (getInfo->whichComponents & - XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT) { - add_string(temp, sizeof(temp), ¤t, - get_sub_path_str(sub_path)); + if (getInfo->whichComponents & XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT) { + add_string(temp, sizeof(temp), ¤t, get_sub_path_str(sub_path)); } // Add a human readable and localized name of the device. - if ((getInfo->whichComponents & - XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT) != 0) { + if ((getInfo->whichComponents & XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT) != 0) { add_string(temp, sizeof(temp), ¤t, oip->localized_name); } //! @todo This implementation is very very very ugly. - if ((getInfo->whichComponents & - XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT) != 0) { + if ((getInfo->whichComponents & XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT) != 0) { /* * The above enum is miss-named it should be called identifier * instead of component. */ add_string(temp, sizeof(temp), ¤t, - get_identifier_str_in_profile( - log, sess->sys->inst, getInfo->sourcePath, oip)); + get_identifier_str_in_profile(log, sess->sys->inst, getInfo->sourcePath, oip)); } // Include the null character. current += 1; - OXR_TWO_CALL_HELPER(log, bufferCapacityInput, bufferCountOutput, buffer, - (size_t)current, temp, + OXR_TWO_CALL_HELPER(log, bufferCapacityInput, bufferCountOutput, buffer, (size_t)current, temp, oxr_session_success_result(sess)); } diff --git a/src/xrt/state_trackers/oxr/oxr_binding_data.h b/src/xrt/state_trackers/oxr/oxr_binding_data.h index 5f25dd9c7..7268bdc41 100644 --- a/src/xrt/state_trackers/oxr/oxr_binding_data.h +++ b/src/xrt/state_trackers/oxr/oxr_binding_data.h @@ -40,101 +40,101 @@ struct profile_template * */ -#define MAKE_INPUT(COMPONENT, NAME, SUFFIX, INPUT) \ - { \ - .sub_path = OXR_SUB_ACTION_PATH_LEFT, \ - .localized_name = NAME, \ - .paths = \ - { \ - "/user/hand/left/input/" #COMPONENT "/" #SUFFIX, \ - "/user/hand/left/input/" #COMPONENT, \ - NULL, \ - }, \ - .input = INPUT, \ - }, \ - { \ - .sub_path = OXR_SUB_ACTION_PATH_RIGHT, \ - .localized_name = NAME, \ - .paths = \ - { \ - "/user/hand/right/input/" #COMPONENT "/" #SUFFIX, \ - "/user/hand/right/input/" #COMPONENT, \ - NULL, \ - }, \ - .input = INPUT, \ +#define MAKE_INPUT(COMPONENT, NAME, SUFFIX, INPUT) \ + { \ + .sub_path = OXR_SUB_ACTION_PATH_LEFT, \ + .localized_name = NAME, \ + .paths = \ + { \ + "/user/hand/left/input/" #COMPONENT "/" #SUFFIX, \ + "/user/hand/left/input/" #COMPONENT, \ + NULL, \ + }, \ + .input = INPUT, \ + }, \ + { \ + .sub_path = OXR_SUB_ACTION_PATH_RIGHT, \ + .localized_name = NAME, \ + .paths = \ + { \ + "/user/hand/right/input/" #COMPONENT "/" #SUFFIX, \ + "/user/hand/right/input/" #COMPONENT, \ + NULL, \ + }, \ + .input = INPUT, \ }, // creates an input that can not be "downgraded" to the top level path. // e.g. don't bind ../trackpad/click, ../trackpad/touch with just ../trackpad -#define MAKE_INPUT_SUFFIX_ONLY(COMPONENT, NAME, SUFFIX, INPUT) \ - { \ - .sub_path = OXR_SUB_ACTION_PATH_LEFT, \ - .localized_name = NAME, \ - .paths = \ - { \ - "/user/hand/left/input/" #COMPONENT "/" #SUFFIX, \ - NULL, \ - }, \ - .input = INPUT, \ - }, \ - { \ - .sub_path = OXR_SUB_ACTION_PATH_RIGHT, \ - .localized_name = NAME, \ - .paths = \ - { \ - "/user/hand/right/input/" #COMPONENT "/" #SUFFIX, \ - NULL, \ - }, \ - .input = INPUT, \ +#define MAKE_INPUT_SUFFIX_ONLY(COMPONENT, NAME, SUFFIX, INPUT) \ + { \ + .sub_path = OXR_SUB_ACTION_PATH_LEFT, \ + .localized_name = NAME, \ + .paths = \ + { \ + "/user/hand/left/input/" #COMPONENT "/" #SUFFIX, \ + NULL, \ + }, \ + .input = INPUT, \ + }, \ + { \ + .sub_path = OXR_SUB_ACTION_PATH_RIGHT, \ + .localized_name = NAME, \ + .paths = \ + { \ + "/user/hand/right/input/" #COMPONENT "/" #SUFFIX, \ + NULL, \ + }, \ + .input = INPUT, \ }, // creates an input with a top level path and /x and /y sub paths -#define MAKE_INPUT_VEC2F(COMPONENT, NAME, INPUT) \ - { \ - .sub_path = OXR_SUB_ACTION_PATH_LEFT, \ - .localized_name = NAME, \ - .paths = \ - { \ - "/user/hand/left/input/" #COMPONENT, \ - "/user/hand/left/input/" #COMPONENT "/x", \ - "/user/hand/left/input/" #COMPONENT "/y", \ - NULL, \ - }, \ - .input = INPUT, \ - }, \ - { \ - .sub_path = OXR_SUB_ACTION_PATH_RIGHT, \ - .localized_name = NAME, \ - .paths = \ - { \ - "/user/hand/right/input/" #COMPONENT, \ - "/user/hand/right/input/" #COMPONENT "/x", \ - "/user/hand/right/input/" #COMPONENT "/y", \ - NULL, \ - }, \ - .input = INPUT, \ +#define MAKE_INPUT_VEC2F(COMPONENT, NAME, INPUT) \ + { \ + .sub_path = OXR_SUB_ACTION_PATH_LEFT, \ + .localized_name = NAME, \ + .paths = \ + { \ + "/user/hand/left/input/" #COMPONENT, \ + "/user/hand/left/input/" #COMPONENT "/x", \ + "/user/hand/left/input/" #COMPONENT "/y", \ + NULL, \ + }, \ + .input = INPUT, \ + }, \ + { \ + .sub_path = OXR_SUB_ACTION_PATH_RIGHT, \ + .localized_name = NAME, \ + .paths = \ + { \ + "/user/hand/right/input/" #COMPONENT, \ + "/user/hand/right/input/" #COMPONENT "/x", \ + "/user/hand/right/input/" #COMPONENT "/y", \ + NULL, \ + }, \ + .input = INPUT, \ }, -#define MAKE_OUTPUT(COMPONENT, NAME, OUTPUT) \ - { \ - .sub_path = OXR_SUB_ACTION_PATH_LEFT, \ - .localized_name = NAME, \ - .paths = \ - { \ - "/user/hand/left/output/" #COMPONENT, \ - NULL, \ - }, \ - .output = OUTPUT, \ - }, \ - { \ - .sub_path = OXR_SUB_ACTION_PATH_RIGHT, \ - .localized_name = NAME, \ - .paths = \ - { \ - "/user/hand/right/output/" #COMPONENT, \ - NULL, \ - }, \ - .output = OUTPUT, \ +#define MAKE_OUTPUT(COMPONENT, NAME, OUTPUT) \ + { \ + .sub_path = OXR_SUB_ACTION_PATH_LEFT, \ + .localized_name = NAME, \ + .paths = \ + { \ + "/user/hand/left/output/" #COMPONENT, \ + NULL, \ + }, \ + .output = OUTPUT, \ + }, \ + { \ + .sub_path = OXR_SUB_ACTION_PATH_RIGHT, \ + .localized_name = NAME, \ + .paths = \ + { \ + "/user/hand/right/output/" #COMPONENT, \ + NULL, \ + }, \ + .output = OUTPUT, \ }, diff --git a/src/xrt/state_trackers/oxr/oxr_chain.h b/src/xrt/state_trackers/oxr/oxr_chain.h index 1f89df8cf..3f9e77032 100644 --- a/src/xrt/state_trackers/oxr/oxr_chain.h +++ b/src/xrt/state_trackers/oxr/oxr_chain.h @@ -49,7 +49,7 @@ oxr_find_input_in_chain(const void *ptr, XrStructureType desired) * Note: There is no protection here to ensure that STRUCTURE_TYPE_ENUM (an * XrStructureType value) and TYPE (a type name) actually match! */ -#define OXR_GET_INPUT_FROM_CHAIN(PTR, STRUCTURE_TYPE_ENUM, TYPE) \ +#define OXR_GET_INPUT_FROM_CHAIN(PTR, STRUCTURE_TYPE_ENUM, TYPE) \ ((TYPE const *)oxr_find_input_in_chain(PTR, STRUCTURE_TYPE_ENUM)) /*! @@ -82,7 +82,7 @@ oxr_find_output_in_chain(void *ptr, XrStructureType desired) * Note: There is no protection here to ensure that STRUCTURE_TYPE_ENUM (an * XrStructureType value) and TYPE (a type name) actually match! */ -#define OXR_GET_OUTPUT_FROM_CHAIN(PTR, STRUCTURE_TYPE_ENUM, TYPE) \ +#define OXR_GET_OUTPUT_FROM_CHAIN(PTR, STRUCTURE_TYPE_ENUM, TYPE) \ ((TYPE *)oxr_find_output_in_chain(PTR, STRUCTURE_TYPE_ENUM)) /*! diff --git a/src/xrt/state_trackers/oxr/oxr_event.c b/src/xrt/state_trackers/oxr/oxr_event.c index 7c3cac3b1..a20bd5ff3 100644 --- a/src/xrt/state_trackers/oxr/oxr_event.c +++ b/src/xrt/state_trackers/oxr/oxr_event.c @@ -89,28 +89,22 @@ push(struct oxr_instance *inst, struct oxr_event *event) } } -#define ALLOC(log, inst, event, extra) \ - do { \ - XrResult ret = \ - oxr_event_alloc(log, inst, sizeof(**extra), event); \ - if (ret != XR_SUCCESS) { \ - return ret; \ - } \ - *((void **)extra) = oxr_event_extra(*event); \ +#define ALLOC(log, inst, event, extra) \ + do { \ + XrResult ret = oxr_event_alloc(log, inst, sizeof(**extra), event); \ + if (ret != XR_SUCCESS) { \ + return ret; \ + } \ + *((void **)extra) = oxr_event_extra(*event); \ } while (false) static XrResult -oxr_event_alloc(struct oxr_logger *log, - struct oxr_instance *inst, - size_t size, - struct oxr_event **out_event) +oxr_event_alloc(struct oxr_logger *log, struct oxr_instance *inst, size_t size, struct oxr_event **out_event) { - struct oxr_event *event = U_CALLOC_WITH_CAST( - struct oxr_event, sizeof(struct oxr_event) + size); + struct oxr_event *event = U_CALLOC_WITH_CAST(struct oxr_event, sizeof(struct oxr_event) + size); if (event == NULL) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Out of memory"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Out of memory"); } event->next = NULL; @@ -129,13 +123,11 @@ is_session_link_to_event(struct oxr_event *event, XrSession session) switch (*type) { case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: { - XrEventDataSessionStateChanged *changed = - (XrEventDataSessionStateChanged *)type; + XrEventDataSessionStateChanged *changed = (XrEventDataSessionStateChanged *)type; return changed->session == session; } case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: { - XrEventDataInteractionProfileChanged *changed = - (XrEventDataInteractionProfileChanged *)type; + XrEventDataInteractionProfileChanged *changed = (XrEventDataInteractionProfileChanged *)type; return changed->session == session; } default: return false; @@ -165,9 +157,7 @@ oxr_event_push_XrEventDataSessionStateChanged(struct oxr_logger *log, changed->state = state; changed->time = time; - event->result = state == XR_SESSION_STATE_LOSS_PENDING - ? XR_SESSION_LOSS_PENDING - : XR_SUCCESS; + event->result = state == XR_SESSION_STATE_LOSS_PENDING ? XR_SESSION_LOSS_PENDING : XR_SUCCESS; lock(inst); push(inst, event); @@ -178,8 +168,7 @@ oxr_event_push_XrEventDataSessionStateChanged(struct oxr_logger *log, XrResult -oxr_event_push_XrEventDataInteractionProfileChanged(struct oxr_logger *log, - struct oxr_session *sess) +oxr_event_push_XrEventDataInteractionProfileChanged(struct oxr_logger *log, struct oxr_session *sess) { struct oxr_instance *inst = sess->sys->inst; XrEventDataSessionStateChanged *changed; @@ -198,8 +187,9 @@ oxr_event_push_XrEventDataInteractionProfileChanged(struct oxr_logger *log, } XrResult -oxr_event_push_XrEventDataMainSessionVisibilityChangedEXTX( - struct oxr_logger *log, struct oxr_session *sess, bool visible) +oxr_event_push_XrEventDataMainSessionVisibilityChangedEXTX(struct oxr_logger *log, + struct oxr_session *sess, + bool visible) { struct oxr_instance *inst = sess->sys->inst; XrEventDataMainSessionVisibilityChangedEXTX *changed; @@ -218,8 +208,7 @@ oxr_event_push_XrEventDataMainSessionVisibilityChangedEXTX( } XrResult -oxr_event_remove_session_events(struct oxr_logger *log, - struct oxr_session *sess) +oxr_event_remove_session_events(struct oxr_logger *log, struct oxr_session *sess) { struct oxr_instance *inst = sess->sys->inst; XrSession session = oxr_session_to_openxr(sess); @@ -251,9 +240,7 @@ oxr_event_remove_session_events(struct oxr_logger *log, } XrResult -oxr_poll_event(struct oxr_logger *log, - struct oxr_instance *inst, - XrEventDataBuffer *eventData) +oxr_poll_event(struct oxr_logger *log, struct oxr_instance *inst, XrEventDataBuffer *eventData) { struct oxr_session *sess = inst->sessions; while (sess) { diff --git a/src/xrt/state_trackers/oxr/oxr_extension_support.h b/src/xrt/state_trackers/oxr/oxr_extension_support.h index b1ed8e5da..f6f85d8c9 100644 --- a/src/xrt/state_trackers/oxr/oxr_extension_support.h +++ b/src/xrt/state_trackers/oxr/oxr_extension_support.h @@ -25,8 +25,7 @@ */ #if defined(XR_KHR_android_create_instance) && defined(XR_USE_PLATFORM_ANDROID) #define OXR_HAVE_KHR_android_create_instance -#define OXR_EXTENSION_SUPPORT_KHR_android_create_instance(_) \ - _(KHR_android_create_instance, KHR_ANDROID_CREATE_INSTANCE) +#define OXR_EXTENSION_SUPPORT_KHR_android_create_instance(_) _(KHR_android_create_instance, KHR_ANDROID_CREATE_INSTANCE) #else #define OXR_EXTENSION_SUPPORT_KHR_android_create_instance(_) #endif @@ -37,8 +36,7 @@ */ #if defined(XR_KHR_convert_timespec_time) && defined(XR_USE_TIMESPEC) #define OXR_HAVE_KHR_convert_timespec_time -#define OXR_EXTENSION_SUPPORT_KHR_convert_timespec_time(_) \ - _(KHR_convert_timespec_time, KHR_CONVERT_TIMESPEC_TIME) +#define OXR_EXTENSION_SUPPORT_KHR_convert_timespec_time(_) _(KHR_convert_timespec_time, KHR_CONVERT_TIMESPEC_TIME) #else #define OXR_EXTENSION_SUPPORT_KHR_convert_timespec_time(_) #endif @@ -49,8 +47,7 @@ */ #if defined(XR_KHR_opengl_enable) && defined(XR_USE_GRAPHICS_API_OPENGL) #define OXR_HAVE_KHR_opengl_enable -#define OXR_EXTENSION_SUPPORT_KHR_opengl_enable(_) \ - _(KHR_opengl_enable, KHR_OPENGL_ENABLE) +#define OXR_EXTENSION_SUPPORT_KHR_opengl_enable(_) _(KHR_opengl_enable, KHR_OPENGL_ENABLE) #else #define OXR_EXTENSION_SUPPORT_KHR_opengl_enable(_) #endif @@ -61,8 +58,7 @@ */ #if defined(XR_KHR_opengl_es_enable) && defined(XR_USE_GRAPHICS_API_OPENGL_ES) #define OXR_HAVE_KHR_opengl_es_enable -#define OXR_EXTENSION_SUPPORT_KHR_opengl_es_enable(_) \ - _(KHR_opengl_es_enable, KHR_OPENGL_ES_ENABLE) +#define OXR_EXTENSION_SUPPORT_KHR_opengl_es_enable(_) _(KHR_opengl_es_enable, KHR_OPENGL_ES_ENABLE) #else #define OXR_EXTENSION_SUPPORT_KHR_opengl_es_enable(_) #endif @@ -73,8 +69,7 @@ */ #if defined(XR_KHR_vulkan_enable) && defined(XR_USE_GRAPHICS_API_VULKAN) #define OXR_HAVE_KHR_vulkan_enable -#define OXR_EXTENSION_SUPPORT_KHR_vulkan_enable(_) \ - _(KHR_vulkan_enable, KHR_VULKAN_ENABLE) +#define OXR_EXTENSION_SUPPORT_KHR_vulkan_enable(_) _(KHR_vulkan_enable, KHR_VULKAN_ENABLE) #else #define OXR_EXTENSION_SUPPORT_KHR_vulkan_enable(_) #endif @@ -85,8 +80,7 @@ */ #if defined(XR_KHR_vulkan_enable2) && defined(XR_USE_GRAPHICS_API_VULKAN) #define OXR_HAVE_KHR_vulkan_enable2 -#define OXR_EXTENSION_SUPPORT_KHR_vulkan_enable2(_) \ - _(KHR_vulkan_enable2, KHR_VULKAN_ENABLE2) +#define OXR_EXTENSION_SUPPORT_KHR_vulkan_enable2(_) _(KHR_vulkan_enable2, KHR_VULKAN_ENABLE2) #else #define OXR_EXTENSION_SUPPORT_KHR_vulkan_enable2(_) #endif @@ -95,11 +89,9 @@ /* * XR_KHR_composition_layer_depth */ -#if defined(XR_KHR_composition_layer_depth) && \ - defined(XRT_FEATURE_OPENXR_LAYER_DEPTH) +#if defined(XR_KHR_composition_layer_depth) && defined(XRT_FEATURE_OPENXR_LAYER_DEPTH) #define OXR_HAVE_KHR_composition_layer_depth -#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_depth(_) \ - _(KHR_composition_layer_depth, KHR_COMPOSITION_LAYER_DEPTH) +#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_depth(_) _(KHR_composition_layer_depth, KHR_COMPOSITION_LAYER_DEPTH) #else #define OXR_EXTENSION_SUPPORT_KHR_composition_layer_depth(_) #endif @@ -108,11 +100,9 @@ /* * XR_KHR_composition_layer_cube */ -#if defined(XR_KHR_composition_layer_cube) && \ - defined(XRT_FEATURE_OPENXR_LAYER_CUBE) +#if defined(XR_KHR_composition_layer_cube) && defined(XRT_FEATURE_OPENXR_LAYER_CUBE) #define OXR_HAVE_KHR_composition_layer_cube -#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_cube(_) \ - _(KHR_composition_layer_cube, KHR_COMPOSITION_LAYER_CUBE) +#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_cube(_) _(KHR_composition_layer_cube, KHR_COMPOSITION_LAYER_CUBE) #else #define OXR_EXTENSION_SUPPORT_KHR_composition_layer_cube(_) #endif @@ -121,10 +111,9 @@ /* * XR_KHR_composition_layer_cylinder */ -#if defined(XR_KHR_composition_layer_cylinder) && \ - defined(XRT_FEATURE_OPENXR_LAYER_CYLINDER) +#if defined(XR_KHR_composition_layer_cylinder) && defined(XRT_FEATURE_OPENXR_LAYER_CYLINDER) #define OXR_HAVE_KHR_composition_layer_cylinder -#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_cylinder(_) \ +#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_cylinder(_) \ _(KHR_composition_layer_cylinder, KHR_COMPOSITION_LAYER_CYLINDER) #else #define OXR_EXTENSION_SUPPORT_KHR_composition_layer_cylinder(_) @@ -134,10 +123,9 @@ /* * XR_KHR_composition_layer_equirect */ -#if defined(XR_KHR_composition_layer_equirect) && \ - defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT1) +#if defined(XR_KHR_composition_layer_equirect) && defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT1) #define OXR_HAVE_KHR_composition_layer_equirect -#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_equirect(_) \ +#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_equirect(_) \ _(KHR_composition_layer_equirect, KHR_COMPOSITION_LAYER_EQUIRECT) #else #define OXR_EXTENSION_SUPPORT_KHR_composition_layer_equirect(_) @@ -147,10 +135,9 @@ /* * XR_KHR_composition_layer_equirect2 */ -#if defined(XR_KHR_composition_layer_equirect2) && \ - defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT2) +#if defined(XR_KHR_composition_layer_equirect2) && defined(XRT_FEATURE_OPENXR_LAYER_EQUIRECT2) #define OXR_HAVE_KHR_composition_layer_equirect2 -#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_equirect2(_) \ +#define OXR_EXTENSION_SUPPORT_KHR_composition_layer_equirect2(_) \ _(KHR_composition_layer_equirect2, KHR_COMPOSITION_LAYER_EQUIRECT2) #else #define OXR_EXTENSION_SUPPORT_KHR_composition_layer_equirect2(_) @@ -162,8 +149,7 @@ */ #if defined(XR_EXT_debug_utils) #define OXR_HAVE_EXT_debug_utils -#define OXR_EXTENSION_SUPPORT_EXT_debug_utils(_) \ - _(EXT_debug_utils, EXT_DEBUG_UTILS) +#define OXR_EXTENSION_SUPPORT_EXT_debug_utils(_) _(EXT_debug_utils, EXT_DEBUG_UTILS) #else #define OXR_EXTENSION_SUPPORT_EXT_debug_utils(_) #endif @@ -185,9 +171,8 @@ */ #if defined(XR_MND_swapchain_usage_input_attachment_bit) #define OXR_HAVE_MND_swapchain_usage_input_attachment_bit -#define OXR_EXTENSION_SUPPORT_MND_swapchain_usage_input_attachment_bit(_) \ - _(MND_swapchain_usage_input_attachment_bit, \ - MND_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT) +#define OXR_EXTENSION_SUPPORT_MND_swapchain_usage_input_attachment_bit(_) \ + _(MND_swapchain_usage_input_attachment_bit, MND_SWAPCHAIN_USAGE_INPUT_ATTACHMENT_BIT) #else #define OXR_EXTENSION_SUPPORT_MND_swapchain_usage_input_attachment_bit(_) #endif @@ -207,11 +192,9 @@ /* * XR_MNDX_egl_enable */ -#if defined(XR_MNDX_egl_enable) && defined(XR_USE_PLATFORM_EGL) && \ - defined(XR_USE_GRAPHICS_API_OPENGL) +#if defined(XR_MNDX_egl_enable) && defined(XR_USE_PLATFORM_EGL) && defined(XR_USE_GRAPHICS_API_OPENGL) #define OXR_HAVE_MNDX_egl_enable -#define OXR_EXTENSION_SUPPORT_MNDX_egl_enable(_) \ - _(MNDX_egl_enable, MNDX_EGL_ENABLE) +#define OXR_EXTENSION_SUPPORT_MNDX_egl_enable(_) _(MNDX_egl_enable, MNDX_EGL_ENABLE) #else #define OXR_EXTENSION_SUPPORT_MNDX_egl_enable(_) #endif @@ -222,7 +205,7 @@ */ #if defined(XR_MNDX_ball_on_a_stick_controller) #define OXR_HAVE_MNDX_ball_on_a_stick_controller -#define OXR_EXTENSION_SUPPORT_MNDX_ball_on_a_stick_controller(_) \ +#define OXR_EXTENSION_SUPPORT_MNDX_ball_on_a_stick_controller(_) \ _(MNDX_ball_on_a_stick_controller, MNDX_BALL_ON_A_STICK_CONTROLLER) #else #define OXR_EXTENSION_SUPPORT_MNDX_ball_on_a_stick_controller(_) @@ -234,8 +217,7 @@ */ #if defined(XR_EXT_hand_tracking) #define OXR_HAVE_EXT_hand_tracking -#define OXR_EXTENSION_SUPPORT_EXT_hand_tracking(_) \ - _(EXT_hand_tracking, EXT_HAND_TRACKING) +#define OXR_EXTENSION_SUPPORT_EXT_hand_tracking(_) _(EXT_hand_tracking, EXT_HAND_TRACKING) #else #define OXR_EXTENSION_SUPPORT_EXT_hand_tracking(_) #endif diff --git a/src/xrt/state_trackers/oxr/oxr_handle.h b/src/xrt/state_trackers/oxr/oxr_handle.h index 650c78e6e..db3218286 100644 --- a/src/xrt/state_trackers/oxr/oxr_handle.h +++ b/src/xrt/state_trackers/oxr/oxr_handle.h @@ -65,9 +65,8 @@ oxr_handle_allocate_and_init(struct oxr_logger *log, * * @relates oxr_handle_base */ -#define OXR_ALLOCATE_HANDLE(LOG, OUT, DEBUG, DESTROY, PARENT) \ - oxr_handle_allocate_and_init(LOG, sizeof(*OUT), DEBUG, DESTROY, \ - PARENT, (void **)&OUT) +#define OXR_ALLOCATE_HANDLE(LOG, OUT, DEBUG, DESTROY, PARENT) \ + oxr_handle_allocate_and_init(LOG, sizeof(*OUT), DEBUG, DESTROY, PARENT, (void **)&OUT) /*! * Allocate memory for a handle, returning in case of failure. @@ -83,13 +82,12 @@ oxr_handle_allocate_and_init(struct oxr_logger *log, * * @relates oxr_handle_base */ -#define OXR_ALLOCATE_HANDLE_OR_RETURN(LOG, OUT, DEBUG, DESTROY, PARENT) \ - do { \ - XrResult allocResult = \ - OXR_ALLOCATE_HANDLE(LOG, OUT, DEBUG, DESTROY, PARENT); \ - if (allocResult != XR_SUCCESS) { \ - return allocResult; \ - } \ +#define OXR_ALLOCATE_HANDLE_OR_RETURN(LOG, OUT, DEBUG, DESTROY, PARENT) \ + do { \ + XrResult allocResult = OXR_ALLOCATE_HANDLE(LOG, OUT, DEBUG, DESTROY, PARENT); \ + if (allocResult != XR_SUCCESS) { \ + return allocResult; \ + } \ } while (0) #ifdef __cplusplus diff --git a/src/xrt/state_trackers/oxr/oxr_handle_base.c b/src/xrt/state_trackers/oxr/oxr_handle_base.c index d6b396ed2..72c66f67d 100644 --- a/src/xrt/state_trackers/oxr/oxr_handle_base.c +++ b/src/xrt/state_trackers/oxr/oxr_handle_base.c @@ -19,23 +19,22 @@ #include -#define HANDLE_LIFECYCLE_LOG(log, ...) \ - if (log->inst != NULL && log->inst->lifecycle_verbose) { \ - oxr_log(log, " Handle Lifecycle: " __VA_ARGS__); \ +#define HANDLE_LIFECYCLE_LOG(log, ...) \ + if (log->inst != NULL && log->inst->lifecycle_verbose) { \ + oxr_log(log, " Handle Lifecycle: " __VA_ARGS__); \ } // Variation of HANDLE_LIFECYCLE_LOG() to wrap a handle free() which might // potentially free the instance (in which logger info is stored). -#define HANDLE_LIFECYCLE_LOG_SCOPED_BEGIN(log) \ - { \ - const bool _log_lifecycle_verbose = \ - log->inst != NULL && log->inst->lifecycle_verbose; -#define HANDLE_LIFECYCLE_LOG_SCOPED_END \ - } \ +#define HANDLE_LIFECYCLE_LOG_SCOPED_BEGIN(log) \ + { \ + const bool _log_lifecycle_verbose = log->inst != NULL && log->inst->lifecycle_verbose; +#define HANDLE_LIFECYCLE_LOG_SCOPED_END \ + } \ (void)0 -#define HANDLE_LIFECYCLE_LOG_SCOPED(log, ...) \ - if (_log_lifecycle_verbose) { \ - oxr_log(log, " Handle Lifecycle: " __VA_ARGS__); \ +#define HANDLE_LIFECYCLE_LOG_SCOPED(log, ...) \ + if (_log_lifecycle_verbose) { \ + oxr_log(log, " Handle Lifecycle: " __VA_ARGS__); \ } @@ -63,20 +62,16 @@ oxr_handle_init(struct oxr_logger *log, assert(destroy != NULL); assert(debug != 0); - HANDLE_LIFECYCLE_LOG( - log, "[init %p] Initializing handle, parent handle = %p", - (void *)hb, (void *)parent); + HANDLE_LIFECYCLE_LOG(log, "[init %p] Initializing handle, parent handle = %p", (void *)hb, (void *)parent); hb->state = OXR_HANDLE_STATE_UNINITIALIZED; if (parent != NULL) { if (parent->state != OXR_HANDLE_STATE_LIVE) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "Handle %p given parent %p in invalid state: %s", - (void *)parent, (void *)hb, - oxr_handle_state_to_string(parent->state)); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "Handle %p given parent %p in invalid state: %s", (void *)parent, (void *)hb, + oxr_handle_state_to_string(parent->state)); } bool placed = false; @@ -117,8 +112,7 @@ oxr_handle_allocate_and_init(struct oxr_logger *log, * This allocation call, taking a size, not a type, is why this * function isn't recommended for direct use. */ - struct oxr_handle_base *hb = - U_CALLOC_WITH_CAST(struct oxr_handle_base, size); + struct oxr_handle_base *hb = U_CALLOC_WITH_CAST(struct oxr_handle_base, size); XrResult result = oxr_handle_init(log, hb, debug, destroy, parent); if (result != XR_SUCCESS) { free(hb); @@ -136,9 +130,7 @@ oxr_handle_allocate_and_init(struct oxr_logger *log, * recursion. */ static XrResult -oxr_handle_do_destroy(struct oxr_logger *log, - struct oxr_handle_base *hb, - int level) +oxr_handle_do_destroy(struct oxr_logger *log, struct oxr_handle_base *hb, int level) { HANDLE_LIFECYCLE_LOG(log, @@ -153,11 +145,10 @@ oxr_handle_do_destroy(struct oxr_logger *log, for (int i = 0; i < XRT_MAX_HANDLE_CHILDREN; ++i) { if (parent->children[i] == hb) { - HANDLE_LIFECYCLE_LOG( - log, - "[%d: destroying %p] Removing handle from " - "child slot %d in parent %p", - level, (void *)hb, i, (void *)hb->parent); + HANDLE_LIFECYCLE_LOG(log, + "[%d: destroying %p] Removing handle from " + "child slot %d in parent %p", + level, (void *)hb, i, (void *)hb->parent); parent->children[i] = NULL; found = true; @@ -165,9 +156,7 @@ oxr_handle_do_destroy(struct oxr_logger *log, } } if (!found) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "Parent handle does not refer to this handle"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Parent handle does not refer to this handle"); } /* clear parent pointer */ @@ -179,8 +168,7 @@ oxr_handle_do_destroy(struct oxr_logger *log, struct oxr_handle_base *child = hb->children[i]; if (child != NULL) { - XrResult result = - oxr_handle_do_destroy(log, child, level + 1); + XrResult result = oxr_handle_do_destroy(log, child, level + 1); if (result != XR_SUCCESS) { return result; } @@ -191,16 +179,14 @@ oxr_handle_do_destroy(struct oxr_logger *log, HANDLE_LIFECYCLE_LOG_SCOPED_BEGIN(log) { /* Destroy self */ - HANDLE_LIFECYCLE_LOG_SCOPED( - log, "[%d: destroying %p] Calling handle object destructor", - level, (void *)hb); + HANDLE_LIFECYCLE_LOG_SCOPED(log, "[%d: destroying %p] Calling handle object destructor", level, + (void *)hb); hb->state = OXR_HANDLE_STATE_DESTROYED; XrResult result = hb->destroy(log, hb); if (result != XR_SUCCESS) { return result; } - HANDLE_LIFECYCLE_LOG_SCOPED(log, "r%d: destroying %p] Done", - level, (void *)hb); + HANDLE_LIFECYCLE_LOG_SCOPED(log, "r%d: destroying %p] Done", level, (void *)hb); } HANDLE_LIFECYCLE_LOG_SCOPED_END; @@ -216,15 +202,11 @@ oxr_handle_destroy(struct oxr_logger *log, struct oxr_handle_base *hb) /* Might destroy instance, which log needs, so use secured variant */ HANDLE_LIFECYCLE_LOG_SCOPED_BEGIN(log) { - HANDLE_LIFECYCLE_LOG_SCOPED( - log, "[~: destroying %p] oxr_handle_destroy starting", - (void *)hb); + HANDLE_LIFECYCLE_LOG_SCOPED(log, "[~: destroying %p] oxr_handle_destroy starting", (void *)hb); XrResult result = oxr_handle_do_destroy(log, hb, 0); - HANDLE_LIFECYCLE_LOG_SCOPED( - log, "[~: destroying %p] oxr_handle_destroy finished", - (void *)hb); + HANDLE_LIFECYCLE_LOG_SCOPED(log, "[~: destroying %p] oxr_handle_destroy finished", (void *)hb); return result; } diff --git a/src/xrt/state_trackers/oxr/oxr_input.c b/src/xrt/state_trackers/oxr/oxr_input.c index cd3df8e53..6ae26bebb 100644 --- a/src/xrt/state_trackers/oxr/oxr_input.c +++ b/src/xrt/state_trackers/oxr/oxr_input.c @@ -34,17 +34,15 @@ */ static void -oxr_session_get_action_set_attachment( - struct oxr_session *sess, - XrActionSet actionSet, - struct oxr_action_set_attachment **act_set_attached, - struct oxr_action_set **act_set); +oxr_session_get_action_set_attachment(struct oxr_session *sess, + XrActionSet actionSet, + struct oxr_action_set_attachment **act_set_attached, + struct oxr_action_set **act_set); static void -oxr_session_get_action_attachment( - struct oxr_session *sess, - uint32_t act_key, - struct oxr_action_attachment **out_act_attached); +oxr_session_get_action_attachment(struct oxr_session *sess, + uint32_t act_key, + struct oxr_action_attachment **out_act_attached); static void oxr_action_cache_update(struct oxr_logger *log, @@ -111,8 +109,7 @@ static void oxr_action_attachment_teardown(struct oxr_action_attachment *act_attached) { struct oxr_session *sess = act_attached->sess; - u_hashmap_int_erase(sess->act_attachments_by_key, - act_attached->act_key); + u_hashmap_int_erase(sess->act_attachments_by_key, act_attached->act_key); #define CACHE_TEARDOWN(X) oxr_action_cache_teardown(&(act_attached->X)); OXR_FOR_EACH_SUBACTION_PATH(CACHE_TEARDOWN) @@ -136,8 +133,7 @@ oxr_action_attachment_init(struct oxr_logger *log, struct oxr_session *sess = act_set_attached->sess; act_attached->sess = sess; act_attached->act_set_attached = act_set_attached; - u_hashmap_int_insert(sess->act_attachments_by_key, act->act_key, - act_attached); + u_hashmap_int_insert(sess->act_attachments_by_key, act->act_key, act_attached); // Reference this action's refcounted data act_attached->act_ref = act->data; @@ -159,11 +155,10 @@ oxr_action_attachment_init(struct oxr_logger *log, * @public @memberof oxr_action_set_attachment */ static XrResult -oxr_action_set_attachment_init( - struct oxr_logger *log, - struct oxr_session *sess, - struct oxr_action_set *act_set, - struct oxr_action_set_attachment *act_set_attached) +oxr_action_set_attachment_init(struct oxr_logger *log, + struct oxr_session *sess, + struct oxr_action_set *act_set, + struct oxr_action_set_attachment *act_set_attached) { act_set_attached->sess = sess; @@ -171,8 +166,7 @@ oxr_action_set_attachment_init( act_set_attached->act_set_ref = act_set->data; oxr_refcounted_ref(&act_set_attached->act_set_ref->base); - u_hashmap_int_insert(sess->act_sets_attachments_by_key, - act_set->act_set_key, act_set_attached); + u_hashmap_int_insert(sess->act_sets_attachments_by_key, act_set->act_set_key, act_set_attached); // Copy this for efficiency. act_set_attached->act_set_key = act_set->act_set_key; @@ -181,20 +175,17 @@ oxr_action_set_attachment_init( } void -oxr_action_set_attachment_teardown( - struct oxr_action_set_attachment *act_set_attached) +oxr_action_set_attachment_teardown(struct oxr_action_set_attachment *act_set_attached) { for (size_t i = 0; i < act_set_attached->num_action_attachments; ++i) { - oxr_action_attachment_teardown( - &(act_set_attached->act_attachments[i])); + oxr_action_attachment_teardown(&(act_set_attached->act_attachments[i])); } free(act_set_attached->act_attachments); act_set_attached->act_attachments = NULL; act_set_attached->num_action_attachments = 0; struct oxr_session *sess = act_set_attached->sess; - u_hashmap_int_erase(sess->act_sets_attachments_by_key, - act_set_attached->act_set_key); + u_hashmap_int_erase(sess->act_sets_attachments_by_key, act_set_attached->act_set_key); // Unref this action set's refcounted data oxr_refcounted_unref(&act_set_attached->act_set_ref->base); @@ -209,8 +200,7 @@ oxr_action_set_attachment_teardown( static void oxr_action_set_ref_destroy_cb(struct oxr_refcounted *orc) { - struct oxr_action_set_ref *act_set_ref = - (struct oxr_action_set_ref *)orc; + struct oxr_action_set_ref *act_set_ref = (struct oxr_action_set_ref *)orc; u_hashset_destroy(&act_set_ref->actions.name_store); u_hashset_destroy(&act_set_ref->actions.loc_store); @@ -227,14 +217,12 @@ oxr_action_set_destroy_cb(struct oxr_logger *log, struct oxr_handle_base *hb) act_set->data = NULL; if (act_set->name_item != NULL) { - u_hashset_erase_item(act_set->inst->action_sets.name_store, - act_set->name_item); + u_hashset_erase_item(act_set->inst->action_sets.name_store, act_set->name_item); free(act_set->name_item); act_set->name_item = NULL; } if (act_set->loc_item != NULL) { - u_hashset_erase_item(act_set->inst->action_sets.loc_store, - act_set->loc_item); + u_hashset_erase_item(act_set->inst->action_sets.loc_store, act_set->loc_item); free(act_set->loc_item); act_set->loc_item = NULL; } @@ -255,11 +243,9 @@ oxr_action_set_create(struct oxr_logger *log, int h_ret; struct oxr_action_set *act_set = NULL; - OXR_ALLOCATE_HANDLE_OR_RETURN(log, act_set, OXR_XR_DEBUG_ACTIONSET, - oxr_action_set_destroy_cb, &inst->handle); + OXR_ALLOCATE_HANDLE_OR_RETURN(log, act_set, OXR_XR_DEBUG_ACTIONSET, oxr_action_set_destroy_cb, &inst->handle); - struct oxr_action_set_ref *act_set_ref = - U_TYPED_CALLOC(struct oxr_action_set_ref); + struct oxr_action_set_ref *act_set_ref = U_TYPED_CALLOC(struct oxr_action_set_ref); act_set_ref->base.destroy = oxr_action_set_ref_destroy_cb; oxr_refcounted_ref(&act_set_ref->base); act_set->data = act_set_ref; @@ -272,25 +258,19 @@ oxr_action_set_create(struct oxr_logger *log, h_ret = u_hashset_create(&act_set_ref->actions.name_store); if (h_ret != 0) { oxr_handle_destroy(log, &act_set->handle); - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to create name_store hashset"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to create name_store hashset"); } h_ret = u_hashset_create(&act_set_ref->actions.loc_store); if (h_ret != 0) { oxr_handle_destroy(log, &act_set->handle); - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to create loc_store hashset"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to create loc_store hashset"); } - strncpy(act_set_ref->name, createInfo->actionSetName, - sizeof(act_set_ref->name)); + strncpy(act_set_ref->name, createInfo->actionSetName, sizeof(act_set_ref->name)); - u_hashset_create_and_insert_str_c(inst->action_sets.name_store, - createInfo->actionSetName, - &act_set->name_item); - u_hashset_create_and_insert_str_c(inst->action_sets.loc_store, - createInfo->localizedActionSetName, + u_hashset_create_and_insert_str_c(inst->action_sets.name_store, createInfo->actionSetName, &act_set->name_item); + u_hashset_create_and_insert_str_c(inst->action_sets.loc_store, createInfo->localizedActionSetName, &act_set->loc_item); act_set_ref->priority = createInfo->priority; @@ -323,14 +303,12 @@ oxr_action_destroy_cb(struct oxr_logger *log, struct oxr_handle_base *hb) act->data = NULL; if (act->name_item != NULL) { - u_hashset_erase_item(act->act_set->data->actions.name_store, - act->name_item); + u_hashset_erase_item(act->act_set->data->actions.name_store, act->name_item); free(act->name_item); act->name_item = NULL; } if (act->loc_item != NULL) { - u_hashset_erase_item(act->act_set->data->actions.loc_store, - act->loc_item); + u_hashset_erase_item(act->act_set->data->actions.loc_store, act->loc_item); free(act->loc_item); act->loc_item = NULL; } @@ -352,15 +330,13 @@ oxr_action_create(struct oxr_logger *log, // Mod music for all! static uint32_t key_gen = 1; - if (!oxr_classify_sub_action_paths( - log, inst, createInfo->countSubactionPaths, - createInfo->subactionPaths, &sub_paths)) { + if (!oxr_classify_sub_action_paths(log, inst, createInfo->countSubactionPaths, createInfo->subactionPaths, + &sub_paths)) { return XR_ERROR_PATH_UNSUPPORTED; } struct oxr_action *act = NULL; - OXR_ALLOCATE_HANDLE_OR_RETURN(log, act, OXR_XR_DEBUG_ACTION, - oxr_action_destroy_cb, &act_set->handle); + OXR_ALLOCATE_HANDLE_OR_RETURN(log, act, OXR_XR_DEBUG_ACTION, oxr_action_destroy_cb, &act_set->handle); struct oxr_action_ref *act_ref = U_TYPED_CALLOC(struct oxr_action_ref); @@ -377,11 +353,8 @@ oxr_action_create(struct oxr_logger *log, strncpy(act_ref->name, createInfo->actionName, sizeof(act_ref->name)); - u_hashset_create_and_insert_str_c(act_set->data->actions.name_store, - createInfo->actionName, - &act->name_item); - u_hashset_create_and_insert_str_c(act_set->data->actions.loc_store, - createInfo->localizedActionName, + u_hashset_create_and_insert_str_c(act_set->data->actions.name_store, createInfo->actionName, &act->name_item); + u_hashset_create_and_insert_str_c(act_set->data->actions.loc_store, createInfo->localizedActionName, &act->loc_item); *out_act = act; @@ -418,10 +391,10 @@ oxr_classify_sub_action_paths(struct oxr_logger *log, for (uint32_t i = 0; i < num_subaction_paths; i++) { XrPath path = subaction_paths[i]; -#define IDENTIFY_PATH(X) \ - else if (path == inst->path_cache.X) \ - { \ - sub_paths->X = true; \ +#define IDENTIFY_PATH(X) \ + else if (path == inst->path_cache.X) \ + { \ + sub_paths->X = true; \ } @@ -432,8 +405,7 @@ oxr_classify_sub_action_paths(struct oxr_logger *log, { oxr_path_get_string(log, inst, path, &str, &length); - oxr_warn(log, " unrecognized sub action path '%s'", - str); + oxr_warn(log, " unrecognized sub action path '%s'", str); ret = false; } #undef IDENTIFY_PATH @@ -462,10 +434,10 @@ oxr_action_get_pose_input(struct oxr_logger *log, } // Priority of inputs. -#define GET_POSE_INPUT(X) \ - if (act_attached->X.current.active && sub_paths.X) { \ - *out_input = act_attached->X.inputs; \ - return XR_SUCCESS; \ +#define GET_POSE_INPUT(X) \ + if (act_attached->X.current.active && sub_paths.X) { \ + *out_input = act_attached->X.inputs; \ + return XR_SUCCESS; \ } OXR_FOR_EACH_VALID_SUBACTION_PATH(GET_POSE_INPUT) @@ -598,8 +570,7 @@ do_io_bindings(struct oxr_binding *binding_point, } static struct xrt_binding_profile * -get_matching_binding_profile(struct oxr_interaction_profile *profile, - struct xrt_device *xdev) +get_matching_binding_profile(struct oxr_interaction_profile *profile, struct xrt_device *xdev) { for (size_t i = 0; i < xdev->num_binding_profiles; i++) { if (xdev->binding_profiles[i].name == profile->xname) { @@ -617,8 +588,7 @@ get_matched_xrpath(struct oxr_binding *b, struct oxr_action *act) for (uint32_t i = 0; i < b->num_keys; i++) { if (b->keys[i] == act->act_key) { uint32_t preferred_path_index = XR_NULL_PATH; - preferred_path_index = - b->preferred_binding_path_index[i]; + preferred_path_index = b->preferred_binding_path_index[i]; preferred_path = b->paths[preferred_path_index]; break; } @@ -647,10 +617,10 @@ get_binding(struct oxr_logger *log, //! @todo This probably falls on its head if the application doesn't use //! sub action paths. switch (sub_path) { -#define PATH_CASE(NAME, NAMECAPS, PATH) \ - case OXR_SUB_ACTION_PATH_##NAMECAPS: \ - user_path_str = PATH; \ - xdev = GET_XDEV_BY_ROLE(sess->sys, NAME); \ +#define PATH_CASE(NAME, NAMECAPS, PATH) \ + case OXR_SUB_ACTION_PATH_##NAMECAPS: \ + user_path_str = PATH; \ + xdev = GET_XDEV_BY_ROLE(sess->sys, NAME); \ break; OXR_FOR_EACH_VALID_SUBACTION_PATH_DETAILED(PATH_CASE) @@ -676,8 +646,7 @@ get_binding(struct oxr_logger *log, return; } - oxr_path_get_string(log, sess->sys->inst, profile->path, &profile_str, - &length); + oxr_path_get_string(log, sess->sys->inst, profile->path, &profile_str, &length); oxr_slog(slog, "\t\tProfile: %s\n", profile_str); @@ -687,19 +656,16 @@ get_binding(struct oxr_logger *log, * profile. This allows the device to provide a mapping from one device * to itself. */ - struct xrt_binding_profile *xbp = - get_matching_binding_profile(profile, xdev); + struct xrt_binding_profile *xbp = get_matching_binding_profile(profile, xdev); // No point in proceeding here without either. if (profile->xname != xdev->name && xbp == NULL) { - oxr_slog(slog, - "\t\t\tProfile not for device and no xbp fallback!\n"); + oxr_slog(slog, "\t\t\tProfile not for device and no xbp fallback!\n"); return; } size_t num = 0; - oxr_binding_find_bindings_from_key(log, profile, act->act_key, - binding_points, &num); + oxr_binding_find_bindings_from_key(log, profile, act->act_key, binding_points, &num); if (num == 0) { oxr_slog(slog, "\t\t\tNo bindings!\n"); return; @@ -711,8 +677,7 @@ get_binding(struct oxr_logger *log, XrPath matched_path = get_matched_xrpath(binding_point, act); - oxr_path_get_string(log, sess->sys->inst, matched_path, &str, - &length); + oxr_path_get_string(log, sess->sys->inst, matched_path, &str, &length); oxr_slog(slog, "\t\t\tBinding: %s\n", str); if (binding_point->sub_path != sub_path) { @@ -770,8 +735,7 @@ oxr_action_attachment_bind(struct oxr_logger *log, struct oxr_session *sess = act_attached->sess; // Start logging into a single buffer. - oxr_slog(&slog, ": Binding %s/%s\n", act->act_set->data->name, - act_ref->name); + oxr_slog(&slog, ": Binding %s/%s\n", act->act_set->data->name, act_ref->name); if (act_ref->sub_paths.user || act_ref->sub_paths.any) { #if 0 @@ -780,11 +744,10 @@ oxr_action_attachment_bind(struct oxr_logger *log, #endif } -#define BIND_SUBACTION(NAME, NAME_CAPS, PATH) \ - if (act_ref->sub_paths.NAME || act_ref->sub_paths.any) { \ - oxr_action_bind_io(log, &slog, sess, act, &act_attached->NAME, \ - profiles->NAME, \ - OXR_SUB_ACTION_PATH_##NAME_CAPS); \ +#define BIND_SUBACTION(NAME, NAME_CAPS, PATH) \ + if (act_ref->sub_paths.NAME || act_ref->sub_paths.any) { \ + oxr_action_bind_io(log, &slog, sess, act, &act_attached->NAME, profiles->NAME, \ + OXR_SUB_ACTION_PATH_##NAME_CAPS); \ } OXR_FOR_EACH_VALID_SUBACTION_PATH_DETAILED(BIND_SUBACTION) #undef BIND_SUBACTION @@ -796,12 +759,10 @@ oxr_action_attachment_bind(struct oxr_logger *log, */ if (act_ref->action_type == XR_ACTION_TYPE_POSE_INPUT) { -#define POSE_ANY(NAME) \ - if ((act_ref->sub_paths.NAME || act_ref->sub_paths.any) && \ - act_attached->NAME.num_inputs > 0) { \ - act_attached->any_pose_sub_path.NAME = true; \ - oxr_slog(&slog, "\tFor: \n\t\tBinding any pose to " #NAME \ - ".\n"); \ +#define POSE_ANY(NAME) \ + if ((act_ref->sub_paths.NAME || act_ref->sub_paths.any) && act_attached->NAME.num_inputs > 0) { \ + act_attached->any_pose_sub_path.NAME = true; \ + oxr_slog(&slog, "\tFor: \n\t\tBinding any pose to " #NAME ".\n"); \ } else OXR_FOR_EACH_VALID_SUBACTION_PATH(POSE_ANY) #undef POSE_ANY @@ -826,9 +787,7 @@ oxr_action_attachment_bind(struct oxr_logger *log, } static void -oxr_action_cache_stop_output(struct oxr_logger *log, - struct oxr_session *sess, - struct oxr_action_cache *cache) +oxr_action_cache_stop_output(struct oxr_logger *log, struct oxr_session *sess, struct oxr_action_cache *cache) { // Set this as stopped. cache->stop_output_time = 0; @@ -844,8 +803,7 @@ oxr_action_cache_stop_output(struct oxr_logger *log, } static bool -oxr_input_is_input_for_cache(struct oxr_action_input *action_input, - struct oxr_action_cache *cache) +oxr_input_is_input_for_cache(struct oxr_action_input *action_input, struct oxr_action_cache *cache) { for (size_t i = 0; i < cache->num_inputs; i++) { if (action_input->bound_path == cache->inputs[i].bound_path) { @@ -856,17 +814,14 @@ oxr_input_is_input_for_cache(struct oxr_action_input *action_input, } static bool -oxr_input_is_bound_in_act_set( - struct oxr_action_input *action_input, - struct oxr_action_set_attachment *act_set_attached) +oxr_input_is_bound_in_act_set(struct oxr_action_input *action_input, struct oxr_action_set_attachment *act_set_attached) { for (size_t i = 0; i < act_set_attached->num_action_attachments; i++) { - struct oxr_action_attachment *act_attached = - &act_set_attached->act_attachments[i]; + struct oxr_action_attachment *act_attached = &act_set_attached->act_attachments[i]; -#define ACCUMULATE_PATHS(X) \ - if (oxr_input_is_input_for_cache(action_input, &act_attached->X)) { \ - return true; \ +#define ACCUMULATE_PATHS(X) \ + if (oxr_input_is_input_for_cache(action_input, &act_attached->X)) { \ + return true; \ } OXR_FOR_EACH_SUBACTION_PATH(ACCUMULATE_PATHS) #undef ACCUMULATE_PATHS @@ -882,8 +837,7 @@ oxr_input_supressed(struct oxr_session *sess, struct oxr_action_attachment *act_attached, struct oxr_action_input *action_input) { - struct oxr_action_set_ref *act_set_ref = - act_attached->act_set_attached->act_set_ref; + struct oxr_action_set_ref *act_set_ref = act_attached->act_set_attached->act_set_ref; uint32_t priority = act_set_ref->priority; // find sources that are bound to an action in a set with higher prio @@ -892,8 +846,7 @@ oxr_input_supressed(struct oxr_session *sess, struct oxr_action_set *other_act_set = NULL; struct oxr_action_set_attachment *other_act_set_attached = NULL; - oxr_session_get_action_set_attachment( - sess, set, &other_act_set_attached, &other_act_set); + oxr_session_get_action_set_attachment(sess, set, &other_act_set_attached, &other_act_set); if (other_act_set_attached == NULL) { continue; @@ -915,12 +868,9 @@ oxr_input_supressed(struct oxr_session *sess, * - high prio set syncs w/ ANY subpath or * - high prio set syncs w/ subpath matching this input subpath */ - bool relevant_subpath = - other_act_set_attached->requested_sub_paths.any; + bool relevant_subpath = other_act_set_attached->requested_sub_paths.any; -#define ACCUMULATE_PATHS(X) \ - relevant_subpath |= \ - (other_act_set_attached->requested_sub_paths.X && sub_path->X); +#define ACCUMULATE_PATHS(X) relevant_subpath |= (other_act_set_attached->requested_sub_paths.X && sub_path->X); OXR_FOR_EACH_SUBACTION_PATH(ACCUMULATE_PATHS) #undef ACCUMULATE_PATHS @@ -928,8 +878,7 @@ oxr_input_supressed(struct oxr_session *sess, continue; } - if (oxr_input_is_bound_in_act_set(action_input, - other_act_set_attached)) { + if (oxr_input_is_bound_in_act_set(action_input, other_act_set_attached)) { return true; } } @@ -966,8 +915,7 @@ oxr_input_combine_input(struct oxr_session *sess, // suppress input if it is also bound to action in set with // higher priority - if (oxr_input_supressed(sess, countActionSets, actionSets, - sub_path, act_attached, action_input)) { + if (oxr_input_supressed(sess, countActionSets, actionSets, sub_path, act_attached, action_input)) { continue; } @@ -983,9 +931,8 @@ oxr_input_combine_input(struct oxr_session *sess, }; struct oxr_input_value_tagged transformed = {0}; - if (!oxr_input_transform_process(action_input->transforms, - action_input->num_transforms, - &raw_input, &transformed)) { + if (!oxr_input_transform_process(action_input->transforms, action_input->num_transforms, &raw_input, + &transformed)) { // We couldn't transform, how strange. Reset all state. // At this level we don't know what action this is, etc. // so a warning message isn't very helpful. @@ -1003,30 +950,24 @@ oxr_input_combine_input(struct oxr_session *sess, * OR. The action only changes to true on the earliest * input that sets it to true, and to false on the * latest input that is false. */ - if (res.value.boolean && transformed.value.boolean && - input->timestamp < res_timestamp) { + if (res.value.boolean && transformed.value.boolean && input->timestamp < res_timestamp) { res_timestamp = input->timestamp; - } else if (!res.value.boolean && - !transformed.value.boolean && + } else if (!res.value.boolean && !transformed.value.boolean && input->timestamp > res_timestamp) { res_timestamp = input->timestamp; } break; case XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE: case XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE: - if (fabsf(transformed.value.vec1.x) > - fabsf(res.value.vec1.x)) { + if (fabsf(transformed.value.vec1.x) > fabsf(res.value.vec1.x)) { res.value.vec1.x = transformed.value.vec1.x; res_timestamp = input->timestamp; } break; case XRT_INPUT_TYPE_VEC2_MINUS_ONE_TO_ONE: { - float res_sq = res.value.vec2.x * res.value.vec2.x + - res.value.vec2.y * res.value.vec2.y; - float trans_sq = - transformed.value.vec2.x * - transformed.value.vec2.x + - transformed.value.vec2.y * transformed.value.vec2.y; + float res_sq = res.value.vec2.x * res.value.vec2.x + res.value.vec2.y * res.value.vec2.y; + float trans_sq = transformed.value.vec2.x * transformed.value.vec2.x + + transformed.value.vec2.y * transformed.value.vec2.y; if (trans_sq > res_sq) { res.value.vec2 = transformed.value.vec2; res_timestamp = input->timestamp; @@ -1089,11 +1030,9 @@ oxr_action_cache_update(struct oxr_logger *log, } } else if (cache->num_inputs > 0) { - if (!oxr_input_combine_input( - sess, countActionSets, actionSets, act_attached, - sub_path, cache, &combined, ×tamp, &is_active)) { - oxr_log(log, "Failed to get/combine input values '%s'", - act_attached->act_ref->name); + if (!oxr_input_combine_input(sess, countActionSets, actionSets, act_attached, sub_path, cache, + &combined, ×tamp, &is_active)) { + oxr_log(log, "Failed to get/combine input values '%s'", act_attached->act_ref->name); return; } @@ -1116,9 +1055,8 @@ oxr_action_cache_update(struct oxr_logger *log, break; } case XRT_INPUT_TYPE_VEC2_MINUS_ONE_TO_ONE: { - changed = - (combined.value.vec2.x != last.value.vec2.x) || - (combined.value.vec2.y != last.value.vec2.y); + changed = (combined.value.vec2.x != last.value.vec2.x) || + (combined.value.vec2.y != last.value.vec2.y); cache->current.value.vec2.x = combined.value.vec2.x; cache->current.value.vec2.y = combined.value.vec2.y; break; @@ -1135,8 +1073,7 @@ oxr_action_cache_update(struct oxr_logger *log, } #endif case XRT_INPUT_TYPE_BOOLEAN: { - changed = - (combined.value.boolean != last.value.boolean); + changed = (combined.value.boolean != last.value.boolean); cache->current.value.boolean = combined.value.boolean; break; } @@ -1164,32 +1101,32 @@ oxr_action_cache_update(struct oxr_logger *log, } } -#define BOOL_CHECK(NAME) \ - if (act_attached->NAME.current.active) { \ - active |= true; \ - value |= act_attached->NAME.current.value.boolean; \ - timestamp = act_attached->NAME.current.timestamp; \ - } -#define VEC1_CHECK(NAME) \ - if (act_attached->NAME.current.active) { \ - active |= true; \ - if (value < act_attached->NAME.current.value.vec1.x) { \ - value = act_attached->NAME.current.value.vec1.x; \ - timestamp = act_attached->NAME.current.timestamp; \ - } \ - } -#define VEC2_CHECK(NAME) \ - if (act_attached->NAME.current.active) { \ - active |= true; \ - float curr_x = act_attached->NAME.current.value.vec2.x; \ - float curr_y = act_attached->NAME.current.value.vec2.y; \ - float curr_d = curr_x * curr_x + curr_y * curr_y; \ - if (distance < curr_d) { \ - x = curr_x; \ - y = curr_y; \ - distance = curr_d; \ - timestamp = act_attached->NAME.current.timestamp; \ - } \ +#define BOOL_CHECK(NAME) \ + if (act_attached->NAME.current.active) { \ + active |= true; \ + value |= act_attached->NAME.current.value.boolean; \ + timestamp = act_attached->NAME.current.timestamp; \ + } +#define VEC1_CHECK(NAME) \ + if (act_attached->NAME.current.active) { \ + active |= true; \ + if (value < act_attached->NAME.current.value.vec1.x) { \ + value = act_attached->NAME.current.value.vec1.x; \ + timestamp = act_attached->NAME.current.timestamp; \ + } \ + } +#define VEC2_CHECK(NAME) \ + if (act_attached->NAME.current.active) { \ + active |= true; \ + float curr_x = act_attached->NAME.current.value.vec2.x; \ + float curr_y = act_attached->NAME.current.value.vec2.y; \ + float curr_d = curr_x * curr_x + curr_y * curr_y; \ + if (distance < curr_d) { \ + x = curr_x; \ + y = curr_y; \ + distance = curr_d; \ + timestamp = act_attached->NAME.current.timestamp; \ + } \ } /*! @@ -1213,12 +1150,11 @@ oxr_action_attachment_update(struct oxr_logger *log, //! @todo "/user" sub-action path. -#define UPDATE_SELECT(X) \ - struct oxr_sub_paths sub_paths_##X = {0}; \ - sub_paths_##X.X = true; \ - bool select_##X = sub_paths.X || sub_paths.any; \ - oxr_action_cache_update(log, sess, countActionSets, actionSets, \ - act_attached, &act_attached->X, time, \ +#define UPDATE_SELECT(X) \ + struct oxr_sub_paths sub_paths_##X = {0}; \ + sub_paths_##X.X = true; \ + bool select_##X = sub_paths.X || sub_paths.any; \ + oxr_action_cache_update(log, sess, countActionSets, actionSets, act_attached, &act_attached->X, time, \ &sub_paths_##X, select_##X); OXR_FOR_EACH_VALID_SUBACTION_PATH(UPDATE_SELECT) @@ -1305,14 +1241,12 @@ oxr_action_populate_input_transform(struct oxr_logger *log, assert(action_input->num_transforms == 0); const char *str; size_t length; - oxr_path_get_string(log, sess->sys->inst, action_input->bound_path, - &str, &length); + oxr_path_get_string(log, sess->sys->inst, action_input->bound_path, &str, &length); enum xrt_input_type t = XRT_GET_INPUT_TYPE(action_input->input->name); - return oxr_input_transform_create_chain( - log, slog, t, act->data->action_type, act->data->name, str, - &action_input->transforms, &action_input->num_transforms); + return oxr_input_transform_create_chain(log, slog, t, act->data->action_type, act->data->name, str, + &action_input->transforms, &action_input->num_transforms); } static void @@ -1329,21 +1263,18 @@ oxr_action_bind_io(struct oxr_logger *log, struct oxr_action_output outputs[OXR_MAX_BINDINGS_PER_ACTION] = {0}; uint32_t num_outputs = 0; - get_binding(log, slog, sess, act, profile, sub_path, inputs, - &num_inputs, outputs, &num_outputs); + get_binding(log, slog, sess, act, profile, sub_path, inputs, &num_inputs, outputs, &num_outputs); cache->current.active = false; if (num_inputs > 0) { uint32_t count = 0; cache->current.active = true; - cache->inputs = - U_TYPED_ARRAY_CALLOC(struct oxr_action_input, num_inputs); + cache->inputs = U_TYPED_ARRAY_CALLOC(struct oxr_action_input, num_inputs); for (uint32_t i = 0; i < num_inputs; i++) { // Only add the input if we can find a transform. - if (oxr_action_populate_input_transform( - log, slog, sess, act, &(inputs[i]))) { + if (oxr_action_populate_input_transform(log, slog, sess, act, &(inputs[i]))) { cache->inputs[count++] = inputs[i]; continue; } @@ -1362,8 +1293,7 @@ oxr_action_bind_io(struct oxr_logger *log, if (num_outputs > 0) { cache->current.active = true; - cache->outputs = - U_TYPED_ARRAY_CALLOC(struct oxr_action_output, num_outputs); + cache->outputs = U_TYPED_ARRAY_CALLOC(struct oxr_action_output, num_outputs); for (uint32_t i = 0; i < num_outputs; i++) { cache->outputs[i] = outputs[i]; } @@ -1385,15 +1315,13 @@ oxr_action_bind_io(struct oxr_logger *log, * @private @memberof oxr_session */ static void -oxr_session_get_action_set_attachment( - struct oxr_session *sess, - XrActionSet actionSet, - struct oxr_action_set_attachment **act_set_attached, - struct oxr_action_set **act_set) +oxr_session_get_action_set_attachment(struct oxr_session *sess, + XrActionSet actionSet, + struct oxr_action_set_attachment **act_set_attached, + struct oxr_action_set **act_set) { void *ptr = NULL; - *act_set = - XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_action_set *, actionSet); + *act_set = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_action_set *, actionSet); *act_set_attached = NULL; // In case no action_sets have been attached. @@ -1401,8 +1329,7 @@ oxr_session_get_action_set_attachment( return; } - int ret = u_hashmap_int_find(sess->act_sets_attachments_by_key, - (*act_set)->act_set_key, &ptr); + int ret = u_hashmap_int_find(sess->act_sets_attachments_by_key, (*act_set)->act_set_key, &ptr); if (ret == 0) { *act_set_attached = (struct oxr_action_set_attachment *)ptr; } @@ -1415,15 +1342,13 @@ oxr_session_get_action_set_attachment( * @private @memberof oxr_session */ static void -oxr_session_get_action_attachment( - struct oxr_session *sess, - uint32_t act_key, - struct oxr_action_attachment **out_act_attached) +oxr_session_get_action_attachment(struct oxr_session *sess, + uint32_t act_key, + struct oxr_action_attachment **out_act_attached) { void *ptr = NULL; - int ret = - u_hashmap_int_find(sess->act_attachments_by_key, act_key, &ptr); + int ret = u_hashmap_int_find(sess->act_attachments_by_key, act_key, &ptr); if (ret == 0) { *out_act_attached = (struct oxr_action_attachment *)ptr; } @@ -1448,60 +1373,49 @@ oxr_session_attach_action_sets(struct oxr_logger *log, { struct oxr_instance *inst = sess->sys->inst; struct oxr_profiles_per_subaction profiles = {0}; -#define FIND_PROFILE(X) \ - oxr_find_profile_for_device(log, inst, GET_XDEV_BY_ROLE(sess->sys, X), \ - &profiles.X); +#define FIND_PROFILE(X) oxr_find_profile_for_device(log, inst, GET_XDEV_BY_ROLE(sess->sys, X), &profiles.X); OXR_FOR_EACH_VALID_SUBACTION_PATH(FIND_PROFILE) #undef FIND_PROFILE // Allocate room for list. No need to check if anything has been // attached the API function does that. sess->num_action_set_attachments = bindInfo->countActionSets; - sess->act_set_attachments = U_TYPED_ARRAY_CALLOC( - struct oxr_action_set_attachment, sess->num_action_set_attachments); + sess->act_set_attachments = + U_TYPED_ARRAY_CALLOC(struct oxr_action_set_attachment, sess->num_action_set_attachments); // Set up the per-session data for these action sets. for (uint32_t i = 0; i < sess->num_action_set_attachments; i++) { - struct oxr_action_set *act_set = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_action_set *, bindInfo->actionSets[i]); + struct oxr_action_set *act_set = + XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_action_set *, bindInfo->actionSets[i]); struct oxr_action_set_ref *act_set_ref = act_set->data; act_set_ref->ever_attached = true; - struct oxr_action_set_attachment *act_set_attached = - &sess->act_set_attachments[i]; - oxr_action_set_attachment_init(log, sess, act_set, - act_set_attached); + struct oxr_action_set_attachment *act_set_attached = &sess->act_set_attachments[i]; + oxr_action_set_attachment_init(log, sess, act_set, act_set_attached); // Allocate the action attachments for this set. - act_set_attached->num_action_attachments = - oxr_handle_base_get_num_children(&act_set->handle); - act_set_attached->act_attachments = U_TYPED_ARRAY_CALLOC( - struct oxr_action_attachment, - act_set_attached->num_action_attachments); + act_set_attached->num_action_attachments = oxr_handle_base_get_num_children(&act_set->handle); + act_set_attached->act_attachments = + U_TYPED_ARRAY_CALLOC(struct oxr_action_attachment, act_set_attached->num_action_attachments); // Set up the per-session data for the actions. uint32_t child_index = 0; for (uint32_t k = 0; k < XRT_MAX_HANDLE_CHILDREN; k++) { - struct oxr_action *act = - (struct oxr_action *)act_set->handle.children[k]; + struct oxr_action *act = (struct oxr_action *)act_set->handle.children[k]; if (act == NULL) { continue; } - struct oxr_action_attachment *act_attached = - &act_set_attached->act_attachments[child_index]; - oxr_action_attachment_init(log, act_set_attached, - act_attached, act); - oxr_action_attachment_bind(log, act_attached, act, - &profiles); + struct oxr_action_attachment *act_attached = &act_set_attached->act_attachments[child_index]; + oxr_action_attachment_init(log, act_set_attached, act_attached, act); + oxr_action_attachment_bind(log, act_attached, act, &profiles); ++child_index; } } -#define POPULATE_PROFILE(X) \ - if (profiles.X != NULL) { \ - sess->X = profiles.X->path; \ - oxr_event_push_XrEventDataInteractionProfileChanged(log, \ - sess); \ +#define POPULATE_PROFILE(X) \ + if (profiles.X != NULL) { \ + sess->X = profiles.X->path; \ + oxr_event_push_XrEventDataInteractionProfileChanged(log, sess); \ } OXR_FOR_EACH_VALID_SUBACTION_PATH(POPULATE_PROFILE) #undef POPULATE_PROFILE @@ -1519,14 +1433,12 @@ oxr_action_sync_data(struct oxr_logger *log, // Check that all action sets has been attached. for (uint32_t i = 0; i < countActionSets; i++) { - oxr_session_get_action_set_attachment( - sess, actionSets[i].actionSet, &act_set_attached, &act_set); + oxr_session_get_action_set_attachment(sess, actionSets[i].actionSet, &act_set_attached, &act_set); if (act_set_attached == NULL) { - return oxr_error( - log, XR_ERROR_ACTIONSET_NOT_ATTACHED, - "(actionSets[%i].actionSet) action set '%s' has " - "not been attached to this session", - i, act_set != NULL ? act_set->data->name : "NULL"); + return oxr_error(log, XR_ERROR_ACTIONSET_NOT_ATTACHED, + "(actionSets[%i].actionSet) action set '%s' has " + "not been attached to this session", + i, act_set != NULL ? act_set->data->name : "NULL"); } } @@ -1548,13 +1460,10 @@ oxr_action_sync_data(struct oxr_logger *log, //! @todo can be listed more than once with different paths! for (uint32_t i = 0; i < countActionSets; i++) { struct oxr_sub_paths sub_paths; - oxr_session_get_action_set_attachment( - sess, actionSets[i].actionSet, &act_set_attached, &act_set); + oxr_session_get_action_set_attachment(sess, actionSets[i].actionSet, &act_set_attached, &act_set); assert(act_set_attached != NULL); - if (!oxr_classify_sub_action_paths(log, sess->sys->inst, 1, - &actionSets[i].subactionPath, - &sub_paths)) { + if (!oxr_classify_sub_action_paths(log, sess->sys->inst, 1, &actionSets[i].subactionPath, &sub_paths)) { return XR_ERROR_PATH_UNSUPPORTED; } @@ -1563,55 +1472,45 @@ oxr_action_sync_data(struct oxr_logger *log, /* never error when requesting any subpath */ bool any_action_with_subpath = sub_paths.any; -#define ACCUMULATE_REQUESTED(X) \ - act_set_attached->requested_sub_paths.X |= sub_paths.X; +#define ACCUMULATE_REQUESTED(X) act_set_attached->requested_sub_paths.X |= sub_paths.X; OXR_FOR_EACH_SUBACTION_PATH(ACCUMULATE_REQUESTED) #undef ACCUMULATE_REQUESTED /* check if we have at least one action for requested subpath */ - for (uint32_t k = 0; - k < act_set_attached->num_action_attachments; k++) { - struct oxr_action_attachment *act_attached = - &act_set_attached->act_attachments[k]; + for (uint32_t k = 0; k < act_set_attached->num_action_attachments; k++) { + struct oxr_action_attachment *act_attached = &act_set_attached->act_attachments[k]; if (act_attached == NULL) { continue; } -#define ACCUMULATE_REQUESTED(X) \ - any_action_with_subpath |= \ - sub_paths.X && act_attached->act_ref->sub_paths.X; +#define ACCUMULATE_REQUESTED(X) any_action_with_subpath |= sub_paths.X && act_attached->act_ref->sub_paths.X; OXR_FOR_EACH_SUBACTION_PATH(ACCUMULATE_REQUESTED) #undef ACCUMULATE_REQUESTED } if (!any_action_with_subpath) { - return oxr_error( - log, XR_ERROR_PATH_UNSUPPORTED, - "No action with specified subpath in actionset"); + return oxr_error(log, XR_ERROR_PATH_UNSUPPORTED, + "No action with specified subpath in actionset"); } } // Now, update all action attachments for (size_t i = 0; i < sess->num_action_set_attachments; ++i) { act_set_attached = &sess->act_set_attachments[i]; - struct oxr_sub_paths sub_paths = - act_set_attached->requested_sub_paths; + struct oxr_sub_paths sub_paths = act_set_attached->requested_sub_paths; - for (uint32_t k = 0; - k < act_set_attached->num_action_attachments; k++) { - struct oxr_action_attachment *act_attached = - &act_set_attached->act_attachments[k]; + for (uint32_t k = 0; k < act_set_attached->num_action_attachments; k++) { + struct oxr_action_attachment *act_attached = &act_set_attached->act_attachments[k]; if (act_attached == NULL) { continue; } - oxr_action_attachment_update(log, sess, countActionSets, - actionSets, act_attached, - now, sub_paths); + oxr_action_attachment_update(log, sess, countActionSets, actionSets, act_attached, now, + sub_paths); } } @@ -1619,9 +1518,7 @@ oxr_action_sync_data(struct oxr_logger *log, } static void -add_path_to_set(XrPath path_set[OXR_MAX_BINDINGS_PER_ACTION], - XrPath new_path, - uint32_t *inout_num_paths) +add_path_to_set(XrPath path_set[OXR_MAX_BINDINGS_PER_ACTION], XrPath new_path, uint32_t *inout_num_paths) { const uint32_t n = *inout_num_paths; @@ -1653,24 +1550,20 @@ oxr_action_enumerate_bound_sources(struct oxr_logger *log, oxr_session_get_action_attachment(sess, act_key, &act_attached); if (act_attached == NULL) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "act_key did not find any action"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "act_key did not find any action"); } -#define ACCUMULATE_PATHS(X) \ - if (act_attached->X.num_inputs > 0) { \ - for (uint32_t i = 0; i < act_attached->X.num_inputs; i++) { \ - add_path_to_set(temp, \ - act_attached->X.inputs[i].bound_path, \ - &num_paths); \ - } \ +#define ACCUMULATE_PATHS(X) \ + if (act_attached->X.num_inputs > 0) { \ + for (uint32_t i = 0; i < act_attached->X.num_inputs; i++) { \ + add_path_to_set(temp, act_attached->X.inputs[i].bound_path, &num_paths); \ + } \ } OXR_FOR_EACH_SUBACTION_PATH(ACCUMULATE_PATHS) #undef ACCUMULATE_PATHS - OXR_TWO_CALL_HELPER(log, sourceCapacityInput, sourceCountOutput, - sources, num_paths, temp, + OXR_TWO_CALL_HELPER(log, sourceCapacityInput, sourceCountOutput, sources, num_paths, temp, oxr_session_success_result(sess)); } @@ -1681,12 +1574,11 @@ oxr_action_enumerate_bound_sources(struct oxr_logger *log, * */ -#define OXR_ACTION_GET_XR_STATE_FROM_ACTION_STATE_COMMON(ACTION_STATE, DATA) \ - do { \ - DATA->lastChangeTime = time_state_monotonic_to_ts_ns( \ - inst->timekeeping, ACTION_STATE->timestamp); \ - DATA->changedSinceLastSync = ACTION_STATE->changed; \ - DATA->isActive = XR_TRUE; \ +#define OXR_ACTION_GET_XR_STATE_FROM_ACTION_STATE_COMMON(ACTION_STATE, DATA) \ + do { \ + DATA->lastChangeTime = time_state_monotonic_to_ts_ns(inst->timekeeping, ACTION_STATE->timestamp); \ + DATA->changedSinceLastSync = ACTION_STATE->changed; \ + DATA->isActive = XR_TRUE; \ } while (0) static void @@ -1701,9 +1593,7 @@ get_xr_state_from_action_state_bool(struct oxr_instance *inst, } static void -get_xr_state_from_action_state_vec1(struct oxr_instance *inst, - struct oxr_action_state *state, - XrActionStateFloat *data) +get_xr_state_from_action_state_vec1(struct oxr_instance *inst, struct oxr_action_state *state, XrActionStateFloat *data) { /* only get here if the action is active! */ assert(state->active); @@ -1728,42 +1618,36 @@ get_xr_state_from_action_state_vec2(struct oxr_instance *inst, * * @note Keep this synchronized with OXR_FOR_EACH_SUBACTION_PATH! */ -#define OXR_ACTION_GET_FILLER(TYPE) \ - if (sub_paths.any && act_attached->any_state.active) { \ - get_xr_state_from_action_state_##TYPE( \ - sess->sys->inst, &act_attached->any_state, data); \ - } \ - if (sub_paths.user && act_attached->user.current.active) { \ - get_xr_state_from_action_state_##TYPE( \ - sess->sys->inst, &act_attached->user.current, data); \ - } \ - if (sub_paths.head && act_attached->head.current.active) { \ - get_xr_state_from_action_state_##TYPE( \ - sess->sys->inst, &act_attached->head.current, data); \ - } \ - if (sub_paths.left && act_attached->left.current.active) { \ - get_xr_state_from_action_state_##TYPE( \ - sess->sys->inst, &act_attached->left.current, data); \ - } \ - if (sub_paths.right && act_attached->right.current.active) { \ - get_xr_state_from_action_state_##TYPE( \ - sess->sys->inst, &act_attached->right.current, data); \ - } \ - if (sub_paths.gamepad && act_attached->gamepad.current.active) { \ - get_xr_state_from_action_state_##TYPE( \ - sess->sys->inst, &act_attached->gamepad.current, data); \ +#define OXR_ACTION_GET_FILLER(TYPE) \ + if (sub_paths.any && act_attached->any_state.active) { \ + get_xr_state_from_action_state_##TYPE(sess->sys->inst, &act_attached->any_state, data); \ + } \ + if (sub_paths.user && act_attached->user.current.active) { \ + get_xr_state_from_action_state_##TYPE(sess->sys->inst, &act_attached->user.current, data); \ + } \ + if (sub_paths.head && act_attached->head.current.active) { \ + get_xr_state_from_action_state_##TYPE(sess->sys->inst, &act_attached->head.current, data); \ + } \ + if (sub_paths.left && act_attached->left.current.active) { \ + get_xr_state_from_action_state_##TYPE(sess->sys->inst, &act_attached->left.current, data); \ + } \ + if (sub_paths.right && act_attached->right.current.active) { \ + get_xr_state_from_action_state_##TYPE(sess->sys->inst, &act_attached->right.current, data); \ + } \ + if (sub_paths.gamepad && act_attached->gamepad.current.active) { \ + get_xr_state_from_action_state_##TYPE(sess->sys->inst, &act_attached->gamepad.current, data); \ } /*! * Clear the actual data members of the XrActionState* types, to have the * correct return value in case of the action being not active */ -#define OXR_ACTION_RESET_XR_ACTION_STATE(data) \ - do { \ - data->isActive = XR_FALSE; \ - data->changedSinceLastSync = XR_FALSE; \ - data->lastChangeTime = 0; \ - U_ZERO(&data->currentState); \ +#define OXR_ACTION_RESET_XR_ACTION_STATE(data) \ + do { \ + data->isActive = XR_FALSE; \ + data->changedSinceLastSync = XR_FALSE; \ + data->lastChangeTime = 0; \ + U_ZERO(&data->currentState); \ } while (0) XrResult @@ -1777,9 +1661,7 @@ oxr_action_get_boolean(struct oxr_logger *log, oxr_session_get_action_attachment(sess, act_key, &act_attached); if (act_attached == NULL) { - return oxr_error( - log, XR_ERROR_ACTIONSET_NOT_ATTACHED, - "Action has not been attached to this session"); + return oxr_error(log, XR_ERROR_ACTIONSET_NOT_ATTACHED, "Action has not been attached to this session"); } OXR_ACTION_RESET_XR_ACTION_STATE(data); @@ -1800,9 +1682,7 @@ oxr_action_get_vector1f(struct oxr_logger *log, oxr_session_get_action_attachment(sess, act_key, &act_attached); if (act_attached == NULL) { - return oxr_error( - log, XR_ERROR_ACTIONSET_NOT_ATTACHED, - "Action has not been attached to this session"); + return oxr_error(log, XR_ERROR_ACTIONSET_NOT_ATTACHED, "Action has not been attached to this session"); } OXR_ACTION_RESET_XR_ACTION_STATE(data); @@ -1823,9 +1703,7 @@ oxr_action_get_vector2f(struct oxr_logger *log, oxr_session_get_action_attachment(sess, act_key, &act_attached); if (act_attached == NULL) { - return oxr_error( - log, XR_ERROR_ACTIONSET_NOT_ATTACHED, - "Action has not been attached to this session"); + return oxr_error(log, XR_ERROR_ACTIONSET_NOT_ATTACHED, "Action has not been attached to this session"); } OXR_ACTION_RESET_XR_ACTION_STATE(data); @@ -1846,9 +1724,7 @@ oxr_action_get_pose(struct oxr_logger *log, oxr_session_get_action_attachment(sess, act_key, &act_attached); if (act_attached == NULL) { - return oxr_error( - log, XR_ERROR_ACTIONSET_NOT_ATTACHED, - "Action has not been attached to this session"); + return oxr_error(log, XR_ERROR_ACTIONSET_NOT_ATTACHED, "Action has not been attached to this session"); } // For poses on the any path we select a single path. @@ -1861,9 +1737,9 @@ oxr_action_get_pose(struct oxr_logger *log, /* * The sub path any is used as a catch all here to see if any */ -#define COMPUTE_ACTIVE(X) \ - if (sub_paths.X) { \ - data->isActive |= act_attached->X.current.active; \ +#define COMPUTE_ACTIVE(X) \ + if (sub_paths.X) { \ + data->isActive |= act_attached->X.current.active; \ } OXR_FOR_EACH_VALID_SUBACTION_PATH(COMPUTE_ACTIVE) @@ -1911,9 +1787,7 @@ oxr_action_apply_haptic_feedback(struct oxr_logger *log, oxr_session_get_action_attachment(sess, act_key, &act_attached); if (act_attached == NULL) { - return oxr_error( - log, XR_ERROR_ACTIONSET_NOT_ATTACHED, - "Action has not been attached to this session"); + return oxr_error(log, XR_ERROR_ACTIONSET_NOT_ATTACHED, "Action has not been attached to this session"); } const XrHapticVibration *data = (const XrHapticVibration *)hapticEvent; @@ -1928,11 +1802,9 @@ oxr_action_apply_haptic_feedback(struct oxr_logger *log, stop_ns = now_ns + data->duration; } -#define SET_OUT_VIBRATION(X) \ - if (act_attached->X.current.active && \ - (sub_paths.X || sub_paths.any)) { \ - set_action_output_vibration(sess, &act_attached->X, stop_ns, \ - data); \ +#define SET_OUT_VIBRATION(X) \ + if (act_attached->X.current.active && (sub_paths.X || sub_paths.any)) { \ + set_action_output_vibration(sess, &act_attached->X, stop_ns, data); \ } OXR_FOR_EACH_SUBACTION_PATH(SET_OUT_VIBRATION) @@ -1950,15 +1822,12 @@ oxr_action_stop_haptic_feedback(struct oxr_logger *log, oxr_session_get_action_attachment(sess, act_key, &act_attached); if (act_attached == NULL) { - return oxr_error( - log, XR_ERROR_ACTIONSET_NOT_ATTACHED, - "Action has not been attached to this session"); + return oxr_error(log, XR_ERROR_ACTIONSET_NOT_ATTACHED, "Action has not been attached to this session"); } -#define STOP_VIBRATION(X) \ - if (act_attached->X.current.active && \ - (sub_paths.X || sub_paths.any)) { \ - oxr_action_cache_stop_output(log, sess, &act_attached->X); \ +#define STOP_VIBRATION(X) \ + if (act_attached->X.current.active && (sub_paths.X || sub_paths.any)) { \ + oxr_action_cache_stop_output(log, sess, &act_attached->X); \ } OXR_FOR_EACH_SUBACTION_PATH(STOP_VIBRATION) diff --git a/src/xrt/state_trackers/oxr/oxr_input_transform.c b/src/xrt/state_trackers/oxr/oxr_input_transform.c index 09c63a25d..79900a447 100644 --- a/src/xrt/state_trackers/oxr/oxr_input_transform.c +++ b/src/xrt/state_trackers/oxr/oxr_input_transform.c @@ -67,8 +67,7 @@ oxr_input_transform_destroy(struct oxr_input_transform **transform_ptr) } bool -oxr_input_transform_init_root(struct oxr_input_transform *transform, - enum xrt_input_type input_type) +oxr_input_transform_init_root(struct oxr_input_transform *transform, enum xrt_input_type input_type) { assert(transform != NULL); U_ZERO(transform); @@ -79,8 +78,7 @@ oxr_input_transform_init_root(struct oxr_input_transform *transform, } bool -oxr_input_transform_init_vec2_get_x(struct oxr_input_transform *transform, - const struct oxr_input_transform *parent) +oxr_input_transform_init_vec2_get_x(struct oxr_input_transform *transform, const struct oxr_input_transform *parent) { assert(transform != NULL); assert(parent != NULL); @@ -94,8 +92,7 @@ oxr_input_transform_init_vec2_get_x(struct oxr_input_transform *transform, } bool -oxr_input_transform_init_vec2_get_y(struct oxr_input_transform *transform, - const struct oxr_input_transform *parent) +oxr_input_transform_init_vec2_get_y(struct oxr_input_transform *transform, const struct oxr_input_transform *parent) { assert(transform != NULL); assert(parent != NULL); @@ -166,15 +163,10 @@ oxr_input_transform_process(const struct oxr_input_transform *transform, case INPUT_TRANSFORM_IDENTITY: // do nothing break; - case INPUT_TRANSFORM_VEC2_GET_X: - data.value.vec1.x = data.value.vec2.x; - break; - case INPUT_TRANSFORM_VEC2_GET_Y: - data.value.vec1.x = data.value.vec2.y; - break; + case INPUT_TRANSFORM_VEC2_GET_X: data.value.vec1.x = data.value.vec2.x; break; + case INPUT_TRANSFORM_VEC2_GET_Y: data.value.vec1.x = data.value.vec2.y; break; case INPUT_TRANSFORM_THRESHOLD: { - bool temp = - data.value.vec1.x > xform->data.threshold.threshold; + bool temp = data.value.vec1.x > xform->data.threshold.threshold; if (xform->data.threshold.invert) { temp = !temp; } @@ -183,9 +175,7 @@ oxr_input_transform_process(const struct oxr_input_transform *transform, } case INPUT_TRANSFORM_BOOL_TO_VEC1: { data.value.vec1.x = - data.value.boolean - ? xform->data.bool_to_vec1.true_val - : xform->data.bool_to_vec1.false_val; + data.value.boolean ? xform->data.bool_to_vec1.true_val : xform->data.bool_to_vec1.false_val; break; } case INPUT_TRANSFORM_INVALID: @@ -204,15 +194,13 @@ ends_with(const char *str, const char *suffix) int len = strlen(str); int suffix_len = strlen(suffix); - return (len >= suffix_len) && - (0 == strcmp(str + (len - suffix_len), suffix)); + return (len >= suffix_len) && (0 == strcmp(str + (len - suffix_len), suffix)); } static inline bool input_is_float(enum xrt_input_type input_type) { - return (input_type == XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE) || - (input_type == XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE); + return (input_type == XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE) || (input_type == XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE); } static inline uint8_t @@ -231,11 +219,9 @@ static inline bool oxr_type_matches_xrt(enum xrt_input_type input_type, XrActionType result_type) { switch (result_type) { - case XR_ACTION_TYPE_BOOLEAN_INPUT: - return input_type == XRT_INPUT_TYPE_BOOLEAN; + case XR_ACTION_TYPE_BOOLEAN_INPUT: return input_type == XRT_INPUT_TYPE_BOOLEAN; case XR_ACTION_TYPE_FLOAT_INPUT: return input_is_float(input_type); - case XR_ACTION_TYPE_VECTOR2F_INPUT: - return input_type == XRT_INPUT_TYPE_VEC2_MINUS_ONE_TO_ONE; + case XR_ACTION_TYPE_VECTOR2F_INPUT: return input_type == XRT_INPUT_TYPE_VEC2_MINUS_ONE_TO_ONE; default: return false; } } @@ -249,53 +235,37 @@ extend_transform_array(struct oxr_logger *log, const char *bound_path_string) { enum xrt_input_type input_type = parent->result_type; - if (input_dim(input_type) == 2 && - result_type != XR_ACTION_TYPE_VECTOR2F_INPUT) { + if (input_dim(input_type) == 2 && result_type != XR_ACTION_TYPE_VECTOR2F_INPUT) { // reduce dimension if (ends_with(bound_path_string, "/x")) { - oxr_slog(slog, - "\t\t\tAdding transform: get x of Vec2\n"); - return oxr_input_transform_init_vec2_get_x(transform, - parent); + oxr_slog(slog, "\t\t\tAdding transform: get x of Vec2\n"); + return oxr_input_transform_init_vec2_get_x(transform, parent); } if (ends_with(bound_path_string, "/y")) { - oxr_slog(slog, - "\t\t\tAdding transform: get y of Vec2\n"); - return oxr_input_transform_init_vec2_get_y(transform, - parent); + oxr_slog(slog, "\t\t\tAdding transform: get y of Vec2\n"); + return oxr_input_transform_init_vec2_get_y(transform, parent); } - oxr_slog( - slog, - "\t\t\tNo rule to get float from vec2f for binding %s\n", - bound_path_string); + oxr_slog(slog, "\t\t\tNo rule to get float from vec2f for binding %s\n", bound_path_string); return false; } - if (input_type == XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE && - result_type == XR_ACTION_TYPE_BOOLEAN_INPUT) { + if (input_type == XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE && result_type == XR_ACTION_TYPE_BOOLEAN_INPUT) { // 0.2 is for a little deadband around the center. - oxr_slog(slog, - "\t\t\tAdding transform: threshold [-1, 1] float\n"); - return oxr_input_transform_init_threshold(transform, parent, - 0.2f, false); + oxr_slog(slog, "\t\t\tAdding transform: threshold [-1, 1] float\n"); + return oxr_input_transform_init_threshold(transform, parent, 0.2f, false); } - if (input_type == XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE && - result_type == XR_ACTION_TYPE_BOOLEAN_INPUT) { + if (input_type == XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE && result_type == XR_ACTION_TYPE_BOOLEAN_INPUT) { // Need it pressed nearly all the way - oxr_slog(slog, - "\t\t\tAdding transform: threshold [0, 1] float\n"); - return oxr_input_transform_init_threshold(transform, parent, - 0.7f, false); + oxr_slog(slog, "\t\t\tAdding transform: threshold [0, 1] float\n"); + return oxr_input_transform_init_threshold(transform, parent, 0.7f, false); } - if (input_type == XRT_INPUT_TYPE_BOOLEAN && - result_type == XR_ACTION_TYPE_FLOAT_INPUT) { + if (input_type == XRT_INPUT_TYPE_BOOLEAN && result_type == XR_ACTION_TYPE_FLOAT_INPUT) { // this conversion is in the spec oxr_slog(slog, "\t\t\tAdding transform: bool to float\n"); - return oxr_input_transform_init_bool_to_vec1( - transform, parent, XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, 1.f, - 0.f); + return oxr_input_transform_init_bool_to_vec1(transform, parent, XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, 1.f, + 0.f); } oxr_slog(slog, "\t\t\tCould not transform!\n"); @@ -304,11 +274,9 @@ extend_transform_array(struct oxr_logger *log, } struct oxr_input_transform * -oxr_input_transform_clone_chain(struct oxr_input_transform *transforms, - size_t num_transforms) +oxr_input_transform_clone_chain(struct oxr_input_transform *transforms, size_t num_transforms) { - struct oxr_input_transform *ret = - U_TYPED_ARRAY_CALLOC(struct oxr_input_transform, num_transforms); + struct oxr_input_transform *ret = U_TYPED_ARRAY_CALLOC(struct oxr_input_transform, num_transforms); memcpy(ret, transforms, sizeof(*ret) * num_transforms); return ret; } @@ -325,8 +293,7 @@ oxr_input_transform_create_chain(struct oxr_logger *log, { struct oxr_input_transform chain[OXR_MAX_INPUT_TRANSFORMS] = {0}; - oxr_slog(slog, "\t\tAdding transform from '%s' to '%s'\n", - xr_action_type_to_str(result_type), + oxr_slog(slog, "\t\tAdding transform from '%s' to '%s'\n", xr_action_type_to_str(result_type), xrt_input_type_to_str(input_type)); struct oxr_input_transform *current_xform = &(chain[0]); @@ -336,10 +303,8 @@ oxr_input_transform_create_chain(struct oxr_logger *log, return false; } - bool identity = - (result_type == XR_ACTION_TYPE_POSE_INPUT && - input_type == XRT_INPUT_TYPE_POSE) || - oxr_type_matches_xrt(current_xform->result_type, result_type); + bool identity = (result_type == XR_ACTION_TYPE_POSE_INPUT && input_type == XRT_INPUT_TYPE_POSE) || + oxr_type_matches_xrt(current_xform->result_type, result_type); if (identity) { // No transform needed, just return identity to keep this alive. @@ -363,10 +328,8 @@ oxr_input_transform_create_chain(struct oxr_logger *log, return false; } - struct oxr_input_transform *new_xform = - &(chain[num_transforms]); - if (!extend_transform_array(log, slog, new_xform, current_xform, - result_type, bound_path_string)) { + struct oxr_input_transform *new_xform = &(chain[num_transforms]); + if (!extend_transform_array(log, slog, new_xform, current_xform, result_type, bound_path_string)) { // Error has already been logged. *out_num_transforms = 0; @@ -379,8 +342,7 @@ oxr_input_transform_create_chain(struct oxr_logger *log, } *out_num_transforms = num_transforms; - *out_transforms = - oxr_input_transform_clone_chain(chain, num_transforms); + *out_transforms = oxr_input_transform_clone_chain(chain, num_transforms); return true; } diff --git a/src/xrt/state_trackers/oxr/oxr_input_transform.h b/src/xrt/state_trackers/oxr/oxr_input_transform.h index fcdc961b9..b2c64e550 100644 --- a/src/xrt/state_trackers/oxr/oxr_input_transform.h +++ b/src/xrt/state_trackers/oxr/oxr_input_transform.h @@ -191,8 +191,7 @@ oxr_input_transform_process(const struct oxr_input_transform *transforms, * @public @memberof oxr_input_transform */ bool -oxr_input_transform_init_root(struct oxr_input_transform *transform, - const enum xrt_input_type input_type); +oxr_input_transform_init_root(struct oxr_input_transform *transform, const enum xrt_input_type input_type); /*! * Allocate a transform to get the X component of a Vec2. @@ -208,8 +207,7 @@ oxr_input_transform_init_root(struct oxr_input_transform *transform, * @public @memberof oxr_input_transform */ bool -oxr_input_transform_init_vec2_get_x(struct oxr_input_transform *transform, - const struct oxr_input_transform *parent); +oxr_input_transform_init_vec2_get_x(struct oxr_input_transform *transform, const struct oxr_input_transform *parent); /*! * Allocate a transform to get the Y component of a Vec2. @@ -225,8 +223,7 @@ oxr_input_transform_init_vec2_get_x(struct oxr_input_transform *transform, * @public @memberof oxr_input_transform */ bool -oxr_input_transform_init_vec2_get_y(struct oxr_input_transform *transform, - const struct oxr_input_transform *parent); +oxr_input_transform_init_vec2_get_y(struct oxr_input_transform *transform, const struct oxr_input_transform *parent); /*! * Allocate a transform to threshold a float to a bool. diff --git a/src/xrt/state_trackers/oxr/oxr_instance.c b/src/xrt/state_trackers/oxr/oxr_instance.c index 69560a45e..0a29f237e 100644 --- a/src/xrt/state_trackers/oxr/oxr_instance.c +++ b/src/xrt/state_trackers/oxr/oxr_instance.c @@ -48,15 +48,9 @@ DEBUG_GET_ONCE_FLOAT_OPTION(lfov_right, "OXR_OVERRIDE_LFOV_RIGHT", 0.0f) DEBUG_GET_ONCE_FLOAT_OPTION(lfov_up, "OXR_OVERRIDE_LFOV_UP", 0.0f) DEBUG_GET_ONCE_FLOAT_OPTION(lfov_down, "OXR_OVERRIDE_LFOV_DOWN", 0.0f) -DEBUG_GET_ONCE_FLOAT_OPTION(tracking_origin_offset_x, - "OXR_TRACKING_ORIGIN_OFFSET_X", - 0.0f) -DEBUG_GET_ONCE_FLOAT_OPTION(tracking_origin_offset_y, - "OXR_TRACKING_ORIGIN_OFFSET_Y", - 0.0f) -DEBUG_GET_ONCE_FLOAT_OPTION(tracking_origin_offset_z, - "OXR_TRACKING_ORIGIN_OFFSET_Z", - 0.0f) +DEBUG_GET_ONCE_FLOAT_OPTION(tracking_origin_offset_x, "OXR_TRACKING_ORIGIN_OFFSET_X", 0.0f) +DEBUG_GET_ONCE_FLOAT_OPTION(tracking_origin_offset_y, "OXR_TRACKING_ORIGIN_OFFSET_Y", 0.0f) +DEBUG_GET_ONCE_FLOAT_OPTION(tracking_origin_offset_z, "OXR_TRACKING_ORIGIN_OFFSET_Z", 0.0f) /* ---- HACK ---- */ extern int @@ -114,10 +108,7 @@ oxr_instance_destroy(struct oxr_logger *log, struct oxr_handle_base *hb) } static void -cache_path(struct oxr_logger *log, - struct oxr_instance *inst, - const char *str, - XrPath *out_path) +cache_path(struct oxr_logger *log, struct oxr_instance *inst, const char *str, XrPath *out_path) { oxr_path_get_or_create(log, inst, str, strlen(str), out_path); } @@ -131,9 +122,7 @@ min_size_t(size_t a, size_t b) } XrResult -oxr_instance_create(struct oxr_logger *log, - const XrInstanceCreateInfo *createInfo, - struct oxr_instance **out_instance) +oxr_instance_create(struct oxr_logger *log, const XrInstanceCreateInfo *createInfo, struct oxr_instance **out_instance) { struct oxr_instance *inst = NULL; struct xrt_device *xdevs[NUM_XDEVS] = {0}; @@ -141,8 +130,7 @@ oxr_instance_create(struct oxr_logger *log, xrt_result_t xret; XrResult ret; - OXR_ALLOCATE_HANDLE_OR_RETURN(log, inst, OXR_XR_DEBUG_INSTANCE, - oxr_instance_destroy, NULL); + OXR_ALLOCATE_HANDLE_OR_RETURN(log, inst, OXR_XR_DEBUG_INSTANCE, oxr_instance_destroy, NULL); inst->lifecycle_verbose = debug_get_bool_option_lifecycle_verbose(); inst->debug_spaces = debug_get_bool_option_debug_spaces(); @@ -151,8 +139,7 @@ oxr_instance_create(struct oxr_logger *log, m_ret = os_mutex_init(&inst->event.mutex); if (m_ret < 0) { - ret = oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to init mutex"); + ret = oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to init mutex"); return ret; } @@ -168,23 +155,20 @@ oxr_instance_create(struct oxr_logger *log, h_ret = u_hashset_create(&inst->action_sets.name_store); if (h_ret != 0) { oxr_instance_destroy(log, &inst->handle); - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to create name_store hashset"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to create name_store hashset"); } h_ret = u_hashset_create(&inst->action_sets.loc_store); if (h_ret != 0) { oxr_instance_destroy(log, &inst->handle); - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to create loc_store hashset"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to create loc_store hashset"); } // Cache certain often looked up paths. -#define CACHE_SUBACTION_PATHS(NAME, NAME_CAPS, PATH) \ - cache_path(log, inst, PATH, &inst->path_cache.NAME); +#define CACHE_SUBACTION_PATHS(NAME, NAME_CAPS, PATH) cache_path(log, inst, PATH, &inst->path_cache.NAME); OXR_FOR_EACH_SUBACTION_PATH_DETAILED(CACHE_SUBACTION_PATHS) #undef CACHE_SUBACTION_PATHS @@ -206,24 +190,19 @@ oxr_instance_create(struct oxr_logger *log, // fields? struct xrt_instance_info i_info = {0}; - snprintf(i_info.application_name, - sizeof(inst->xinst->instance_info.application_name), "%s", + snprintf(i_info.application_name, sizeof(inst->xinst->instance_info.application_name), "%s", createInfo->applicationInfo.applicationName); #ifdef XRT_OS_ANDROID - XrInstanceCreateInfoAndroidKHR const *create_info_android = - OXR_GET_INPUT_FROM_CHAIN(createInfo, - XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR, - XrInstanceCreateInfoAndroidKHR); - android_globals_store_vm_and_activity( - (struct _JavaVM *)create_info_android->applicationVM, - create_info_android->applicationActivity); + XrInstanceCreateInfoAndroidKHR const *create_info_android = OXR_GET_INPUT_FROM_CHAIN( + createInfo, XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR, XrInstanceCreateInfoAndroidKHR); + android_globals_store_vm_and_activity((struct _JavaVM *)create_info_android->applicationVM, + create_info_android->applicationActivity); #endif xinst_ret = xrt_instance_create(&i_info, &inst->xinst); if (xinst_ret != 0) { - ret = oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to create prober"); + ret = oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to create prober"); oxr_instance_destroy(log, &inst->handle); return ret; } @@ -231,8 +210,7 @@ oxr_instance_create(struct oxr_logger *log, xinst_ret = xrt_instance_select(inst->xinst, xdevs, NUM_XDEVS); if (xinst_ret != 0) { - ret = oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to select device(s)"); + ret = oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to select device(s)"); oxr_instance_destroy(log, &inst->handle); return ret; } @@ -252,26 +230,22 @@ oxr_instance_create(struct oxr_logger *log, oxr_xdev_destroy(&xdevs[i]); } - u_device_assign_xdev_roles(xdevs, NUM_XDEVS, &sys->role.head, - &sys->role.left, &sys->role.right); + u_device_assign_xdev_roles(xdevs, NUM_XDEVS, &sys->role.head, &sys->role.left, &sys->role.right); // Did we find any HMD // @todo Headless with only controllers? struct xrt_device *dev = GET_XDEV_BY_ROLE(sys, head); if (dev == NULL) { - ret = oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to find any HMD device"); + ret = oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to find any HMD device"); oxr_instance_destroy(log, &inst->handle); return ret; } - struct xrt_vec3 global_tracking_origin_offset = { - debug_get_float_option_tracking_origin_offset_x(), - debug_get_float_option_tracking_origin_offset_y(), - debug_get_float_option_tracking_origin_offset_z()}; + struct xrt_vec3 global_tracking_origin_offset = {debug_get_float_option_tracking_origin_offset_x(), + debug_get_float_option_tracking_origin_offset_y(), + debug_get_float_option_tracking_origin_offset_z()}; - u_device_setup_tracking_origins(dev, GET_XDEV_BY_ROLE(sys, left), - GET_XDEV_BY_ROLE(sys, right), + u_device_setup_tracking_origins(dev, GET_XDEV_BY_ROLE(sys, left), GET_XDEV_BY_ROLE(sys, right), &global_tracking_origin_offset); const float left_override = debug_get_float_option_lfov_left(); @@ -279,8 +253,8 @@ oxr_instance_create(struct oxr_logger *log, U_LOG_I( "Overriding left eye angle_left with %f radians (%i°), " "and right eye angle_right with %f radians (%i°)", - left_override, radtodeg_for_display(left_override), - -left_override, radtodeg_for_display(-left_override)); + left_override, radtodeg_for_display(left_override), -left_override, + radtodeg_for_display(-left_override)); dev->hmd->views[0].fov.angle_left = left_override; dev->hmd->views[1].fov.angle_right = -left_override; } @@ -290,24 +264,24 @@ oxr_instance_create(struct oxr_logger *log, U_LOG_I( "Overriding left eye angle_right with %f radians (%i°), " "and right eye angle_left with %f radians (%i°)", - right_override, radtodeg_for_display(right_override), - -right_override, radtodeg_for_display(-right_override)); + right_override, radtodeg_for_display(right_override), -right_override, + radtodeg_for_display(-right_override)); dev->hmd->views[0].fov.angle_right = right_override; dev->hmd->views[1].fov.angle_left = -right_override; } const float up_override = debug_get_float_option_lfov_up(); if (up_override != 0.0f) { - U_LOG_I("Overriding both eyes angle_up with %f radians (%i°)", - up_override, radtodeg_for_display(up_override)); + U_LOG_I("Overriding both eyes angle_up with %f radians (%i°)", up_override, + radtodeg_for_display(up_override)); dev->hmd->views[0].fov.angle_up = up_override; dev->hmd->views[1].fov.angle_up = up_override; } const float down_override = debug_get_float_option_lfov_down(); if (down_override != 0.0f) { - U_LOG_I("Overriding both eyes angle_down with %f radians (%i°)", - down_override, radtodeg_for_display(down_override)); + U_LOG_I("Overriding both eyes angle_down with %f radians (%i°)", down_override, + radtodeg_for_display(down_override)); dev->hmd->views[0].fov.angle_down = down_override; dev->hmd->views[1].fov.angle_down = down_override; } @@ -316,11 +290,10 @@ oxr_instance_create(struct oxr_logger *log, U_ZERO(&inst->extensions); for (uint32_t i = 0; i < createInfo->enabledExtensionCount; ++i) { -#define ENABLE_EXT(mixed_case, all_caps) \ - if (strcmp(createInfo->enabledExtensionNames[i], \ - XR_##all_caps##_EXTENSION_NAME) == 0) { \ - inst->extensions.mixed_case = true; \ - continue; \ +#define ENABLE_EXT(mixed_case, all_caps) \ + if (strcmp(createInfo->enabledExtensionNames[i], XR_##all_caps##_EXTENSION_NAME) == 0) { \ + inst->extensions.mixed_case = true; \ + continue; \ } OXR_EXTENSION_SUPPORT_GENERATE(ENABLE_EXT) // assert(false && @@ -330,31 +303,28 @@ oxr_instance_create(struct oxr_logger *log, // Create the compositor, if we are not headless. if (!inst->extensions.MND_headless) { - xret = xrt_instance_create_native_compositor(inst->xinst, dev, - &sys->xcn); + xret = xrt_instance_create_native_compositor(inst->xinst, dev, &sys->xcn); if (ret < 0 || sys->xcn == NULL) { - ret = oxr_error( - log, XR_ERROR_INITIALIZATION_FAILED, - "Failed to create a native compositor '%i'", xret); + ret = oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, + "Failed to create a native compositor '%i'", xret); oxr_instance_destroy(log, &inst->handle); return ret; } // Make sure that the compositor we were given can do all the // things the build config promised. -#define CHECK_LAYER_TYPE(NAME, MEMBER_NAME) \ - do { \ - if (sys->xcn->base.MEMBER_NAME == NULL) { \ - ret = oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, \ - "Logic error: build config " \ - "advertised support for " NAME \ - " but compositor does not " \ - "implement " #MEMBER_NAME); \ - oxr_instance_destroy(log, &inst->handle); \ - assert(false && \ - "Build configured with unsupported layers"); \ - return ret; \ - } \ +#define CHECK_LAYER_TYPE(NAME, MEMBER_NAME) \ + do { \ + if (sys->xcn->base.MEMBER_NAME == NULL) { \ + ret = oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, \ + "Logic error: build config " \ + "advertised support for " NAME \ + " but compositor does not " \ + "implement " #MEMBER_NAME); \ + oxr_instance_destroy(log, &inst->handle); \ + assert(false && "Build configured with unsupported layers"); \ + return ret; \ + } \ } while (0) // Keep this list in sync with types in xrt_config_build.h @@ -365,8 +335,7 @@ oxr_instance_create(struct oxr_logger *log, CHECK_LAYER_TYPE("cylinder layers", layer_cylinder); #endif #ifdef XRT_FEATURE_OPENXR_LAYER_DEPTH - CHECK_LAYER_TYPE("projection layers with depth images", - layer_stereo_projection_depth); + CHECK_LAYER_TYPE("projection layers with depth images", layer_stereo_projection_depth); #endif #ifdef XRT_FEATURE_OPENXR_LAYER_EQUIRECT1 CHECK_LAYER_TYPE("equirect1 layers", layer_equirect1); @@ -401,13 +370,11 @@ oxr_instance_create(struct oxr_logger *log, XrResult -oxr_instance_get_properties(struct oxr_logger *log, - struct oxr_instance *inst, - XrInstanceProperties *instanceProperties) +oxr_instance_get_properties(struct oxr_logger *log, struct oxr_instance *inst, XrInstanceProperties *instanceProperties) { instanceProperties->runtimeVersion = XR_MAKE_VERSION(0, 1, 42); - snprintf(instanceProperties->runtimeName, XR_MAX_RUNTIME_NAME_SIZE - 1, - "Monado(XRT) by Collabora et al '%s'", u_git_tag); + snprintf(instanceProperties->runtimeName, XR_MAX_RUNTIME_NAME_SIZE - 1, "Monado(XRT) by Collabora et al '%s'", + u_git_tag); return XR_SUCCESS; } diff --git a/src/xrt/state_trackers/oxr/oxr_logger.c b/src/xrt/state_trackers/oxr/oxr_logger.c index 5cb32095c..a6514a6ea 100644 --- a/src/xrt/state_trackers/oxr/oxr_logger.c +++ b/src/xrt/state_trackers/oxr/oxr_logger.c @@ -65,11 +65,9 @@ print_prefix(struct oxr_logger *logger, const char *fmt, const char *prefix) { if (logger->api_func_name != NULL) { if (is_fmt_func_arg_start(fmt)) { - fprintf(stderr, "%s: %s", prefix, - logger->api_func_name); + fprintf(stderr, "%s: %s", prefix, logger->api_func_name); } else { - fprintf(stderr, "%s in %s: ", prefix, - logger->api_func_name); + fprintf(stderr, "%s in %s: ", prefix, logger->api_func_name); } } else { fprintf(stderr, "%s: ", prefix); @@ -153,8 +151,7 @@ oxr_error(struct oxr_logger *logger, XrResult result, const char *fmt, ...) va_end(args); fprintf(stderr, "\n"); - if (debug_get_bool_option_break_on_error() && - result != XR_ERROR_FUNCTION_UNSUPPORTED) { + if (debug_get_bool_option_break_on_error() && result != XR_ERROR_FUNCTION_UNSUPPORTED) { /// Trigger a debugger breakpoint. XRT_DEBUGBREAK(); } @@ -221,8 +218,7 @@ oxr_slog(struct oxr_sink_logger *slog, const char *fmt, ...) oxr_slog_ensure(slog, ret + 1); va_start(args, fmt); - ret = vsnprintf(slog->store + slog->length, - slog->store_size - slog->length, fmt, args); + ret = vsnprintf(slog->store + slog->length, slog->store_size - slog->length, fmt, args); va_end(args); slog->length += ret; @@ -249,9 +245,7 @@ oxr_warn_slog(struct oxr_logger *log, struct oxr_sink_logger *slog) } XrResult -oxr_error_slog(struct oxr_logger *log, - XrResult res, - struct oxr_sink_logger *slog) +oxr_error_slog(struct oxr_logger *log, XrResult res, struct oxr_sink_logger *slog) { oxr_error(log, res, "%s", slog->store); slog_free_store(slog); diff --git a/src/xrt/state_trackers/oxr/oxr_logger.h b/src/xrt/state_trackers/oxr/oxr_logger.h index 5d2d4a3d5..b749861e1 100644 --- a/src/xrt/state_trackers/oxr/oxr_logger.h +++ b/src/xrt/state_trackers/oxr/oxr_logger.h @@ -19,13 +19,13 @@ extern "C" { * * @ingroup oxr_main */ -#define OXR_WARN_ONCE(log, ...) \ - do { \ - static bool _once = false; \ - if (!_once) { \ - _once = true; \ - oxr_warn(log, __VA_ARGS__); \ - } \ +#define OXR_WARN_ONCE(log, ...) \ + do { \ + static bool _once = false; \ + if (!_once) { \ + _once = true; \ + oxr_warn(log, __VA_ARGS__); \ + } \ } while (false) /*! @@ -50,11 +50,9 @@ oxr_log_init(struct oxr_logger *logger, const char *api_func_name); void oxr_log_set_instance(struct oxr_logger *logger, struct oxr_instance *inst); void -oxr_log(struct oxr_logger *logger, const char *fmt, ...) - XRT_PRINTF_FORMAT(2, 3); +oxr_log(struct oxr_logger *logger, const char *fmt, ...) XRT_PRINTF_FORMAT(2, 3); void -oxr_warn(struct oxr_logger *logger, const char *fmt, ...) - XRT_PRINTF_FORMAT(2, 3); +oxr_warn(struct oxr_logger *logger, const char *fmt, ...) XRT_PRINTF_FORMAT(2, 3); /*! * Output an error and return the result code. @@ -70,8 +68,7 @@ oxr_warn(struct oxr_logger *logger, const char *fmt, ...) * msg`. */ XrResult -oxr_error(struct oxr_logger *logger, XrResult result, const char *fmt, ...) - XRT_PRINTF_FORMAT(3, 4); +oxr_error(struct oxr_logger *logger, XrResult result, const char *fmt, ...) XRT_PRINTF_FORMAT(3, 4); @@ -119,9 +116,7 @@ oxr_warn_slog(struct oxr_logger *log, struct oxr_sink_logger *slog); * Flush sink as a error message, frees all internal data. */ XrResult -oxr_error_slog(struct oxr_logger *log, - XrResult res, - struct oxr_sink_logger *slog); +oxr_error_slog(struct oxr_logger *log, XrResult res, struct oxr_sink_logger *slog); /*! diff --git a/src/xrt/state_trackers/oxr/oxr_messenger.c b/src/xrt/state_trackers/oxr/oxr_messenger.c index ae314bfe0..433b0d371 100644 --- a/src/xrt/state_trackers/oxr/oxr_messenger.c +++ b/src/xrt/state_trackers/oxr/oxr_messenger.c @@ -33,8 +33,7 @@ oxr_messenger_destroy(struct oxr_logger *log, struct oxr_handle_base *hb) return XR_SUCCESS; } } - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - " debug messenger not found in parent instance"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, " debug messenger not found in parent instance"); } //! @todo call into inst to create this instead? @@ -53,14 +52,11 @@ oxr_create_messenger(struct oxr_logger *log, } } if (parent_slot == NULL) { - return oxr_error( - log, XR_ERROR_LIMIT_REACHED, - " Instance cannot hold any more debug messengers"); + return oxr_error(log, XR_ERROR_LIMIT_REACHED, " Instance cannot hold any more debug messengers"); } struct oxr_debug_messenger *mssngr = NULL; - OXR_ALLOCATE_HANDLE_OR_RETURN(log, mssngr, OXR_XR_DEBUG_MESSENGER, - oxr_messenger_destroy, &inst->handle); + OXR_ALLOCATE_HANDLE_OR_RETURN(log, mssngr, OXR_XR_DEBUG_MESSENGER, oxr_messenger_destroy, &inst->handle); mssngr->inst = inst; mssngr->message_severities = createInfo->messageSeverities; diff --git a/src/xrt/state_trackers/oxr/oxr_objects.h b/src/xrt/state_trackers/oxr/oxr_objects.h index b27736272..7fab9f4c3 100644 --- a/src/xrt/state_trackers/oxr/oxr_objects.h +++ b/src/xrt/state_trackers/oxr/oxr_objects.h @@ -48,8 +48,7 @@ extern "C" { * * @ingroup oxr */ -#define XRT_CAST_PTR_TO_OXR_HANDLE(HANDLE_TYPE, PTR) \ - ((HANDLE_TYPE)(uint64_t)(uintptr_t)(PTR)) +#define XRT_CAST_PTR_TO_OXR_HANDLE(HANDLE_TYPE, PTR) ((HANDLE_TYPE)(uint64_t)(uintptr_t)(PTR)) /*! * @brief Cast an OpenXR handle to a pointer in such a way as to avoid warnings. @@ -60,8 +59,7 @@ extern "C" { * * @ingroup oxr */ -#define XRT_CAST_OXR_HANDLE_TO_PTR(PTR_TYPE, HANDLE) \ - ((PTR_TYPE)(uintptr_t)(uint64_t)(HANDLE)) +#define XRT_CAST_OXR_HANDLE_TO_PTR(PTR_TYPE, HANDLE) ((PTR_TYPE)(uintptr_t)(uint64_t)(HANDLE)) /*! * @defgroup oxr_main OpenXR main code @@ -128,8 +126,7 @@ struct time_state; * * @relates oxr_handle_base */ -typedef XrResult (*oxr_handle_destroyer)(struct oxr_logger *log, - struct oxr_handle_base *hb); +typedef XrResult (*oxr_handle_destroyer)(struct oxr_logger *log, struct oxr_handle_base *hb); /*! * State of a handle base, to reduce likelihood of going "boom" on @@ -216,9 +213,7 @@ oxr_instance_to_openxr(struct oxr_instance *inst) * @public @static @memberof oxr_instance */ XrResult -oxr_instance_create(struct oxr_logger *log, - const XrInstanceCreateInfo *createInfo, - struct oxr_instance **out_inst); +oxr_instance_create(struct oxr_logger *log, const XrInstanceCreateInfo *createInfo, struct oxr_instance **out_inst); /*! * @public @memberof oxr_instance @@ -271,17 +266,13 @@ oxr_path_init(struct oxr_logger *log, struct oxr_instance *inst); * @public @memberof oxr_instance */ bool -oxr_path_is_valid(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath path); +oxr_path_is_valid(struct oxr_logger *log, struct oxr_instance *inst, XrPath path); /*! * @public @memberof oxr_instance */ void * -oxr_path_get_attached(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath path); +oxr_path_get_attached(struct oxr_logger *log, struct oxr_instance *inst, XrPath path); /*! * Get the path for the given string if it exists, or create it if it does not. @@ -289,11 +280,8 @@ oxr_path_get_attached(struct oxr_logger *log, * @public @memberof oxr_instance */ XrResult -oxr_path_get_or_create(struct oxr_logger *log, - struct oxr_instance *inst, - const char *str, - size_t length, - XrPath *out_path); +oxr_path_get_or_create( + struct oxr_logger *log, struct oxr_instance *inst, const char *str, size_t length, XrPath *out_path); /*! * Only get the path for the given string if it exists. @@ -301,11 +289,7 @@ oxr_path_get_or_create(struct oxr_logger *log, * @public @memberof oxr_instance */ XrResult -oxr_path_only_get(struct oxr_logger *log, - struct oxr_instance *inst, - const char *str, - size_t length, - XrPath *out_path); +oxr_path_only_get(struct oxr_logger *log, struct oxr_instance *inst, const char *str, size_t length, XrPath *out_path); /*! * Get a pointer and length of the internal string. @@ -318,11 +302,8 @@ oxr_path_only_get(struct oxr_logger *log, * @public @memberof oxr_instance */ XrResult -oxr_path_get_string(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath path, - const char **out_str, - size_t *out_length); +oxr_path_get_string( + struct oxr_logger *log, struct oxr_instance *inst, XrPath path, const char **out_str, size_t *out_length); /*! * Destroy the path system and all paths that the instance has created. @@ -571,32 +552,29 @@ oxr_binding_find_bindings_from_key(struct oxr_logger *log, * @public @memberof oxr_instance */ XrResult -oxr_action_suggest_interaction_profile_bindings( - struct oxr_logger *log, - struct oxr_instance *inst, - const XrInteractionProfileSuggestedBinding *suggestedBindings); +oxr_action_suggest_interaction_profile_bindings(struct oxr_logger *log, + struct oxr_instance *inst, + const XrInteractionProfileSuggestedBinding *suggestedBindings); /*! * @public @memberof oxr_instance */ XrResult -oxr_action_get_current_interaction_profile( - struct oxr_logger *log, - struct oxr_session *sess, - XrPath topLevelUserPath, - XrInteractionProfileState *interactionProfile); +oxr_action_get_current_interaction_profile(struct oxr_logger *log, + struct oxr_session *sess, + XrPath topLevelUserPath, + XrInteractionProfileState *interactionProfile); /*! * @public @memberof oxr_session */ XrResult -oxr_action_get_input_source_localized_name( - struct oxr_logger *log, - struct oxr_session *sess, - const XrInputSourceLocalizedNameGetInfo *getInfo, - uint32_t bufferCapacityInput, - uint32_t *bufferCountOutput, - char *buffer); +oxr_action_get_input_source_localized_name(struct oxr_logger *log, + struct oxr_session *sess, + const XrInputSourceLocalizedNameGetInfo *getInfo, + uint32_t bufferCapacityInput, + uint32_t *bufferCountOutput, + char *buffer); /*! * @} @@ -634,9 +612,7 @@ oxr_session_enumerate_formats(struct oxr_logger *log, int64_t *formats); XrResult -oxr_session_begin(struct oxr_logger *log, - struct oxr_session *sess, - const XrSessionBeginInfo *beginInfo); +oxr_session_begin(struct oxr_logger *log, struct oxr_session *sess, const XrSessionBeginInfo *beginInfo); XrResult oxr_session_end(struct oxr_logger *log, struct oxr_session *sess); @@ -667,17 +643,13 @@ oxr_session_views(struct oxr_logger *log, XrView *views); XrResult -oxr_session_frame_wait(struct oxr_logger *log, - struct oxr_session *sess, - XrFrameState *frameState); +oxr_session_frame_wait(struct oxr_logger *log, struct oxr_session *sess, XrFrameState *frameState); XrResult oxr_session_frame_begin(struct oxr_logger *log, struct oxr_session *sess); XrResult -oxr_session_frame_end(struct oxr_logger *log, - struct oxr_session *sess, - const XrFrameEndInfo *frameEndInfo); +oxr_session_frame_end(struct oxr_logger *log, struct oxr_session *sess, const XrFrameEndInfo *frameEndInfo); XrResult oxr_session_hand_joints(struct oxr_logger *log, @@ -714,11 +686,8 @@ oxr_space_reference_create(struct oxr_logger *log, struct oxr_space **out_space); XrResult -oxr_space_locate(struct oxr_logger *log, - struct oxr_space *spc, - struct oxr_space *baseSpc, - XrTime time, - XrSpaceLocation *location); +oxr_space_locate( + struct oxr_logger *log, struct oxr_space *spc, struct oxr_space *baseSpc, XrTime time, XrSpaceLocation *location); XrResult oxr_space_ref_relation(struct oxr_logger *log, @@ -780,8 +749,7 @@ oxr_create_messenger(struct oxr_logger *, const XrDebugUtilsMessengerCreateInfoEXT *, struct oxr_debug_messenger **out_mssngr); XrResult -oxr_destroy_messenger(struct oxr_logger *log, - struct oxr_debug_messenger *mssngr); +oxr_destroy_messenger(struct oxr_logger *log, struct oxr_debug_messenger *mssngr); /* @@ -798,15 +766,10 @@ oxr_system_select(struct oxr_logger *log, struct oxr_system **out_selected); XrResult -oxr_system_fill_in(struct oxr_logger *log, - struct oxr_instance *inst, - XrSystemId systemId, - struct oxr_system *sys); +oxr_system_fill_in(struct oxr_logger *log, struct oxr_instance *inst, XrSystemId systemId, struct oxr_system *sys); XrResult -oxr_system_verify_id(struct oxr_logger *log, - const struct oxr_instance *inst, - XrSystemId systemId); +oxr_system_verify_id(struct oxr_logger *log, const struct oxr_instance *inst, XrSystemId systemId); XrResult oxr_system_get_by_id(struct oxr_logger *log, @@ -815,17 +778,14 @@ oxr_system_get_by_id(struct oxr_logger *log, struct oxr_system **system); XrResult -oxr_system_get_properties(struct oxr_logger *log, - struct oxr_system *sys, - XrSystemProperties *properties); +oxr_system_get_properties(struct oxr_logger *log, struct oxr_system *sys, XrSystemProperties *properties); XrResult -oxr_system_enumerate_view_confs( - struct oxr_logger *log, - struct oxr_system *sys, - uint32_t viewConfigurationTypeCapacityInput, - uint32_t *viewConfigurationTypeCountOutput, - XrViewConfigurationType *viewConfigurationTypes); +oxr_system_enumerate_view_confs(struct oxr_logger *log, + struct oxr_system *sys, + uint32_t viewConfigurationTypeCapacityInput, + uint32_t *viewConfigurationTypeCountOutput, + XrViewConfigurationType *viewConfigurationTypes); XrResult oxr_system_enumerate_blend_modes(struct oxr_logger *log, @@ -836,24 +796,21 @@ oxr_system_enumerate_blend_modes(struct oxr_logger *log, XrEnvironmentBlendMode *environmentBlendModes); XrResult -oxr_system_get_view_conf_properties( - struct oxr_logger *log, - struct oxr_system *sys, - XrViewConfigurationType viewConfigurationType, - XrViewConfigurationProperties *configurationProperties); +oxr_system_get_view_conf_properties(struct oxr_logger *log, + struct oxr_system *sys, + XrViewConfigurationType viewConfigurationType, + XrViewConfigurationProperties *configurationProperties); XrResult -oxr_system_enumerate_view_conf_views( - struct oxr_logger *log, - struct oxr_system *sys, - XrViewConfigurationType viewConfigurationType, - uint32_t viewCapacityInput, - uint32_t *viewCountOutput, - XrViewConfigurationView *views); +oxr_system_enumerate_view_conf_views(struct oxr_logger *log, + struct oxr_system *sys, + XrViewConfigurationType viewConfigurationType, + uint32_t viewCapacityInput, + uint32_t *viewCountOutput, + XrViewConfigurationView *views); bool -oxr_system_get_hand_tracking_support(struct oxr_logger *log, - struct oxr_instance *inst); +oxr_system_get_hand_tracking_support(struct oxr_logger *log, struct oxr_instance *inst); /* * @@ -862,9 +819,7 @@ oxr_system_get_hand_tracking_support(struct oxr_logger *log, */ XrResult -oxr_poll_event(struct oxr_logger *log, - struct oxr_instance *inst, - XrEventDataBuffer *eventData); +oxr_poll_event(struct oxr_logger *log, struct oxr_instance *inst, XrEventDataBuffer *eventData); XrResult oxr_event_push_XrEventDataSessionStateChanged(struct oxr_logger *log, @@ -873,19 +828,18 @@ oxr_event_push_XrEventDataSessionStateChanged(struct oxr_logger *log, XrTime time); XrResult -oxr_event_push_XrEventDataMainSessionVisibilityChangedEXTX( - struct oxr_logger *log, struct oxr_session *sess, bool visible); +oxr_event_push_XrEventDataMainSessionVisibilityChangedEXTX(struct oxr_logger *log, + struct oxr_session *sess, + bool visible); XrResult -oxr_event_push_XrEventDataInteractionProfileChanged(struct oxr_logger *log, - struct oxr_session *sess); +oxr_event_push_XrEventDataInteractionProfileChanged(struct oxr_logger *log, struct oxr_session *sess); /*! * This clears all pending events refers to the given session. */ XrResult -oxr_event_remove_session_events(struct oxr_logger *log, - struct oxr_session *sess); +oxr_event_remove_session_events(struct oxr_logger *log, struct oxr_session *sess); /* @@ -904,17 +858,13 @@ oxr_xdev_update(struct xrt_device *xdev); * Return true if it finds an input of that name on this device. */ bool -oxr_xdev_find_input(struct xrt_device *xdev, - enum xrt_input_name name, - struct xrt_input **out_input); +oxr_xdev_find_input(struct xrt_device *xdev, enum xrt_input_name name, struct xrt_input **out_input); /*! * Return true if it finds an output of that name on this device. */ bool -oxr_xdev_find_output(struct xrt_device *xdev, - enum xrt_output_name name, - struct xrt_output **out_output); +oxr_xdev_find_output(struct xrt_device *xdev, enum xrt_output_name name, struct xrt_output **out_output); void oxr_xdev_get_space_graph(struct oxr_logger *log, @@ -962,8 +912,7 @@ oxr_session_populate_gl_xlib(struct oxr_logger *log, #endif // XR_USE_GRAPHICS_API_OPENGL -#if defined(XR_USE_GRAPHICS_API_OPENGL) || \ - defined(XR_USE_GRAPHICS_API_OPENGL_ES) +#if defined(XR_USE_GRAPHICS_API_OPENGL) || defined(XR_USE_GRAPHICS_API_OPENGL_ES) XrResult oxr_swapchain_gl_create(struct oxr_logger *, struct oxr_session *sess, @@ -975,11 +924,10 @@ oxr_swapchain_gl_create(struct oxr_logger *, #if defined(XR_USE_GRAPHICS_API_OPENGL_ES) #if defined(XR_USE_PLATFORM_ANDROID) XrResult -oxr_session_populate_gles_android( - struct oxr_logger *log, - struct oxr_system *sys, - XrGraphicsBindingOpenGLESAndroidKHR const *next, - struct oxr_session *sess); +oxr_session_populate_gles_android(struct oxr_logger *log, + struct oxr_system *sys, + XrGraphicsBindingOpenGLESAndroidKHR const *next, + struct oxr_session *sess); #endif // XR_USE_PLATFORM_ANDROID #endif // XR_USE_GRAPHICS_API_OPENGL_ES @@ -1149,10 +1097,7 @@ struct oxr_system VkPhysicalDevice vulkan_enable2_physical_device; }; -#define GET_XDEV_BY_ROLE(SYS, ROLE) \ - SYS->role.ROLE == XRT_DEVICE_ROLE_UNASSIGNED \ - ? NULL \ - : SYS->xdevs[SYS->role.ROLE] +#define GET_XDEV_BY_ROLE(SYS, ROLE) SYS->role.ROLE == XRT_DEVICE_ROLE_UNASSIGNED ? NULL : SYS->xdevs[SYS->role.ROLE] #define MAKE_EXT_STATUS(mixed_case, all_caps) bool mixed_case; /*! @@ -1522,8 +1467,7 @@ struct oxr_action_set_attachment * @public @memberof oxr_action_set_attachment */ void -oxr_action_set_attachment_teardown( - struct oxr_action_set_attachment *act_set_attached); +oxr_action_set_attachment_teardown(struct oxr_action_set_attachment *act_set_attached); /*! @@ -1754,13 +1698,9 @@ struct oxr_swapchain const XrSwapchainImageAcquireInfo *, uint32_t *); - XrResult (*wait_image)(struct oxr_logger *, - struct oxr_swapchain *, - const XrSwapchainImageWaitInfo *); + XrResult (*wait_image)(struct oxr_logger *, struct oxr_swapchain *, const XrSwapchainImageWaitInfo *); - XrResult (*release_image)(struct oxr_logger *, - struct oxr_swapchain *, - const XrSwapchainImageReleaseInfo *); + XrResult (*release_image)(struct oxr_logger *, struct oxr_swapchain *, const XrSwapchainImageReleaseInfo *); }; struct oxr_refcounted diff --git a/src/xrt/state_trackers/oxr/oxr_path.c b/src/xrt/state_trackers/oxr/oxr_path.c index baa3cc05e..4e2b2b158 100644 --- a/src/xrt/state_trackers/oxr/oxr_path.c +++ b/src/xrt/state_trackers/oxr/oxr_path.c @@ -64,9 +64,7 @@ from_item(struct u_hashset_item *item) */ static XrResult -oxr_ensure_array_length(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath *out_id) +oxr_ensure_array_length(struct oxr_logger *log, struct oxr_instance *inst, XrPath *out_id) { size_t num = inst->path_num + 1; @@ -89,11 +87,8 @@ oxr_ensure_array_length(struct oxr_logger *log, } static XrResult -oxr_allocate_path(struct oxr_logger *log, - struct oxr_instance *inst, - const char *str, - size_t length, - struct oxr_path **out_path) +oxr_allocate_path( + struct oxr_logger *log, struct oxr_instance *inst, const char *str, size_t length, struct oxr_path **out_path) { struct u_hashset_item *item = NULL; struct oxr_path *path = NULL; @@ -108,8 +103,7 @@ oxr_allocate_path(struct oxr_logger *log, // Now allocate and setup the path. path = U_CALLOC_WITH_CAST(struct oxr_path, size); if (path == NULL) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to allocate path"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to allocate path"); } path->debug = OXR_XR_DEBUG_PATH; @@ -129,8 +123,7 @@ oxr_allocate_path(struct oxr_logger *log, ret = u_hashset_insert_item(inst->path_store, item); if (ret) { free(path); - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to insert item"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to insert item"); } oxr_ensure_array_length(log, inst, &path->id); @@ -142,9 +135,7 @@ oxr_allocate_path(struct oxr_logger *log, } struct oxr_path * -get_path_or_null(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath xr_path) +get_path_or_null(struct oxr_logger *log, struct oxr_instance *inst, XrPath xr_path) { if (xr_path >= inst->path_array_length) { return NULL; @@ -161,17 +152,13 @@ get_path_or_null(struct oxr_logger *log, */ bool -oxr_path_is_valid(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath xr_path) +oxr_path_is_valid(struct oxr_logger *log, struct oxr_instance *inst, XrPath xr_path) { return get_path_or_null(log, inst, xr_path) != NULL; } void * -oxr_path_get_attached(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath xr_path) +oxr_path_get_attached(struct oxr_logger *log, struct oxr_instance *inst, XrPath xr_path) { struct oxr_path *path = get_path_or_null(log, inst, xr_path); if (path == NULL) { @@ -182,11 +169,8 @@ oxr_path_get_attached(struct oxr_logger *log, } XrResult -oxr_path_get_or_create(struct oxr_logger *log, - struct oxr_instance *inst, - const char *str, - size_t length, - XrPath *out_path) +oxr_path_get_or_create( + struct oxr_logger *log, struct oxr_instance *inst, const char *str, size_t length, XrPath *out_path) { struct u_hashset_item *item; struct oxr_path *path = NULL; @@ -212,11 +196,7 @@ oxr_path_get_or_create(struct oxr_logger *log, } XrResult -oxr_path_only_get(struct oxr_logger *log, - struct oxr_instance *inst, - const char *str, - size_t length, - XrPath *out_path) +oxr_path_only_get(struct oxr_logger *log, struct oxr_instance *inst, const char *str, size_t length, XrPath *out_path) { struct u_hashset_item *item; int h_ret; @@ -233,11 +213,8 @@ oxr_path_only_get(struct oxr_logger *log, } XrResult -oxr_path_get_string(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath xr_path, - const char **out_str, - size_t *out_length) +oxr_path_get_string( + struct oxr_logger *log, struct oxr_instance *inst, XrPath xr_path, const char **out_str, size_t *out_length) { struct oxr_path *path = get_path_or_null(log, inst, xr_path); if (path == NULL) { @@ -263,8 +240,7 @@ oxr_path_init(struct oxr_logger *log, struct oxr_instance *inst) { int h_ret = u_hashset_create(&inst->path_store); if (h_ret != 0) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to create hashset"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to create hashset"); } size_t new_size = 64; @@ -290,7 +266,6 @@ oxr_path_destroy(struct oxr_logger *log, struct oxr_instance *inst) return; } - u_hashset_clear_and_call_for_each(inst->path_store, destroy_callback, - inst); + u_hashset_clear_and_call_for_each(inst->path_store, destroy_callback, inst); u_hashset_destroy(&inst->path_store); } diff --git a/src/xrt/state_trackers/oxr/oxr_session.c b/src/xrt/state_trackers/oxr/oxr_session.c index fc2c33a0f..a7fa2ff55 100644 --- a/src/xrt/state_trackers/oxr/oxr_session.c +++ b/src/xrt/state_trackers/oxr/oxr_session.c @@ -46,10 +46,9 @@ DEBUG_GET_ONCE_NUM_OPTION(ipd, "OXR_DEBUG_IPD_MM", 63) DEBUG_GET_ONCE_BOOL_OPTION(frame_timing_spew, "OXR_FRAME_TIMING_SPEW", false) -#define CALL_CHK(call) \ - if ((call) == XRT_ERROR_IPC_FAILURE) { \ - return oxr_error(log, XR_ERROR_INSTANCE_LOST, \ - "Error in function call over IPC"); \ +#define CALL_CHK(call) \ + if ((call) == XRT_ERROR_IPC_FAILURE) { \ + return oxr_error(log, XR_ERROR_INSTANCE_LOST, "Error in function call over IPC"); \ } static bool @@ -76,13 +75,11 @@ to_string(XrSessionState state) case XR_SESSION_STATE_UNKNOWN: return "XR_SESSION_STATE_UNKNOWN"; case XR_SESSION_STATE_IDLE: return "XR_SESSION_STATE_IDLE"; case XR_SESSION_STATE_READY: return "XR_SESSION_STATE_READY"; - case XR_SESSION_STATE_SYNCHRONIZED: - return "XR_SESSION_STATE_SYNCHRONIZED"; + case XR_SESSION_STATE_SYNCHRONIZED: return "XR_SESSION_STATE_SYNCHRONIZED"; case XR_SESSION_STATE_VISIBLE: return "XR_SESSION_STATE_VISIBLE"; case XR_SESSION_STATE_FOCUSED: return "XR_SESSION_STATE_FOCUSED"; case XR_SESSION_STATE_STOPPING: return "XR_SESSION_STATE_STOPPING"; - case XR_SESSION_STATE_LOSS_PENDING: - return "XR_SESSION_STATE_LOSS_PENDING"; + case XR_SESSION_STATE_LOSS_PENDING: return "XR_SESSION_STATE_LOSS_PENDING"; case XR_SESSION_STATE_EXITING: return "XR_SESSION_STATE_EXITING"; case XR_SESSION_STATE_MAX_ENUM: return "XR_SESSION_STATE_MAX_ENUM"; default: return ""; @@ -90,9 +87,7 @@ to_string(XrSessionState state) } static void -oxr_session_change_state(struct oxr_logger *log, - struct oxr_session *sess, - XrSessionState state) +oxr_session_change_state(struct oxr_logger *log, struct oxr_session *sess, XrSessionState state) { oxr_event_push_XrEventDataSessionStateChanged(log, sess, state, 0); sess->state = state; @@ -107,8 +102,7 @@ oxr_session_enumerate_formats(struct oxr_logger *log, { struct xrt_compositor *xc = sess->compositor; if (formatCountOutput == NULL) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "(formatCountOutput == NULL) can not be null"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(formatCountOutput == NULL) can not be null"); } if (xc == NULL) { if (formatCountOutput != NULL) { @@ -117,39 +111,31 @@ oxr_session_enumerate_formats(struct oxr_logger *log, return oxr_session_success_result(sess); } - OXR_TWO_CALL_HELPER(log, formatCapacityInput, formatCountOutput, - formats, xc->info.num_formats, xc->info.formats, - oxr_session_success_result(sess)); + OXR_TWO_CALL_HELPER(log, formatCapacityInput, formatCountOutput, formats, xc->info.num_formats, + xc->info.formats, oxr_session_success_result(sess)); } XrResult -oxr_session_begin(struct oxr_logger *log, - struct oxr_session *sess, - const XrSessionBeginInfo *beginInfo) +oxr_session_begin(struct oxr_logger *log, struct oxr_session *sess, const XrSessionBeginInfo *beginInfo) { if (is_running(sess)) { - return oxr_error(log, XR_ERROR_SESSION_RUNNING, - "Session is already running"); + return oxr_error(log, XR_ERROR_SESSION_RUNNING, "Session is already running"); } struct xrt_compositor *xc = sess->compositor; if (xc != NULL) { - XrViewConfigurationType view_type = - beginInfo->primaryViewConfigurationType; + XrViewConfigurationType view_type = beginInfo->primaryViewConfigurationType; if (view_type != sess->sys->view_config_type) { /*! @todo we only support a single view config type per * system right now */ - return oxr_error( - log, XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED, - "(beginInfo->primaryViewConfigurationType == " - "0x%08x) view configuration type not supported", - view_type); + return oxr_error(log, XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED, + "(beginInfo->primaryViewConfigurationType == " + "0x%08x) view configuration type not supported", + view_type); } - CALL_CHK(xrt_comp_begin_session( - xc, (enum xrt_view_type) - beginInfo->primaryViewConfigurationType)); + CALL_CHK(xrt_comp_begin_session(xc, (enum xrt_view_type)beginInfo->primaryViewConfigurationType)); } sess->has_begun = true; @@ -163,12 +149,10 @@ oxr_session_end(struct oxr_logger *log, struct oxr_session *sess) struct xrt_compositor *xc = sess->compositor; if (!is_running(sess)) { - return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, - "Session is not running"); + return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, "Session is not running"); } if (sess->state != XR_SESSION_STATE_STOPPING) { - return oxr_error(log, XR_ERROR_SESSION_NOT_STOPPING, - "Session is not stopping"); + return oxr_error(log, XR_ERROR_SESSION_NOT_STOPPING, "Session is not stopping"); } if (xc != NULL) { @@ -201,20 +185,17 @@ XrResult oxr_session_request_exit(struct oxr_logger *log, struct oxr_session *sess) { if (!is_running(sess)) { - return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, - "Session is not running"); + return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, "Session is not running"); } if (sess->state == XR_SESSION_STATE_FOCUSED) { oxr_session_change_state(log, sess, XR_SESSION_STATE_VISIBLE); } if (sess->state == XR_SESSION_STATE_VISIBLE) { - oxr_session_change_state(log, sess, - XR_SESSION_STATE_SYNCHRONIZED); + oxr_session_change_state(log, sess, XR_SESSION_STATE_SYNCHRONIZED); } if (!sess->has_ended_once) { - oxr_session_change_state(log, sess, - XR_SESSION_STATE_SYNCHRONIZED); + oxr_session_change_state(log, sess, XR_SESSION_STATE_SYNCHRONIZED); // Fake the synchronization. sess->has_ended_once = true; } @@ -249,20 +230,17 @@ oxr_session_poll(struct oxr_logger *log, struct oxr_session *sess) sess->compositor_focused = xce.state.focused; break; case XRT_COMPOSITOR_EVENT_OVERLAY_CHANGE: - oxr_event_push_XrEventDataMainSessionVisibilityChangedEXTX( - log, sess, xce.overlay.visible); + oxr_event_push_XrEventDataMainSessionVisibilityChangedEXTX(log, sess, xce.overlay.visible); break; default: U_LOG_W("unhandled event type! %d", xce.type); break; } } - if (sess->state == XR_SESSION_STATE_SYNCHRONIZED && - sess->compositor_visible) { + if (sess->state == XR_SESSION_STATE_SYNCHRONIZED && sess->compositor_visible) { oxr_session_change_state(log, sess, XR_SESSION_STATE_VISIBLE); } - if (sess->state == XR_SESSION_STATE_VISIBLE && - sess->compositor_focused) { + if (sess->state == XR_SESSION_STATE_VISIBLE && sess->compositor_focused) { oxr_session_change_state(log, sess, XR_SESSION_STATE_FOCUSED); } } @@ -287,39 +265,32 @@ oxr_session_get_view_relation_at(struct oxr_logger *log, // Applies the offset in the function. struct xrt_space_graph xsg = {0}; - oxr_xdev_get_space_graph(log, sess->sys->inst, xdev, - XRT_INPUT_GENERIC_HEAD_POSE, at_time, &xsg); + oxr_xdev_get_space_graph(log, sess->sys->inst, xdev, XRT_INPUT_GENERIC_HEAD_POSE, at_time, &xsg); m_space_graph_resolve(&xsg, out_relation); return oxr_session_success_result(sess); } void -print_view_fov(struct oxr_session *sess, - uint32_t index, - const struct xrt_fov *fov) +print_view_fov(struct oxr_session *sess, uint32_t index, const struct xrt_fov *fov) { if (!sess->sys->inst->debug_views) { return; } - U_LOG_D("views[%i].fov = {%f, %f, %f, %f}", index, fov->angle_left, - fov->angle_right, fov->angle_up, fov->angle_down); + U_LOG_D("views[%i].fov = {%f, %f, %f, %f}", index, fov->angle_left, fov->angle_right, fov->angle_up, + fov->angle_down); } void -print_view_pose(struct oxr_session *sess, - uint32_t index, - const struct xrt_pose *pose) +print_view_pose(struct oxr_session *sess, uint32_t index, const struct xrt_pose *pose) { if (!sess->sys->inst->debug_views) { return; } - U_LOG_D("views[%i].pose = {{%f, %f, %f, %f}, {%f, %f, %f}}", index, - pose->orientation.x, pose->orientation.y, pose->orientation.z, - pose->orientation.w, pose->position.x, pose->position.y, - pose->position.z); + U_LOG_D("views[%i].pose = {{%f, %f, %f, %f}, {%f, %f, %f}}", index, pose->orientation.x, pose->orientation.y, + pose->orientation.z, pose->orientation.w, pose->position.x, pose->position.y, pose->position.z); } static inline XrViewStateFlags @@ -351,8 +322,7 @@ oxr_session_views(struct oxr_logger *log, XrView *views) { struct xrt_device *xdev = GET_XDEV_BY_ROLE(sess->sys, head); - struct oxr_space *baseSpc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_space *, viewLocateInfo->space); + struct oxr_space *baseSpc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, viewLocateInfo->space); uint32_t num_views = 2; // Does this apply for all calls? @@ -369,21 +339,18 @@ oxr_session_views(struct oxr_logger *log, return oxr_session_success_result(sess); } if (viewCapacityInput < num_views) { - return oxr_error(log, XR_ERROR_SIZE_INSUFFICIENT, - "(viewCapacityInput == %u) need %u", + return oxr_error(log, XR_ERROR_SIZE_INSUFFICIENT, "(viewCapacityInput == %u) need %u", viewCapacityInput, num_views); } // End two call handling. if (sess->sys->inst->debug_views) { - U_LOG_D("viewLocateInfo->displayTime %" PRIu64, - viewLocateInfo->displayTime); + U_LOG_D("viewLocateInfo->displayTime %" PRIu64, viewLocateInfo->displayTime); } // Get the viewLocateInfo->space to view space relation. struct xrt_space_relation pure_relation; - oxr_space_ref_relation(log, sess, XR_REFERENCE_SPACE_TYPE_VIEW, - baseSpc->type, viewLocateInfo->displayTime, + oxr_space_ref_relation(log, sess, XR_REFERENCE_SPACE_TYPE_VIEW, baseSpc->type, viewLocateInfo->displayTime, &pure_relation); // @todo the fov information that we get from xdev->hmd->views[i].fov is @@ -427,29 +394,24 @@ oxr_session_views(struct oxr_logger *log, views[i].fov = safe_copy_fov.oxr; struct xrt_pose *pose = (struct xrt_pose *)&views[i].pose; - if ((result.relation_flags & - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT) != 0 && + if ((result.relation_flags & XRT_SPACE_RELATION_ORIENTATION_VALID_BIT) != 0 && !math_quat_ensure_normalized(&pose->orientation)) { struct xrt_quat *q = &pose->orientation; struct xrt_quat norm = *q; math_quat_normalize(&norm); - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "Quaternion %a %a %a %a (normalized %a %a %a %a) " - "in xrLocateViews was invalid", - q->x, q->y, q->z, q->w, norm.x, norm.y, norm.z, - norm.w); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "Quaternion %a %a %a %a (normalized %a %a %a %a) " + "in xrLocateViews was invalid", + q->x, q->y, q->z, q->w, norm.x, norm.y, norm.z, norm.w); } print_view_fov(sess, i, (struct xrt_fov *)&views[i].fov); print_view_pose(sess, i, (struct xrt_pose *)&views[i].pose); if (i == 0) { - viewState->viewStateFlags = - xrt_to_view_state_flags(result.relation_flags); + viewState->viewStateFlags = xrt_to_view_state_flags(result.relation_flags); } else { - viewState->viewStateFlags &= - xrt_to_view_state_flags(result.relation_flags); + viewState->viewStateFlags &= xrt_to_view_state_flags(result.relation_flags); } } @@ -467,26 +429,21 @@ static double ts_ms(struct oxr_session *sess) { timepoint_ns now = time_state_get_now(sess->sys->inst->timekeeping); - int64_t monotonic = - time_state_ts_to_monotonic_ns(sess->sys->inst->timekeeping, now); + int64_t monotonic = time_state_ts_to_monotonic_ns(sess->sys->inst->timekeeping, now); return ns_to_ms(monotonic); } XrResult -oxr_session_frame_wait(struct oxr_logger *log, - struct oxr_session *sess, - XrFrameState *frameState) +oxr_session_frame_wait(struct oxr_logger *log, struct oxr_session *sess, XrFrameState *frameState) { if (!is_running(sess)) { - return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, - "Session is not running"); + return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, "Session is not running"); } //! @todo this should be carefully synchronized, because there may be //! more than one session per instance. - XRT_MAYBE_UNUSED timepoint_ns now = - time_state_get_now_and_update(sess->sys->inst->timekeeping); + XRT_MAYBE_UNUSED timepoint_ns now = time_state_get_now_and_update(sess->sys->inst->timekeeping); struct xrt_compositor *xc = sess->compositor; if (xc == NULL) { @@ -507,33 +464,26 @@ oxr_session_frame_wait(struct oxr_logger *log, os_semaphore_wait(&sess->sem, 0); if (sess->frame_timing_spew) { - oxr_log(log, - "Finished waiting for previous frame begin at %8.3fms", - ts_ms(sess)); + oxr_log(log, "Finished waiting for previous frame begin at %8.3fms", ts_ms(sess)); } uint64_t predicted_display_time; uint64_t predicted_display_period; - CALL_CHK(xrt_comp_wait_frame(xc, &sess->frame_id.waited, - &predicted_display_time, - &predicted_display_period)); + CALL_CHK(xrt_comp_wait_frame(xc, &sess->frame_id.waited, &predicted_display_time, &predicted_display_period)); if ((int64_t)predicted_display_time <= 0) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Got a negative display time '%" PRIi64 "'", + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Got a negative display time '%" PRIi64 "'", (int64_t)predicted_display_time); } frameState->shouldRender = should_render(sess->state); frameState->predictedDisplayPeriod = predicted_display_period; - frameState->predictedDisplayTime = time_state_monotonic_to_ts_ns( - sess->sys->inst->timekeeping, predicted_display_time); + frameState->predictedDisplayTime = + time_state_monotonic_to_ts_ns(sess->sys->inst->timekeeping, predicted_display_time); if (frameState->predictedDisplayTime <= 0) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "Time_state_monotonic_to_ts_ns returned '%" PRIi64 "'", - frameState->predictedDisplayTime); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Time_state_monotonic_to_ts_ns returned '%" PRIi64 "'", + frameState->predictedDisplayTime); } if (sess->frame_timing_spew) { @@ -541,8 +491,7 @@ oxr_session_frame_wait(struct oxr_logger *log, "Waiting finished at %8.3fms. Predicted display time " "%8.3fms, " "period %8.3fms", - ts_ms(sess), ns_to_ms(predicted_display_time), - ns_to_ms(predicted_display_period)); + ts_ms(sess), ns_to_ms(predicted_display_time), ns_to_ms(predicted_display_period)); } return oxr_session_success_result(sess); @@ -552,8 +501,7 @@ XrResult oxr_session_frame_begin(struct oxr_logger *log, struct oxr_session *sess) { if (!is_running(sess)) { - return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, - "Session is not running"); + return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, "Session is not running"); } struct xrt_compositor *xc = sess->compositor; @@ -564,23 +512,20 @@ oxr_session_frame_begin(struct oxr_logger *log, struct oxr_session *sess) XrResult ret; if (active_wait_frames == 0) { - return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, - "xrBeginFrame without xrWaitFrame"); + return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "xrBeginFrame without xrWaitFrame"); } if (sess->frame_started) { // max 2 xrWaitFrame can be in flight so a second xrBeginFrame // is only valid if we have a second xrWaitFrame in flight if (active_wait_frames != 2) { - return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, - "xrBeginFrame without xrWaitFrame"); + return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "xrBeginFrame without xrWaitFrame"); } ret = XR_FRAME_DISCARDED; if (xc != NULL) { - CALL_CHK( - xrt_comp_discard_frame(xc, sess->frame_id.begun)); + CALL_CHK(xrt_comp_discard_frame(xc, sess->frame_id.begun)); sess->frame_id.begun = -1; os_mutex_lock(&sess->active_wait_frames_lock); @@ -619,11 +564,10 @@ static XrResult verify_space(struct oxr_logger *log, uint32_t layer_index, XrSpace space) { if (space == XR_NULL_HANDLE) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(frameEndInfo->layers[%u]->space == " - "XR_NULL_HANDLE) XrSpace must not be XR_NULL_HANDLE", - layer_index); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(frameEndInfo->layers[%u]->space == " + "XR_NULL_HANDLE) XrSpace must not be XR_NULL_HANDLE", + layer_index); } return XR_SUCCESS; @@ -662,8 +606,7 @@ verify_quad_layer(struct xrt_compositor *xc, struct xrt_device *head, uint64_t timestamp) { - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, quad->subImage.swapchain); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, quad->subImage.swapchain); if (sc == NULL) { return oxr_error(log, XR_ERROR_LAYER_INVALID, @@ -694,13 +637,11 @@ verify_quad_layer(struct xrt_compositor *xc, } if (sc->num_array_layers <= quad->subImage.imageArrayIndex) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(frameEndInfo->layers[%u]->subImage.imageArrayIndex == " - "%u) Invalid swapchain array " - "index for quad layer (%u).", - layer_index, quad->subImage.imageArrayIndex, - sc->num_array_layers); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(frameEndInfo->layers[%u]->subImage.imageArrayIndex == " + "%u) Invalid swapchain array " + "index for quad layer (%u).", + layer_index, quad->subImage.imageArrayIndex, sc->num_array_layers); } if (!sc->released.yes) { @@ -711,32 +652,26 @@ verify_quad_layer(struct xrt_compositor *xc, } if (sc->released.index >= (int)sc->swapchain->num_images) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "(frameEndInfo->layers[%u]->subImage.swapchain) internal " - "image index out of bounds", - layer_index); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "(frameEndInfo->layers[%u]->subImage.swapchain) internal " + "image index out of bounds", + layer_index); } if (is_rect_neg(&quad->subImage.imageRect)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->subImage.imageRect.offset == " - "{%i, %i}) has negative component(s)", - layer_index, quad->subImage.imageRect.offset.x, - quad->subImage.imageRect.offset.y); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->subImage.imageRect.offset == " + "{%i, %i}) has negative component(s)", + layer_index, quad->subImage.imageRect.offset.x, quad->subImage.imageRect.offset.y); } if (is_rect_out_of_bounds(&quad->subImage.imageRect, sc)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->subImage.imageRect == {{%i, " - "%i}, {%u, %u}}) imageRect out of image bounds (%u, %u)", - layer_index, quad->subImage.imageRect.offset.x, - quad->subImage.imageRect.offset.y, - quad->subImage.imageRect.extent.width, - quad->subImage.imageRect.extent.height, sc->width, - sc->height); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->subImage.imageRect == {{%i, " + "%i}, {%u, %u}}) imageRect out of image bounds (%u, %u)", + layer_index, quad->subImage.imageRect.offset.x, quad->subImage.imageRect.offset.y, + quad->subImage.imageRect.extent.width, quad->subImage.imageRect.extent.height, + sc->width, sc->height); } return XR_SUCCESS; @@ -757,8 +692,7 @@ verify_depth_layer(struct xrt_compositor *xc, layer_index, i); } - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, depth->subImage.swapchain); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, depth->subImage.swapchain); if (!sc->released.yes) { return oxr_error(log, XR_ERROR_LAYER_INVALID, @@ -769,23 +703,20 @@ verify_depth_layer(struct xrt_compositor *xc, } if (sc->released.index >= (int)sc->swapchain->num_images) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "(frameEndInfo->layers[%u]->views[%i]->next<" - "XrCompositionLayerDepthInfoKHR>.subImage." - "swapchain) internal image index out of bounds", - layer_index, i); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "(frameEndInfo->layers[%u]->views[%i]->next<" + "XrCompositionLayerDepthInfoKHR>.subImage." + "swapchain) internal image index out of bounds", + layer_index, i); } if (sc->num_array_layers <= depth->subImage.imageArrayIndex) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(frameEndInfo->layers[%u]->views[%i]->next<" - "XrCompositionLayerDepthInfoKHR>.subImage." - "imageArrayIndex == %u) Invalid swapchain array " - "index for projection layer (%u).", - layer_index, i, depth->subImage.imageArrayIndex, - sc->num_array_layers); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(frameEndInfo->layers[%u]->views[%i]->next<" + "XrCompositionLayerDepthInfoKHR>.subImage." + "imageArrayIndex == %u) Invalid swapchain array " + "index for projection layer (%u).", + layer_index, i, depth->subImage.imageArrayIndex, sc->num_array_layers); } if (is_rect_neg(&depth->subImage.imageRect)) { @@ -794,23 +725,19 @@ verify_depth_layer(struct xrt_compositor *xc, "XrCompositionLayerDepthInfoKHR>.subImage." "imageRect.offset == {%i, " "%i}) has negative component(s)", - layer_index, i, - depth->subImage.imageRect.offset.x, + layer_index, i, depth->subImage.imageRect.offset.x, depth->subImage.imageRect.offset.y); } if (is_rect_out_of_bounds(&depth->subImage.imageRect, sc)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->views[%i]->next<" - "XrCompositionLayerDepthInfoKHR>.subImage." - "imageRect == {{%i, %i}, {%u, %u}}) imageRect out " - "of image bounds (%u, %u)", - layer_index, i, depth->subImage.imageRect.offset.x, - depth->subImage.imageRect.offset.y, - depth->subImage.imageRect.extent.width, - depth->subImage.imageRect.extent.height, sc->width, - sc->height); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->views[%i]->next<" + "XrCompositionLayerDepthInfoKHR>.subImage." + "imageRect == {{%i, %i}, {%u, %u}}) imageRect out " + "of image bounds (%u, %u)", + layer_index, i, depth->subImage.imageRect.offset.x, depth->subImage.imageRect.offset.y, + depth->subImage.imageRect.extent.width, depth->subImage.imageRect.extent.height, + sc->width, sc->height); } if (depth->minDepth < 0.0f || depth->minDepth > 1.0f) { @@ -834,8 +761,7 @@ verify_depth_layer(struct xrt_compositor *xc, "(frameEndInfo->layers[%u]->views[%i]->next<" "XrCompositionLayerDepthInfoKHR>.minDepth) %f " "must be <= maxDepth %f ", - layer_index, i, depth->minDepth, - depth->maxDepth); + layer_index, i, depth->minDepth, depth->maxDepth); } if (depth->nearZ == depth->farZ) { @@ -864,11 +790,10 @@ verify_projection_layer(struct xrt_compositor *xc, } if (proj->viewCount != 2) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(frameEndInfo->layers[%u]->viewCount == %u) must be 2 for " - "projection layers and the current view configuration", - layer_index, proj->viewCount); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(frameEndInfo->layers[%u]->viewCount == %u) must be 2 for " + "projection layers and the current view configuration", + layer_index, proj->viewCount); } // number of depth layers must be 0 or proj->viewCount @@ -879,61 +804,51 @@ verify_projection_layer(struct xrt_compositor *xc, const XrCompositionLayerProjectionView *view = &proj->views[i]; //! @todo More validation? - if (!math_quat_validate( - (struct xrt_quat *)&view->pose.orientation)) { + if (!math_quat_validate((struct xrt_quat *)&view->pose.orientation)) { const XrQuaternionf *q = &view->pose.orientation; - return oxr_error( - log, XR_ERROR_POSE_INVALID, - "(frameEndInfo->layers[%u]->views[%i]->pose." - "orientation == {%f %f %f %f}) is not a valid quat", - layer_index, i, q->x, q->y, q->z, q->w); + return oxr_error(log, XR_ERROR_POSE_INVALID, + "(frameEndInfo->layers[%u]->views[%i]->pose." + "orientation == {%f %f %f %f}) is not a valid quat", + layer_index, i, q->x, q->y, q->z, q->w); } - if (!math_vec3_validate( - (struct xrt_vec3 *)&view->pose.position)) { + if (!math_vec3_validate((struct xrt_vec3 *)&view->pose.position)) { const XrVector3f *p = &view->pose.position; - return oxr_error( - log, XR_ERROR_POSE_INVALID, - "(frameEndInfo->layers[%u]->views[%i]->pose." - "position == {%f %f %f}) is not valid", - layer_index, i, p->x, p->y, p->z); + return oxr_error(log, XR_ERROR_POSE_INVALID, + "(frameEndInfo->layers[%u]->views[%i]->pose." + "position == {%f %f %f}) is not valid", + layer_index, i, p->x, p->y, p->z); } if (view->subImage.swapchain == XR_NULL_HANDLE) { - return oxr_error( - log, XR_ERROR_HANDLE_INVALID, - "(frameEndInfo->layers[%u]->views[%i]->subImage." - "swapchain is XR_NULL_HANDLE", - layer_index, i); + return oxr_error(log, XR_ERROR_HANDLE_INVALID, + "(frameEndInfo->layers[%u]->views[%i]->subImage." + "swapchain is XR_NULL_HANDLE", + layer_index, i); } - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, view->subImage.swapchain); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, view->subImage.swapchain); if (!sc->released.yes) { - return oxr_error( - log, XR_ERROR_LAYER_INVALID, - "(frameEndInfo->layers[%u]->views[%i].subImage." - "swapchain) swapchain has not been released", - layer_index, i); + return oxr_error(log, XR_ERROR_LAYER_INVALID, + "(frameEndInfo->layers[%u]->views[%i].subImage." + "swapchain) swapchain has not been released", + layer_index, i); } if (sc->released.index >= (int)sc->swapchain->num_images) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "(frameEndInfo->layers[%u]->views[%i].subImage." - "swapchain) internal image index out of bounds", - layer_index, i); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "(frameEndInfo->layers[%u]->views[%i].subImage." + "swapchain) internal image index out of bounds", + layer_index, i); } if (sc->num_array_layers <= view->subImage.imageArrayIndex) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(frameEndInfo->layers[%u]->views[%i]->subImage." - "imageArrayIndex == %u) Invalid swapchain array " - "index for projection layer (%u).", - layer_index, i, view->subImage.imageArrayIndex, - sc->num_array_layers); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(frameEndInfo->layers[%u]->views[%i]->subImage." + "imageArrayIndex == %u) Invalid swapchain array " + "index for projection layer (%u).", + layer_index, i, view->subImage.imageArrayIndex, sc->num_array_layers); } if (is_rect_neg(&view->subImage.imageRect)) { @@ -941,33 +856,26 @@ verify_projection_layer(struct xrt_compositor *xc, "(frameEndInfo->layers[%u]->views[%i]-" ">subImage.imageRect.offset == {%i, " "%i}) has negative component(s)", - layer_index, i, - view->subImage.imageRect.offset.x, + layer_index, i, view->subImage.imageRect.offset.x, view->subImage.imageRect.offset.y); } if (is_rect_out_of_bounds(&view->subImage.imageRect, sc)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->views[%i]->subImage." - "imageRect == {{%i, %i}, {%u, %u}}) imageRect out " - "of image bounds (%u, %u)", - layer_index, i, view->subImage.imageRect.offset.x, - view->subImage.imageRect.offset.y, - view->subImage.imageRect.extent.width, - view->subImage.imageRect.extent.height, sc->width, - sc->height); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->views[%i]->subImage." + "imageRect == {{%i, %i}, {%u, %u}}) imageRect out " + "of image bounds (%u, %u)", + layer_index, i, view->subImage.imageRect.offset.x, + view->subImage.imageRect.offset.y, view->subImage.imageRect.extent.width, + view->subImage.imageRect.extent.height, sc->width, sc->height); } #ifdef XRT_FEATURE_OPENXR_LAYER_DEPTH - const XrCompositionLayerDepthInfoKHR *depth_info = - OXR_GET_INPUT_FROM_CHAIN( - view, XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, - XrCompositionLayerDepthInfoKHR); + const XrCompositionLayerDepthInfoKHR *depth_info = OXR_GET_INPUT_FROM_CHAIN( + view, XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, XrCompositionLayerDepthInfoKHR); if (depth_info) { - ret = verify_depth_layer(xc, log, layer_index, i, - depth_info); + ret = verify_depth_layer(xc, log, layer_index, i, depth_info); if (ret != XR_SUCCESS) { return ret; } @@ -978,11 +886,10 @@ verify_projection_layer(struct xrt_compositor *xc, #ifdef XRT_FEATURE_OPENXR_LAYER_DEPTH if (num_depth_layers > 0 && num_depth_layers != proj->viewCount) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(frameEndInfo->layers[%u] projection layer must have %u " - "depth layers or none, but has: %u)", - layer_index, proj->viewCount, num_depth_layers); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(frameEndInfo->layers[%u] projection layer must have %u " + "depth layers or none, but has: %u)", + layer_index, proj->viewCount, num_depth_layers); } #endif // XRT_FEATURE_OPENXR_LAYER_DEPTH @@ -1003,8 +910,7 @@ verify_cube_layer(struct xrt_compositor *xc, "XrCompositionLayerCubeKHR not supported", layer_index); #else - struct oxr_swapchain *sc = - XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, cube->swapchain); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, cube->swapchain); if (sc == NULL) { return oxr_error(log, XR_ERROR_LAYER_INVALID, @@ -1027,11 +933,10 @@ verify_cube_layer(struct xrt_compositor *xc, } if (sc->num_array_layers <= cube->imageArrayIndex) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(frameEndInfo->layers[%u]->imageArrayIndex == %u) Invalid " - "swapchain array index for cube layer (%u).", - layer_index, cube->imageArrayIndex, sc->num_array_layers); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(frameEndInfo->layers[%u]->imageArrayIndex == %u) Invalid " + "swapchain array index for cube layer (%u).", + layer_index, cube->imageArrayIndex, sc->num_array_layers); } if (!sc->released.yes) { @@ -1042,11 +947,10 @@ verify_cube_layer(struct xrt_compositor *xc, } if (sc->released.index >= (int)sc->swapchain->num_images) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "(frameEndInfo->layers[%u]->subImage.swapchain) internal " - "image index out of bounds", - layer_index); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "(frameEndInfo->layers[%u]->subImage.swapchain) internal " + "image index out of bounds", + layer_index); } return XR_SUCCESS; @@ -1067,8 +971,7 @@ verify_cylinder_layer(struct xrt_compositor *xc, "XrCompositionLayerCylinderKHR not supported", layer_index); #else - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, cylinder->subImage.swapchain); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, cylinder->subImage.swapchain); if (sc == NULL) { return oxr_error(log, XR_ERROR_LAYER_INVALID, @@ -1082,8 +985,7 @@ verify_cylinder_layer(struct xrt_compositor *xc, return ret; } - if (!math_quat_validate( - (struct xrt_quat *)&cylinder->pose.orientation)) { + if (!math_quat_validate((struct xrt_quat *)&cylinder->pose.orientation)) { const XrQuaternionf *q = &cylinder->pose.orientation; return oxr_error(log, XR_ERROR_POSE_INVALID, "(frameEndInfo->layers[%u]->pose.orientation " @@ -1104,9 +1006,7 @@ verify_cylinder_layer(struct xrt_compositor *xc, "(frameEndInfo->layers[%u]->subImage." "imageArrayIndex == %u) Invalid swapchain " "array index for cylinder layer (%u).", - layer_index, - cylinder->subImage.imageArrayIndex, - sc->num_array_layers); + layer_index, cylinder->subImage.imageArrayIndex, sc->num_array_layers); } if (!sc->released.yes) { @@ -1117,32 +1017,27 @@ verify_cylinder_layer(struct xrt_compositor *xc, } if (sc->released.index >= (int)sc->swapchain->num_images) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "(frameEndInfo->layers[%u]->subImage.swapchain) internal " - "image index out of bounds", - layer_index); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "(frameEndInfo->layers[%u]->subImage.swapchain) internal " + "image index out of bounds", + layer_index); } if (is_rect_neg(&cylinder->subImage.imageRect)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->subImage.imageRect.offset == " - "{%i, %i}) has negative component(s)", - layer_index, cylinder->subImage.imageRect.offset.x, - cylinder->subImage.imageRect.offset.y); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->subImage.imageRect.offset == " + "{%i, %i}) has negative component(s)", + layer_index, cylinder->subImage.imageRect.offset.x, + cylinder->subImage.imageRect.offset.y); } if (is_rect_out_of_bounds(&cylinder->subImage.imageRect, sc)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->subImage.imageRect == {{%i, " - "%i}, {%u, %u}}) imageRect out of image bounds (%u, %u)", - layer_index, cylinder->subImage.imageRect.offset.x, - cylinder->subImage.imageRect.offset.y, - cylinder->subImage.imageRect.extent.width, - cylinder->subImage.imageRect.extent.height, sc->width, - sc->height); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->subImage.imageRect == {{%i, " + "%i}, {%u, %u}}) imageRect out of image bounds (%u, %u)", + layer_index, cylinder->subImage.imageRect.offset.x, + cylinder->subImage.imageRect.offset.y, cylinder->subImage.imageRect.extent.width, + cylinder->subImage.imageRect.extent.height, sc->width, sc->height); } if (cylinder->radius < 0.f) { @@ -1152,8 +1047,7 @@ verify_cylinder_layer(struct xrt_compositor *xc, layer_index, cylinder->radius); } - if (cylinder->centralAngle < 0.f || - cylinder->centralAngle > (M_PI * 2)) { + if (cylinder->centralAngle < 0.f || cylinder->centralAngle > (M_PI * 2)) { return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(frameEndInfo->layers[%u]->centralAngle == " "%f) centralAngle out of bounds", @@ -1185,8 +1079,7 @@ verify_equirect1_layer(struct xrt_compositor *xc, "XrCompositionLayerEquirectKHR not supported", layer_index); #else - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, equirect->subImage.swapchain); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, equirect->subImage.swapchain); if (sc == NULL) { return oxr_error(log, XR_ERROR_LAYER_INVALID, @@ -1200,8 +1093,7 @@ verify_equirect1_layer(struct xrt_compositor *xc, return ret; } - if (!math_quat_validate( - (struct xrt_quat *)&equirect->pose.orientation)) { + if (!math_quat_validate((struct xrt_quat *)&equirect->pose.orientation)) { const XrQuaternionf *q = &equirect->pose.orientation; return oxr_error(log, XR_ERROR_POSE_INVALID, "(frameEndInfo->layers[%u]->pose.orientation " @@ -1222,9 +1114,7 @@ verify_equirect1_layer(struct xrt_compositor *xc, "(frameEndInfo->layers[%u]->subImage." "imageArrayIndex == %u) Invalid swapchain " "array index for equirect layer (%u).", - layer_index, - equirect->subImage.imageArrayIndex, - sc->num_array_layers); + layer_index, equirect->subImage.imageArrayIndex, sc->num_array_layers); } if (!sc->released.yes) { @@ -1235,32 +1125,27 @@ verify_equirect1_layer(struct xrt_compositor *xc, } if (sc->released.index >= (int)sc->swapchain->num_images) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "(frameEndInfo->layers[%u]->subImage.swapchain) internal " - "image index out of bounds", - layer_index); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "(frameEndInfo->layers[%u]->subImage.swapchain) internal " + "image index out of bounds", + layer_index); } if (is_rect_neg(&equirect->subImage.imageRect)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->subImage.imageRect.offset == " - "{%i, %i}) has negative component(s)", - layer_index, equirect->subImage.imageRect.offset.x, - equirect->subImage.imageRect.offset.y); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->subImage.imageRect.offset == " + "{%i, %i}) has negative component(s)", + layer_index, equirect->subImage.imageRect.offset.x, + equirect->subImage.imageRect.offset.y); } if (is_rect_out_of_bounds(&equirect->subImage.imageRect, sc)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->subImage.imageRect == {{%i, " - "%i}, {%u, %u}}) imageRect out of image bounds (%u, %u)", - layer_index, equirect->subImage.imageRect.offset.x, - equirect->subImage.imageRect.offset.y, - equirect->subImage.imageRect.extent.width, - equirect->subImage.imageRect.extent.height, sc->width, - sc->height); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->subImage.imageRect == {{%i, " + "%i}, {%u, %u}}) imageRect out of image bounds (%u, %u)", + layer_index, equirect->subImage.imageRect.offset.x, + equirect->subImage.imageRect.offset.y, equirect->subImage.imageRect.extent.width, + equirect->subImage.imageRect.extent.height, sc->width, sc->height); } if (equirect->radius < .0f) { @@ -1288,8 +1173,7 @@ verify_equirect2_layer(struct xrt_compositor *xc, "XrCompositionLayerEquirect2KHR not supported", layer_index); #else - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, equirect->subImage.swapchain); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, equirect->subImage.swapchain); if (sc == NULL) { return oxr_error(log, XR_ERROR_LAYER_INVALID, @@ -1303,8 +1187,7 @@ verify_equirect2_layer(struct xrt_compositor *xc, return ret; } - if (!math_quat_validate( - (struct xrt_quat *)&equirect->pose.orientation)) { + if (!math_quat_validate((struct xrt_quat *)&equirect->pose.orientation)) { const XrQuaternionf *q = &equirect->pose.orientation; return oxr_error(log, XR_ERROR_POSE_INVALID, "(frameEndInfo->layers[%u]->pose.orientation " @@ -1325,9 +1208,7 @@ verify_equirect2_layer(struct xrt_compositor *xc, "(frameEndInfo->layers[%u]->subImage." "imageArrayIndex == %u) Invalid swapchain " "array index for equirect layer (%u).", - layer_index, - equirect->subImage.imageArrayIndex, - sc->num_array_layers); + layer_index, equirect->subImage.imageArrayIndex, sc->num_array_layers); } if (!sc->released.yes) { @@ -1338,40 +1219,34 @@ verify_equirect2_layer(struct xrt_compositor *xc, } if (sc->released.index >= (int)sc->swapchain->num_images) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "(frameEndInfo->layers[%u]->subImage.swapchain) internal " - "image index out of bounds", - layer_index); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "(frameEndInfo->layers[%u]->subImage.swapchain) internal " + "image index out of bounds", + layer_index); } if (is_rect_neg(&equirect->subImage.imageRect)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->subImage.imageRect.offset == " - "{%i, %i}) has negative component(s)", - layer_index, equirect->subImage.imageRect.offset.x, - equirect->subImage.imageRect.offset.y); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->subImage.imageRect.offset == " + "{%i, %i}) has negative component(s)", + layer_index, equirect->subImage.imageRect.offset.x, + equirect->subImage.imageRect.offset.y); } if (is_rect_out_of_bounds(&equirect->subImage.imageRect, sc)) { - return oxr_error( - log, XR_ERROR_SWAPCHAIN_RECT_INVALID, - "(frameEndInfo->layers[%u]->subImage.imageRect == {{%i, " - "%i}, {%u, %u}}) imageRect out of image bounds (%u, %u)", - layer_index, equirect->subImage.imageRect.offset.x, - equirect->subImage.imageRect.offset.y, - equirect->subImage.imageRect.extent.width, - equirect->subImage.imageRect.extent.height, sc->width, - sc->height); + return oxr_error(log, XR_ERROR_SWAPCHAIN_RECT_INVALID, + "(frameEndInfo->layers[%u]->subImage.imageRect == {{%i, " + "%i}, {%u, %u}}) imageRect out of image bounds (%u, %u)", + layer_index, equirect->subImage.imageRect.offset.x, + equirect->subImage.imageRect.offset.y, equirect->subImage.imageRect.extent.width, + equirect->subImage.imageRect.extent.height, sc->width, sc->height); } if (equirect->centralHorizontalAngle < .0f) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "(frameEndInfo->layers[%u]->centralHorizontalAngle == %f) " - "centralHorizontalAngle out of bounds", - layer_index, equirect->centralHorizontalAngle); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "(frameEndInfo->layers[%u]->centralHorizontalAngle == %f) " + "centralHorizontalAngle out of bounds", + layer_index, equirect->centralHorizontalAngle); } /* @@ -1447,8 +1322,7 @@ handle_space(struct oxr_logger *log, if (!initial_head_relation_valid(sess)) { return false; } - math_pose_transform(&sess->initial_head_relation.pose, - &pose, &pose); + math_pose_transform(&sess->initial_head_relation.pose, &pose, &pose); } } else { @@ -1456,8 +1330,7 @@ handle_space(struct oxr_logger *log, struct oxr_action_input *input = NULL; - oxr_action_get_pose_input(log, sess, spc->act_key, - &spc->sub_paths, &input); + oxr_action_get_pose_input(log, sess, spc->act_key, &spc->sub_paths, &input); // If the input isn't active. if (input == NULL) { @@ -1468,8 +1341,7 @@ handle_space(struct oxr_logger *log, struct xrt_space_relation out_relation; - oxr_xdev_get_space_relation(log, sess->sys->inst, input->xdev, - input->input->name, timestamp, + oxr_xdev_get_space_relation(log, sess->sys->inst, input->xdev, input->input->name, timestamp, &out_relation); struct xrt_pose device_pose = out_relation.pose; @@ -1498,19 +1370,15 @@ submit_quad_layer(struct oxr_session *sess, struct xrt_pose *inv_offset, uint64_t timestamp) { - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, quad->subImage.swapchain); - struct oxr_space *spc = - XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, quad->space); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, quad->subImage.swapchain); + struct oxr_space *spc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, quad->space); - enum xrt_layer_composition_flags flags = - convert_layer_flags(quad->layerFlags); + enum xrt_layer_composition_flags flags = convert_layer_flags(quad->layerFlags); struct xrt_pose *pose_ptr = (struct xrt_pose *)&quad->pose; struct xrt_pose pose; - if (!handle_space(log, sess, spc, pose_ptr, inv_offset, timestamp, - &pose)) { + if (!handle_space(log, sess, spc, pose_ptr, inv_offset, timestamp, &pose)) { return XR_SUCCESS; } @@ -1548,20 +1416,17 @@ submit_projection_layer(struct xrt_compositor *xc, struct xrt_pose *inv_offset, uint64_t timestamp) { - struct oxr_space *spc = - XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, proj->space); + struct oxr_space *spc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, proj->space); struct oxr_swapchain *d_scs[2] = {NULL, NULL}; struct oxr_swapchain *scs[2]; struct xrt_pose *pose_ptr[2]; struct xrt_pose pose[2]; - enum xrt_layer_composition_flags flags = - convert_layer_flags(proj->layerFlags); + enum xrt_layer_composition_flags flags = convert_layer_flags(proj->layerFlags); uint32_t num_chains = ARRAY_SIZE(scs); for (uint32_t i = 0; i < num_chains; i++) { - scs[i] = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, proj->views[i].subImage.swapchain); + scs[i] = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, proj->views[i].subImage.swapchain); pose_ptr[i] = (struct xrt_pose *)&proj->views[i].pose; pose[i] = *pose_ptr[i]; } @@ -1583,11 +1448,9 @@ submit_projection_layer(struct xrt_compositor *xc, math_pose_transform(inv_offset, &pose[1], &pose[1]); } - struct xrt_rect *l_rect = - (struct xrt_rect *)&proj->views[0].subImage.imageRect; + struct xrt_rect *l_rect = (struct xrt_rect *)&proj->views[0].subImage.imageRect; struct xrt_fov *l_fov = (struct xrt_fov *)&proj->views[0].fov; - struct xrt_rect *r_rect = - (struct xrt_rect *)&proj->views[1].subImage.imageRect; + struct xrt_rect *r_rect = (struct xrt_rect *)&proj->views[1].subImage.imageRect; struct xrt_fov *r_fov = (struct xrt_fov *)&proj->views[1].fov; struct xrt_layer_data data; @@ -1613,22 +1476,18 @@ submit_projection_layer(struct xrt_compositor *xc, #ifdef XRT_FEATURE_OPENXR_LAYER_DEPTH const XrCompositionLayerDepthInfoKHR *d_l = OXR_GET_INPUT_FROM_CHAIN( - &proj->views[0], XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, - XrCompositionLayerDepthInfoKHR); + &proj->views[0], XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, XrCompositionLayerDepthInfoKHR); if (d_l) { data.stereo_depth.l_d.far_z = d_l->farZ; data.stereo_depth.l_d.near_z = d_l->nearZ; data.stereo_depth.l_d.max_depth = d_l->maxDepth; data.stereo_depth.l_d.min_depth = d_l->minDepth; - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, d_l->subImage.swapchain); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, d_l->subImage.swapchain); - struct xrt_rect *d_l_rect = - (struct xrt_rect *)&d_l->subImage.imageRect; + struct xrt_rect *d_l_rect = (struct xrt_rect *)&d_l->subImage.imageRect; data.stereo_depth.l_d.sub.image_index = sc->released.index; - data.stereo_depth.l_d.sub.array_index = - d_l->subImage.imageArrayIndex; + data.stereo_depth.l_d.sub.array_index = d_l->subImage.imageArrayIndex; data.stereo_depth.l_d.sub.rect = *d_l_rect; // Need to pass this in. @@ -1636,8 +1495,7 @@ submit_projection_layer(struct xrt_compositor *xc, } const XrCompositionLayerDepthInfoKHR *d_r = OXR_GET_INPUT_FROM_CHAIN( - &proj->views[1], XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, - XrCompositionLayerDepthInfoKHR); + &proj->views[1], XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, XrCompositionLayerDepthInfoKHR); if (d_r) { data.stereo_depth.r_d.far_z = d_r->farZ; @@ -1645,14 +1503,11 @@ submit_projection_layer(struct xrt_compositor *xc, data.stereo_depth.r_d.max_depth = d_r->maxDepth; data.stereo_depth.r_d.min_depth = d_r->minDepth; - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, d_r->subImage.swapchain); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, d_r->subImage.swapchain); - struct xrt_rect *d_l_rect = - (struct xrt_rect *)&d_r->subImage.imageRect; + struct xrt_rect *d_l_rect = (struct xrt_rect *)&d_r->subImage.imageRect; data.stereo_depth.r_d.sub.image_index = sc->released.index; - data.stereo_depth.r_d.sub.array_index = - d_r->subImage.imageArrayIndex; + data.stereo_depth.r_d.sub.array_index = d_r->subImage.imageArrayIndex; data.stereo_depth.r_d.sub.rect = *d_l_rect; // Need to pass this in. @@ -1663,22 +1518,20 @@ submit_projection_layer(struct xrt_compositor *xc, if (d_scs[0] != NULL && d_scs[1] != NULL) { #ifdef XRT_FEATURE_OPENXR_LAYER_DEPTH data.type = XRT_LAYER_STEREO_PROJECTION_DEPTH; - CALL_CHK(xrt_comp_layer_stereo_projection_depth( - xc, head, - scs[0]->swapchain, // Left - scs[1]->swapchain, // Right - d_scs[0]->swapchain, // Left - d_scs[1]->swapchain, // Right - &data)); + CALL_CHK(xrt_comp_layer_stereo_projection_depth(xc, head, + scs[0]->swapchain, // Left + scs[1]->swapchain, // Right + d_scs[0]->swapchain, // Left + d_scs[1]->swapchain, // Right + &data)); #else assert(false && "Should not get here"); #endif // XRT_FEATURE_OPENXR_LAYER_DEPTH } else { - CALL_CHK( - xrt_comp_layer_stereo_projection(xc, head, - scs[0]->swapchain, // Left - scs[1]->swapchain, // Right - &data)); + CALL_CHK(xrt_comp_layer_stereo_projection(xc, head, + scs[0]->swapchain, // Left + scs[1]->swapchain, // Right + &data)); } return XR_SUCCESS; @@ -1705,21 +1558,16 @@ submit_cylinder_layer(struct oxr_session *sess, struct xrt_pose *inv_offset, uint64_t timestamp) { - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, cylinder->subImage.swapchain); - struct oxr_space *spc = - XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, cylinder->space); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, cylinder->subImage.swapchain); + struct oxr_space *spc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, cylinder->space); - enum xrt_layer_composition_flags flags = - convert_layer_flags(cylinder->layerFlags); - enum xrt_layer_eye_visibility visibility = - convert_eye_visibility(cylinder->eyeVisibility); + enum xrt_layer_composition_flags flags = convert_layer_flags(cylinder->layerFlags); + enum xrt_layer_eye_visibility visibility = convert_eye_visibility(cylinder->eyeVisibility); struct xrt_pose *pose_ptr = (struct xrt_pose *)&cylinder->pose; struct xrt_pose pose; - if (!handle_space(log, sess, spc, pose_ptr, inv_offset, timestamp, - &pose)) { + if (!handle_space(log, sess, spc, pose_ptr, inv_offset, timestamp, &pose)) { return XR_SUCCESS; } @@ -1734,8 +1582,7 @@ submit_cylinder_layer(struct oxr_session *sess, data.timestamp = timestamp; data.flags = flags; - struct xrt_rect *rect = - (struct xrt_rect *)&cylinder->subImage.imageRect; + struct xrt_rect *rect = (struct xrt_rect *)&cylinder->subImage.imageRect; data.cylinder.visibility = visibility; data.cylinder.sub.image_index = sc->released.index; @@ -1760,19 +1607,15 @@ submit_equirect1_layer(struct oxr_session *sess, struct xrt_pose *inv_offset, uint64_t timestamp) { - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, equirect->subImage.swapchain); - struct oxr_space *spc = - XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, equirect->space); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, equirect->subImage.swapchain); + struct oxr_space *spc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, equirect->space); - enum xrt_layer_composition_flags flags = - convert_layer_flags(equirect->layerFlags); + enum xrt_layer_composition_flags flags = convert_layer_flags(equirect->layerFlags); struct xrt_pose *pose_ptr = (struct xrt_pose *)&equirect->pose; struct xrt_pose pose; - if (!handle_space(log, sess, spc, pose_ptr, inv_offset, timestamp, - &pose)) { + if (!handle_space(log, sess, spc, pose_ptr, inv_offset, timestamp, &pose)) { return XR_SUCCESS; } @@ -1787,11 +1630,9 @@ submit_equirect1_layer(struct oxr_session *sess, data.timestamp = timestamp; data.flags = flags; - struct xrt_rect *rect = - (struct xrt_rect *)&equirect->subImage.imageRect; + struct xrt_rect *rect = (struct xrt_rect *)&equirect->subImage.imageRect; - data.equirect1.visibility = - convert_eye_visibility(equirect->eyeVisibility); + data.equirect1.visibility = convert_eye_visibility(equirect->eyeVisibility); data.equirect1.sub.image_index = sc->released.index; data.equirect1.sub.array_index = equirect->subImage.imageArrayIndex; data.equirect1.sub.rect = *rect; @@ -1814,8 +1655,7 @@ static void do_synchronize_state_change(struct oxr_logger *log, struct oxr_session *sess) { if (!sess->has_ended_once && sess->state < XR_SESSION_STATE_VISIBLE) { - oxr_session_change_state(log, sess, - XR_SESSION_STATE_SYNCHRONIZED); + oxr_session_change_state(log, sess, XR_SESSION_STATE_SYNCHRONIZED); sess->has_ended_once = true; } } @@ -1829,19 +1669,15 @@ submit_equirect2_layer(struct oxr_session *sess, struct xrt_pose *inv_offset, uint64_t timestamp) { - struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_swapchain *, equirect->subImage.swapchain); - struct oxr_space *spc = - XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, equirect->space); + struct oxr_swapchain *sc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_swapchain *, equirect->subImage.swapchain); + struct oxr_space *spc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, equirect->space); - enum xrt_layer_composition_flags flags = - convert_layer_flags(equirect->layerFlags); + enum xrt_layer_composition_flags flags = convert_layer_flags(equirect->layerFlags); struct xrt_pose *pose_ptr = (struct xrt_pose *)&equirect->pose; struct xrt_pose pose; - if (!handle_space(log, sess, spc, pose_ptr, inv_offset, timestamp, - &pose)) { + if (!handle_space(log, sess, spc, pose_ptr, inv_offset, timestamp, &pose)) { return XR_SUCCESS; } @@ -1856,19 +1692,16 @@ submit_equirect2_layer(struct oxr_session *sess, data.timestamp = timestamp; data.flags = flags; - struct xrt_rect *rect = - (struct xrt_rect *)&equirect->subImage.imageRect; + struct xrt_rect *rect = (struct xrt_rect *)&equirect->subImage.imageRect; - data.equirect2.visibility = - convert_eye_visibility(equirect->eyeVisibility); + data.equirect2.visibility = convert_eye_visibility(equirect->eyeVisibility); data.equirect2.sub.image_index = sc->released.index; data.equirect2.sub.array_index = equirect->subImage.imageArrayIndex; data.equirect2.sub.rect = *rect; data.equirect2.pose = pose; data.equirect2.radius = equirect->radius; - data.equirect2.central_horizontal_angle = - equirect->centralHorizontalAngle; + data.equirect2.central_horizontal_angle = equirect->centralHorizontalAngle; data.equirect2.upper_vertical_angle = equirect->upperVerticalAngle; data.equirect2.lower_vertical_angle = equirect->lowerVerticalAngle; @@ -1878,36 +1711,29 @@ submit_equirect2_layer(struct oxr_session *sess, } XrResult -oxr_session_frame_end(struct oxr_logger *log, - struct oxr_session *sess, - const XrFrameEndInfo *frameEndInfo) +oxr_session_frame_end(struct oxr_logger *log, struct oxr_session *sess, const XrFrameEndInfo *frameEndInfo) { /* * Session state and call order. */ if (!is_running(sess)) { - return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, - "Session is not running"); + return oxr_error(log, XR_ERROR_SESSION_NOT_RUNNING, "Session is not running"); } if (!sess->frame_started) { - return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, - "Frame not begun with xrBeginFrame"); + return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "Frame not begun with xrBeginFrame"); } if (frameEndInfo->displayTime <= 0) { - return oxr_error( - log, XR_ERROR_TIME_INVALID, - "(frameEndInfo->displayTime == %" PRIi64 - ") zero or a negative value is not a valid XrTime", - frameEndInfo->displayTime); + return oxr_error(log, XR_ERROR_TIME_INVALID, + "(frameEndInfo->displayTime == %" PRIi64 + ") zero or a negative value is not a valid XrTime", + frameEndInfo->displayTime); } - int64_t timestamp = time_state_ts_to_monotonic_ns( - sess->sys->inst->timekeeping, frameEndInfo->displayTime); + int64_t timestamp = time_state_ts_to_monotonic_ns(sess->sys->inst->timekeeping, frameEndInfo->displayTime); if (sess->frame_timing_spew) { - oxr_log(log, "End frame at %8.3fms with display time %8.3fms", - ts_ms(sess), ns_to_ms(timestamp)); + oxr_log(log, "End frame at %8.3fms with display time %8.3fms", ts_ms(sess), ns_to_ms(timestamp)); } struct xrt_compositor *xc = sess->compositor; @@ -1934,8 +1760,7 @@ oxr_session_frame_end(struct oxr_logger *log, * even with 0 layers. */ - enum xrt_blend_mode blend_mode = - oxr_blend_mode_to_xrt(frameEndInfo->environmentBlendMode); + enum xrt_blend_mode blend_mode = oxr_blend_mode_to_xrt(frameEndInfo->environmentBlendMode); if (blend_mode == 0) { return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, @@ -1947,8 +1772,7 @@ oxr_session_frame_end(struct oxr_logger *log, struct xrt_device *xdev = GET_XDEV_BY_ROLE(sess->sys, head); if ((blend_mode & xdev->hmd->blend_mode) == 0) { //! @todo Make integer print to string. - return oxr_error(log, - XR_ERROR_ENVIRONMENT_BLEND_MODE_UNSUPPORTED, + return oxr_error(log, XR_ERROR_ENVIRONMENT_BLEND_MODE_UNSUPPORTED, "(frameEndInfo->environmentBlendMode == %u) " "is not supported", frameEndInfo->environmentBlendMode); @@ -1978,13 +1802,11 @@ oxr_session_frame_end(struct oxr_logger *log, */ if (frameEndInfo->layers == NULL) { - return oxr_error(log, XR_ERROR_LAYER_INVALID, - "(frameEndInfo->layers == NULL)"); + return oxr_error(log, XR_ERROR_LAYER_INVALID, "(frameEndInfo->layers == NULL)"); } for (uint32_t i = 0; i < frameEndInfo->layerCount; i++) { - const XrCompositionLayerBaseHeader *layer = - frameEndInfo->layers[i]; + const XrCompositionLayerBaseHeader *layer = frameEndInfo->layers[i]; if (layer == NULL) { return oxr_error(log, XR_ERROR_LAYER_INVALID, "(frameEndInfo->layers[%u] == NULL) " @@ -1996,34 +1818,28 @@ oxr_session_frame_end(struct oxr_logger *log, switch (layer->type) { case XR_TYPE_COMPOSITION_LAYER_PROJECTION: - res = verify_projection_layer( - xc, log, i, (XrCompositionLayerProjection *)layer, - xdev, frameEndInfo->displayTime); + res = verify_projection_layer(xc, log, i, (XrCompositionLayerProjection *)layer, xdev, + frameEndInfo->displayTime); break; case XR_TYPE_COMPOSITION_LAYER_QUAD: - res = verify_quad_layer( - xc, log, i, (XrCompositionLayerQuad *)layer, xdev, - frameEndInfo->displayTime); + res = verify_quad_layer(xc, log, i, (XrCompositionLayerQuad *)layer, xdev, + frameEndInfo->displayTime); break; case XR_TYPE_COMPOSITION_LAYER_CUBE_KHR: - res = verify_cube_layer( - xc, log, i, (XrCompositionLayerCubeKHR *)layer, - xdev, frameEndInfo->displayTime); + res = verify_cube_layer(xc, log, i, (XrCompositionLayerCubeKHR *)layer, xdev, + frameEndInfo->displayTime); break; case XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR: - res = verify_cylinder_layer( - xc, log, i, (XrCompositionLayerCylinderKHR *)layer, - xdev, frameEndInfo->displayTime); + res = verify_cylinder_layer(xc, log, i, (XrCompositionLayerCylinderKHR *)layer, xdev, + frameEndInfo->displayTime); break; case XR_TYPE_COMPOSITION_LAYER_EQUIRECT_KHR: - res = verify_equirect1_layer( - xc, log, i, (XrCompositionLayerEquirectKHR *)layer, - xdev, frameEndInfo->displayTime); + res = verify_equirect1_layer(xc, log, i, (XrCompositionLayerEquirectKHR *)layer, xdev, + frameEndInfo->displayTime); break; case XR_TYPE_COMPOSITION_LAYER_EQUIRECT2_KHR: - res = verify_equirect2_layer( - xc, log, i, (XrCompositionLayerEquirect2KHR *)layer, - xdev, frameEndInfo->displayTime); + res = verify_equirect2_layer(xc, log, i, (XrCompositionLayerEquirect2KHR *)layer, xdev, + frameEndInfo->displayTime); break; default: return oxr_error(log, XR_ERROR_LAYER_INVALID, @@ -2051,53 +1867,41 @@ oxr_session_frame_end(struct oxr_logger *log, CALL_CHK(xrt_comp_layer_begin(xc, sess->frame_id.begun, blend_mode)); for (uint32_t i = 0; i < frameEndInfo->layerCount; i++) { - const XrCompositionLayerBaseHeader *layer = - frameEndInfo->layers[i]; + const XrCompositionLayerBaseHeader *layer = frameEndInfo->layers[i]; assert(layer != NULL); - int64_t timestamp = time_state_ts_to_monotonic_ns( - sess->sys->inst->timekeeping, frameEndInfo->displayTime); + int64_t timestamp = + time_state_ts_to_monotonic_ns(sess->sys->inst->timekeeping, frameEndInfo->displayTime); switch (layer->type) { case XR_TYPE_COMPOSITION_LAYER_PROJECTION: - submit_projection_layer( - xc, log, (XrCompositionLayerProjection *)layer, - xdev, &inv_offset, timestamp); + submit_projection_layer(xc, log, (XrCompositionLayerProjection *)layer, xdev, &inv_offset, + timestamp); break; case XR_TYPE_COMPOSITION_LAYER_QUAD: - submit_quad_layer(sess, xc, log, - (XrCompositionLayerQuad *)layer, xdev, - &inv_offset, timestamp); + submit_quad_layer(sess, xc, log, (XrCompositionLayerQuad *)layer, xdev, &inv_offset, timestamp); break; case XR_TYPE_COMPOSITION_LAYER_CUBE_KHR: - submit_cube_layer(sess, xc, log, - (XrCompositionLayerCubeKHR *)layer, - xdev, &inv_offset, timestamp); + submit_cube_layer(sess, xc, log, (XrCompositionLayerCubeKHR *)layer, xdev, &inv_offset, + timestamp); break; case XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR: - submit_cylinder_layer( - sess, xc, log, - (XrCompositionLayerCylinderKHR *)layer, xdev, - &inv_offset, timestamp); + submit_cylinder_layer(sess, xc, log, (XrCompositionLayerCylinderKHR *)layer, xdev, &inv_offset, + timestamp); break; case XR_TYPE_COMPOSITION_LAYER_EQUIRECT_KHR: - submit_equirect1_layer( - sess, xc, log, - (XrCompositionLayerEquirectKHR *)layer, xdev, - &inv_offset, timestamp); + submit_equirect1_layer(sess, xc, log, (XrCompositionLayerEquirectKHR *)layer, xdev, &inv_offset, + timestamp); break; case XR_TYPE_COMPOSITION_LAYER_EQUIRECT2_KHR: - submit_equirect2_layer( - sess, xc, log, - (XrCompositionLayerEquirect2KHR *)layer, xdev, - &inv_offset, timestamp); + submit_equirect2_layer(sess, xc, log, (XrCompositionLayerEquirect2KHR *)layer, xdev, + &inv_offset, timestamp); break; default: assert(false && "invalid layer type"); } } - CALL_CHK(xrt_comp_layer_commit(xc, sess->frame_id.begun, - XRT_GRAPHICS_SYNC_HANDLE_INVALID)); + CALL_CHK(xrt_comp_layer_commit(xc, sess->frame_id.begun, XRT_GRAPHICS_SYNC_HANDLE_INVALID)); sess->frame_id.begun = -1; sess->frame_started = false; @@ -2117,18 +1921,15 @@ oxr_session_destroy(struct oxr_logger *log, struct oxr_handle_base *hb) XrResult ret = oxr_event_remove_session_events(log, sess); for (size_t i = 0; i < sess->num_action_set_attachments; ++i) { - oxr_action_set_attachment_teardown( - &sess->act_set_attachments[i]); + oxr_action_set_attachment_teardown(&sess->act_set_attachments[i]); } free(sess->act_set_attachments); sess->act_set_attachments = NULL; sess->num_action_set_attachments = 0; // If we tore everything down correctly, these are empty now. - assert(sess->act_sets_attachments_by_key == NULL || - u_hashmap_int_empty(sess->act_sets_attachments_by_key)); - assert(sess->act_attachments_by_key == NULL || - u_hashmap_int_empty(sess->act_attachments_by_key)); + assert(sess->act_sets_attachments_by_key == NULL || u_hashmap_int_empty(sess->act_sets_attachments_by_key)); + assert(sess->act_attachments_by_key == NULL || u_hashmap_int_empty(sess->act_attachments_by_key)); u_hashmap_int_destroy(&sess->act_sets_attachments_by_key); u_hashmap_int_destroy(&sess->act_attachments_by_key); @@ -2143,12 +1944,11 @@ oxr_session_destroy(struct oxr_logger *log, struct oxr_handle_base *hb) return ret; } -#define OXR_SESSION_ALLOCATE(LOG, SYS, OUT) \ - do { \ - OXR_ALLOCATE_HANDLE_OR_RETURN(LOG, OUT, OXR_XR_DEBUG_SESSION, \ - oxr_session_destroy, \ - &(SYS)->inst->handle); \ - (OUT)->sys = (SYS); \ +#define OXR_SESSION_ALLOCATE(LOG, SYS, OUT) \ + do { \ + OXR_ALLOCATE_HANDLE_OR_RETURN(LOG, OUT, OXR_XR_DEBUG_SESSION, oxr_session_destroy, \ + &(SYS)->inst->handle); \ + (OUT)->sys = (SYS); \ } while (0) /* Just the allocation and populate part, so we can use early-returns to @@ -2160,54 +1960,44 @@ oxr_session_create_impl(struct oxr_logger *log, struct oxr_session **out_session) { #if defined(XR_USE_PLATFORM_XLIB) && defined(XR_USE_GRAPHICS_API_OPENGL) - XrGraphicsBindingOpenGLXlibKHR const *opengl_xlib = - OXR_GET_INPUT_FROM_CHAIN(createInfo, - XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR, - XrGraphicsBindingOpenGLXlibKHR); + XrGraphicsBindingOpenGLXlibKHR const *opengl_xlib = OXR_GET_INPUT_FROM_CHAIN( + createInfo, XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR, XrGraphicsBindingOpenGLXlibKHR); if (opengl_xlib != NULL) { if (!sys->gotten_requirements) { - return oxr_error( - log, XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING, - "Has not called " - "xrGetOpenGL[ES]GraphicsRequirementsKHR"); + return oxr_error(log, XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING, + "Has not called " + "xrGetOpenGL[ES]GraphicsRequirementsKHR"); } OXR_SESSION_ALLOCATE(log, sys, *out_session); - return oxr_session_populate_gl_xlib(log, sys, opengl_xlib, - *out_session); + return oxr_session_populate_gl_xlib(log, sys, opengl_xlib, *out_session); } #endif #if defined(XR_USE_PLATFORM_ANDROID) && defined(XR_USE_GRAPHICS_API_OPENGL_ES) - XrGraphicsBindingOpenGLESAndroidKHR const *opengles_android = - OXR_GET_INPUT_FROM_CHAIN( - createInfo, XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR, - XrGraphicsBindingOpenGLESAndroidKHR); + XrGraphicsBindingOpenGLESAndroidKHR const *opengles_android = OXR_GET_INPUT_FROM_CHAIN( + createInfo, XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR, XrGraphicsBindingOpenGLESAndroidKHR); if (opengles_android != NULL) { if (!sys->gotten_requirements) { - return oxr_error( - log, XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING, - "Has not called " - "xrGetOpenGLESGraphicsRequirementsKHR"); + return oxr_error(log, XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING, + "Has not called " + "xrGetOpenGLESGraphicsRequirementsKHR"); } OXR_SESSION_ALLOCATE(log, sys, *out_session); - return oxr_session_populate_gles_android( - log, sys, opengles_android, *out_session); + return oxr_session_populate_gles_android(log, sys, opengles_android, *out_session); } #endif #ifdef XR_USE_GRAPHICS_API_VULKAN - XrGraphicsBindingVulkanKHR const *vulkan = OXR_GET_INPUT_FROM_CHAIN( - createInfo, XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR, - XrGraphicsBindingVulkanKHR); + XrGraphicsBindingVulkanKHR const *vulkan = + OXR_GET_INPUT_FROM_CHAIN(createInfo, XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR, XrGraphicsBindingVulkanKHR); if (vulkan != NULL) { if (!sys->gotten_requirements) { - return oxr_error( - log, XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING, - "Has not called " - "xrGetVulkanGraphicsRequirementsKHR"); + return oxr_error(log, XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING, + "Has not called " + "xrGetVulkanGraphicsRequirementsKHR"); } OXR_SESSION_ALLOCATE(log, sys, *out_session); @@ -2216,15 +2006,13 @@ oxr_session_create_impl(struct oxr_logger *log, #endif #ifdef XR_USE_PLATFORM_EGL - XrGraphicsBindingEGLMNDX const *egl = OXR_GET_INPUT_FROM_CHAIN( - createInfo, XR_TYPE_GRAPHICS_BINDING_EGL_MNDX, - XrGraphicsBindingEGLMNDX); + XrGraphicsBindingEGLMNDX const *egl = + OXR_GET_INPUT_FROM_CHAIN(createInfo, XR_TYPE_GRAPHICS_BINDING_EGL_MNDX, XrGraphicsBindingEGLMNDX); if (egl != NULL) { if (!sys->gotten_requirements) { - return oxr_error( - log, XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING, - "Has not called " - "xrGetOpenGL[ES]GraphicsRequirementsKHR"); + return oxr_error(log, XR_ERROR_GRAPHICS_REQUIREMENTS_CALL_MISSING, + "Has not called " + "xrGetOpenGL[ES]GraphicsRequirementsKHR"); } OXR_SESSION_ALLOCATE(log, sys, *out_session); @@ -2264,8 +2052,7 @@ oxr_session_create(struct oxr_logger *log, if (ret != XR_SUCCESS) { if (sess != NULL) { /* clean up allocation first */ - XrResult cleanup_result = - oxr_handle_destroy(log, &sess->handle); + XrResult cleanup_result = oxr_handle_destroy(log, &sess->handle); assert(cleanup_result == XR_SUCCESS); (void)cleanup_result; } @@ -2281,10 +2068,8 @@ oxr_session_create(struct oxr_logger *log, struct xrt_compositor *xc = sess->compositor; if (xc != NULL) { struct xrt_session_prepare_info xspi = {0}; - const XrSessionCreateInfoOverlayEXTX *overlay_info = - OXR_GET_INPUT_FROM_CHAIN( - createInfo, XR_TYPE_SESSION_CREATE_INFO_OVERLAY_EXTX, - XrSessionCreateInfoOverlayEXTX); + const XrSessionCreateInfoOverlayEXTX *overlay_info = OXR_GET_INPUT_FROM_CHAIN( + createInfo, XR_TYPE_SESSION_CREATE_INFO_OVERLAY_EXTX, XrSessionCreateInfoOverlayEXTX); if (overlay_info) { xspi.is_overlay = true; xspi.flags = overlay_info->createFlags; @@ -2326,37 +2111,29 @@ oxr_session_hand_joints(struct oxr_logger *log, const XrHandJointsLocateInfoEXT *locateInfo, XrHandJointLocationsEXT *locations) { - struct oxr_space *baseSpc = XRT_CAST_OXR_HANDLE_TO_PTR( - struct oxr_space *, locateInfo->baseSpace); + struct oxr_space *baseSpc = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_space *, locateInfo->baseSpace); struct oxr_session *sess = hand_tracker->sess; - XrHandJointVelocitiesEXT *vel = OXR_GET_OUTPUT_FROM_CHAIN( - locations, XR_TYPE_HAND_JOINT_VELOCITIES_EXT, - XrHandJointVelocitiesEXT); + XrHandJointVelocitiesEXT *vel = + OXR_GET_OUTPUT_FROM_CHAIN(locations, XR_TYPE_HAND_JOINT_VELOCITIES_EXT, XrHandJointVelocitiesEXT); struct xrt_device *xdev = hand_tracker->xdev; enum xrt_input_name name = hand_tracker->input_name; - struct xrt_pose *tracking_origin_offset = - &xdev->tracking_origin->offset; + struct xrt_pose *tracking_origin_offset = &xdev->tracking_origin->offset; XrTime at_time = locateInfo->time; struct xrt_hand_joint_set value; - oxr_xdev_get_hand_tracking_at(log, sess->sys->inst, xdev, name, at_time, - &value); + oxr_xdev_get_hand_tracking_at(log, sess->sys->inst, xdev, name, at_time, &value); for (uint32_t i = 0; i < locations->jointCount; i++) { locations->jointLocations[i].locationFlags = - xrt_to_xr_space_location_flags( - value.values.hand_joint_set_default[i] - .relation.relation_flags); - locations->jointLocations[i].radius = - value.values.hand_joint_set_default[i].radius; + xrt_to_xr_space_location_flags(value.values.hand_joint_set_default[i].relation.relation_flags); + locations->jointLocations[i].radius = value.values.hand_joint_set_default[i].radius; - struct xrt_space_relation r = - value.values.hand_joint_set_default[i].relation; + struct xrt_space_relation r = value.values.hand_joint_set_default[i].relation; struct xrt_space_relation result; struct xrt_space_graph graph = {0}; @@ -2366,43 +2143,35 @@ oxr_session_hand_joints(struct oxr_logger *log, if (baseSpc->type == XR_REFERENCE_SPACE_TYPE_STAGE) { m_space_graph_add_relation(&graph, &value.hand_pose); - m_space_graph_add_pose_if_not_identity( - &graph, tracking_origin_offset); + m_space_graph_add_pose_if_not_identity(&graph, tracking_origin_offset); } else if (baseSpc->type == XR_REFERENCE_SPACE_TYPE_LOCAL) { // for local space, first do stage space and transform // result to local @todo: improve local space m_space_graph_add_relation(&graph, &value.hand_pose); - m_space_graph_add_pose_if_not_identity( - &graph, tracking_origin_offset); + m_space_graph_add_pose_if_not_identity(&graph, tracking_origin_offset); } else if (baseSpc->type == XR_REFERENCE_SPACE_TYPE_VIEW) { /*! @todo: testing, relating to view space unsupported * in other parts of monado */ - struct xrt_device *head_xdev = - GET_XDEV_BY_ROLE(sess->sys, head); + struct xrt_device *head_xdev = GET_XDEV_BY_ROLE(sess->sys, head); struct xrt_space_relation view_relation; - oxr_session_get_view_relation_at(log, sess, at_time, - &view_relation); + oxr_session_get_view_relation_at(log, sess, at_time, &view_relation); m_space_graph_add_relation(&graph, &value.hand_pose); - m_space_graph_add_pose_if_not_identity( - &graph, tracking_origin_offset); + m_space_graph_add_pose_if_not_identity(&graph, tracking_origin_offset); - m_space_graph_add_inverted_relation(&graph, - &view_relation); - m_space_graph_add_inverted_pose_if_not_identity( - &graph, &head_xdev->tracking_origin->offset); + m_space_graph_add_inverted_relation(&graph, &view_relation); + m_space_graph_add_inverted_pose_if_not_identity(&graph, &head_xdev->tracking_origin->offset); } else if (!baseSpc->is_reference) { // action space struct oxr_action_input *input = NULL; - oxr_action_get_pose_input(log, sess, baseSpc->act_key, - &baseSpc->sub_paths, &input); + oxr_action_get_pose_input(log, sess, baseSpc->act_key, &baseSpc->sub_paths, &input); // If the input isn't active. if (input == NULL) { @@ -2412,23 +2181,18 @@ oxr_session_hand_joints(struct oxr_logger *log, struct xrt_space_relation act_space_relation; - oxr_xdev_get_space_relation( - log, sess->sys->inst, input->xdev, - input->input->name, at_time, &act_space_relation); + oxr_xdev_get_space_relation(log, sess->sys->inst, input->xdev, input->input->name, at_time, + &act_space_relation); m_space_graph_add_relation(&graph, &value.hand_pose); - m_space_graph_add_pose_if_not_identity( - &graph, tracking_origin_offset); + m_space_graph_add_pose_if_not_identity(&graph, tracking_origin_offset); - m_space_graph_add_inverted_relation( - &graph, &act_space_relation); - m_space_graph_add_inverted_pose_if_not_identity( - &graph, &input->xdev->tracking_origin->offset); + m_space_graph_add_inverted_relation(&graph, &act_space_relation); + m_space_graph_add_inverted_pose_if_not_identity(&graph, &input->xdev->tracking_origin->offset); } - m_space_graph_add_inverted_pose_if_not_identity(&graph, - &baseSpc->pose); + m_space_graph_add_inverted_pose_if_not_identity(&graph, &baseSpc->pose); m_space_graph_resolve(&graph, &result); if (baseSpc->type == XR_REFERENCE_SPACE_TYPE_LOCAL) { @@ -2438,22 +2202,17 @@ oxr_session_hand_joints(struct oxr_logger *log, } } - xrt_to_xr_pose(&result.pose, - &locations->jointLocations[i].pose); + xrt_to_xr_pose(&result.pose, &locations->jointLocations[i].pose); if (vel) { XrHandJointVelocityEXT *v = &vel->jointVelocities[i]; v->velocityFlags = 0; - if ((result.relation_flags & - XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT)) { - v->velocityFlags |= - XR_SPACE_VELOCITY_LINEAR_VALID_BIT; + if ((result.relation_flags & XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT)) { + v->velocityFlags |= XR_SPACE_VELOCITY_LINEAR_VALID_BIT; } - if ((result.relation_flags & - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT)) { - v->velocityFlags |= - XR_SPACE_VELOCITY_ANGULAR_VALID_BIT; + if ((result.relation_flags & XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT)) { + v->velocityFlags |= XR_SPACE_VELOCITY_ANGULAR_VALID_BIT; } v->linearVelocity.x = result.linear_velocity.x; diff --git a/src/xrt/state_trackers/oxr/oxr_session_egl.c b/src/xrt/state_trackers/oxr/oxr_session_egl.c index 1fe46740c..eee5c7344 100644 --- a/src/xrt/state_trackers/oxr/oxr_session_egl.c +++ b/src/xrt/state_trackers/oxr/oxr_session_egl.c @@ -44,36 +44,27 @@ oxr_session_populate_egl(struct oxr_logger *log, { EGLint egl_client_type = -1; - PFNEGLQUERYCONTEXTPROC eglQueryContext = - (PFNEGLQUERYCONTEXTPROC)next->getProcAddress("eglQueryContext"); + PFNEGLQUERYCONTEXTPROC eglQueryContext = (PFNEGLQUERYCONTEXTPROC)next->getProcAddress("eglQueryContext"); if (!eglQueryContext) { - return oxr_error( - log, XR_ERROR_INITIALIZATION_FAILED, - "Call to getProcAddress(eglQueryContext) failed"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Call to getProcAddress(eglQueryContext) failed"); } - if (!eglQueryContext(next->display, next->context, - EGL_CONTEXT_CLIENT_TYPE, &egl_client_type)) { - return oxr_error( - log, XR_ERROR_INITIALIZATION_FAILED, - "Call to eglQueryContext(EGL_CONTEXT_CLIENT_TYPE) failed"); + if (!eglQueryContext(next->display, next->context, EGL_CONTEXT_CLIENT_TYPE, &egl_client_type)) { + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, + "Call to eglQueryContext(EGL_CONTEXT_CLIENT_TYPE) failed"); } - if (egl_client_type != EGL_OPENGL_API && - egl_client_type != EGL_OPENGL_ES_API) { - return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, - "Unsupported EGL client type: '%i'", + if (egl_client_type != EGL_OPENGL_API && egl_client_type != EGL_OPENGL_ES_API) { + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Unsupported EGL client type: '%i'", egl_client_type); } struct xrt_compositor_native *xcn = sess->sys->xcn; struct xrt_compositor_gl *xcgl = - xrt_gfx_provider_create_gl_egl(xcn, next->display, next->config, - next->context, next->getProcAddress); + xrt_gfx_provider_create_gl_egl(xcn, next->display, next->config, next->context, next->getProcAddress); if (xcgl == NULL) { - return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, - "Failed to create an egl client compositor"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Failed to create an egl client compositor"); } sess->compositor = &xcgl->base; diff --git a/src/xrt/state_trackers/oxr/oxr_session_gl.c b/src/xrt/state_trackers/oxr/oxr_session_gl.c index 3f4b8fcc3..6c6f6f113 100644 --- a/src/xrt/state_trackers/oxr/oxr_session_gl.c +++ b/src/xrt/state_trackers/oxr/oxr_session_gl.c @@ -35,12 +35,10 @@ oxr_session_populate_gl_xlib(struct oxr_logger *log, { struct xrt_compositor_native *xcn = sess->sys->xcn; struct xrt_compositor_gl *xcgl = xrt_gfx_provider_create_gl_xlib( - xcn, next->xDisplay, next->visualid, next->glxFBConfig, - next->glxDrawable, next->glxContext); + xcn, next->xDisplay, next->visualid, next->glxFBConfig, next->glxDrawable, next->glxContext); if (xcgl == NULL) { - return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, - "Failed to create an xlib client compositor"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Failed to create an xlib client compositor"); } sess->compositor = &xcgl->base; diff --git a/src/xrt/state_trackers/oxr/oxr_session_gles_android.c b/src/xrt/state_trackers/oxr/oxr_session_gles_android.c index 9ece4a3a9..b93714010 100644 --- a/src/xrt/state_trackers/oxr/oxr_session_gles_android.c +++ b/src/xrt/state_trackers/oxr/oxr_session_gles_android.c @@ -31,59 +31,47 @@ #include XrResult -oxr_session_populate_gles_android( - struct oxr_logger *log, - struct oxr_system *sys, - XrGraphicsBindingOpenGLESAndroidKHR const *next, - struct oxr_session *sess) +oxr_session_populate_gles_android(struct oxr_logger *log, + struct oxr_system *sys, + XrGraphicsBindingOpenGLESAndroidKHR const *next, + struct oxr_session *sess) { void *so = dlopen("libEGL.so", RTLD_NOW | RTLD_LOCAL); if (so == NULL) { - return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, - "Could not open libEGL.so"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Could not open libEGL.so"); } - PFNEGLGETPROCADDRESSPROC get_proc_addr = - (PFNEGLGETPROCADDRESSPROC)dlsym(so, "eglGetProcAddress"); + PFNEGLGETPROCADDRESSPROC get_proc_addr = (PFNEGLGETPROCADDRESSPROC)dlsym(so, "eglGetProcAddress"); if (get_proc_addr == NULL) { dlclose(so); - return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, - "Could not get eglGetProcAddress"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Could not get eglGetProcAddress"); } EGLint egl_client_type; - PFNEGLQUERYCONTEXTPROC eglQueryContext = - (PFNEGLQUERYCONTEXTPROC)get_proc_addr("eglQueryContext"); + PFNEGLQUERYCONTEXTPROC eglQueryContext = (PFNEGLQUERYCONTEXTPROC)get_proc_addr("eglQueryContext"); if (!eglQueryContext) { dlclose(so); - return oxr_error( - log, XR_ERROR_INITIALIZATION_FAILED, - "Call to getProcAddress(eglQueryContext) failed"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Call to getProcAddress(eglQueryContext) failed"); } - if (!eglQueryContext(next->display, next->context, - EGL_CONTEXT_CLIENT_TYPE, &egl_client_type)) { + if (!eglQueryContext(next->display, next->context, EGL_CONTEXT_CLIENT_TYPE, &egl_client_type)) { dlclose(so); - return oxr_error( - log, XR_ERROR_INITIALIZATION_FAILED, - "Call to eglQueryContext(EGL_CONTEXT_CLIENT_TYPE) failed"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, + "Call to eglQueryContext(EGL_CONTEXT_CLIENT_TYPE) failed"); } - if (egl_client_type != EGL_OPENGL_API && - egl_client_type != EGL_OPENGL_ES_API) { + if (egl_client_type != EGL_OPENGL_API && egl_client_type != EGL_OPENGL_ES_API) { dlclose(so); - return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, - "Unsupported EGL client type"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Unsupported EGL client type"); } struct xrt_compositor_native *xcn = sess->sys->xcn; - struct xrt_compositor_gl *xcgl = xrt_gfx_provider_create_gl_egl( - xcn, next->display, next->config, next->context, get_proc_addr); + struct xrt_compositor_gl *xcgl = + xrt_gfx_provider_create_gl_egl(xcn, next->display, next->config, next->context, get_proc_addr); if (xcgl == NULL) { - return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, - "Failed to create an egl client compositor"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Failed to create an egl client compositor"); } sess->compositor = &xcgl->base; diff --git a/src/xrt/state_trackers/oxr/oxr_session_vk.c b/src/xrt/state_trackers/oxr/oxr_session_vk.c index 3249f765c..8e55a78c4 100644 --- a/src/xrt/state_trackers/oxr/oxr_session_vk.c +++ b/src/xrt/state_trackers/oxr/oxr_session_vk.c @@ -28,13 +28,12 @@ oxr_session_populate_vk(struct oxr_logger *log, struct oxr_session *sess) { struct xrt_compositor_native *xcn = sess->sys->xcn; - struct xrt_compositor_vk *xcvk = xrt_gfx_vk_provider_create( - xcn, next->instance, vkGetInstanceProcAddr, next->physicalDevice, - next->device, next->queueFamilyIndex, next->queueIndex); + struct xrt_compositor_vk *xcvk = + xrt_gfx_vk_provider_create(xcn, next->instance, vkGetInstanceProcAddr, next->physicalDevice, next->device, + next->queueFamilyIndex, next->queueIndex); if (xcvk == NULL) { - return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, - "Failed to create an vk client compositor"); + return oxr_error(log, XR_ERROR_INITIALIZATION_FAILED, "Failed to create an vk client compositor"); } sess->compositor = &xcvk->base; diff --git a/src/xrt/state_trackers/oxr/oxr_space.c b/src/xrt/state_trackers/oxr/oxr_space.c index b276278d7..73bfaf1ed 100644 --- a/src/xrt/state_trackers/oxr/oxr_space.c +++ b/src/xrt/state_trackers/oxr/oxr_space.c @@ -38,8 +38,7 @@ check_reference_space_type(struct oxr_logger *log, XrReferenceSpaceType type) #endif default: return oxr_error(log, XR_ERROR_REFERENCE_SPACE_UNSUPPORTED, - "(createInfo->referenceSpaceType == 0x%08x)", - type); + "(createInfo->referenceSpaceType == 0x%08x)", type); } } @@ -62,11 +61,9 @@ oxr_space_action_create(struct oxr_logger *log, struct oxr_sub_paths sub_paths = {0}; struct oxr_space *spc = NULL; - OXR_ALLOCATE_HANDLE_OR_RETURN(log, spc, OXR_XR_DEBUG_SPACE, - oxr_space_destroy, &sess->handle); + OXR_ALLOCATE_HANDLE_OR_RETURN(log, spc, OXR_XR_DEBUG_SPACE, oxr_space_destroy, &sess->handle); - oxr_classify_sub_action_paths(log, inst, 1, &createInfo->subactionPath, - &sub_paths); + oxr_classify_sub_action_paths(log, inst, 1, &createInfo->subactionPath, &sub_paths); spc->sess = sess; spc->is_reference = false; @@ -92,20 +89,16 @@ oxr_space_reference_create(struct oxr_logger *log, return ret; } - if (!math_pose_validate( - (struct xrt_pose *)&createInfo->poseInReferenceSpace)) { - return oxr_error(log, XR_ERROR_POSE_INVALID, - "(createInfo->poseInReferenceSpace)"); + if (!math_pose_validate((struct xrt_pose *)&createInfo->poseInReferenceSpace)) { + return oxr_error(log, XR_ERROR_POSE_INVALID, "(createInfo->poseInReferenceSpace)"); } struct oxr_space *spc = NULL; - OXR_ALLOCATE_HANDLE_OR_RETURN(log, spc, OXR_XR_DEBUG_SPACE, - oxr_space_destroy, &sess->handle); + OXR_ALLOCATE_HANDLE_OR_RETURN(log, spc, OXR_XR_DEBUG_SPACE, oxr_space_destroy, &sess->handle); spc->sess = sess; spc->is_reference = true; spc->type = createInfo->referenceSpaceType; - memcpy(&spc->pose, &createInfo->poseInReferenceSpace, - sizeof(spc->pose)); + memcpy(&spc->pose, &createInfo->poseInReferenceSpace, sizeof(spc->pose)); *out_space = spc; @@ -129,12 +122,9 @@ get_ref_space_type_short_str(struct oxr_space *spc) } static bool -ensure_initial_head_relation(struct oxr_logger *log, - struct oxr_session *sess, - struct xrt_space_relation *head_relation) +ensure_initial_head_relation(struct oxr_logger *log, struct oxr_session *sess, struct xrt_space_relation *head_relation) { - if ((head_relation->relation_flags & - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT) == 0) { + if ((head_relation->relation_flags & XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT) == 0) { return false; } @@ -145,8 +135,7 @@ ensure_initial_head_relation(struct oxr_logger *log, // https://stackoverflow.com/a/5783030 sess->initial_head_relation.pose.orientation.x = 0; sess->initial_head_relation.pose.orientation.z = 0; - math_quat_normalize( - &sess->initial_head_relation.pose.orientation); + math_quat_normalize(&sess->initial_head_relation.pose.orientation); //! @todo: Handle relation velocities if necessary } @@ -156,8 +145,7 @@ ensure_initial_head_relation(struct oxr_logger *log, bool initial_head_relation_valid(struct oxr_session *sess) { - return sess->initial_head_relation.relation_flags & - XRT_SPACE_RELATION_ORIENTATION_VALID_BIT; + return sess->initial_head_relation.relation_flags & XRT_SPACE_RELATION_ORIENTATION_VALID_BIT; } bool @@ -169,8 +157,7 @@ global_to_local_space(struct oxr_session *sess, struct xrt_space_relation *rel) struct xrt_space_graph graph = {0}; m_space_graph_add_relation(&graph, rel); - m_space_graph_add_inverted_pose_if_not_identity( - &graph, &sess->initial_head_relation.pose); + m_space_graph_add_inverted_pose_if_not_identity(&graph, &sess->initial_head_relation.pose); m_space_graph_resolve(&graph, rel); return true; @@ -197,8 +184,7 @@ oxr_space_ref_relation(struct oxr_logger *log, oxr_session_get_view_relation_at(log, sess, time, out_relation); if (!ensure_initial_head_relation(log, sess, out_relation)) { - out_relation->relation_flags = - XRT_SPACE_RELATION_BITMASK_NONE; + out_relation->relation_flags = XRT_SPACE_RELATION_BITMASK_NONE; return XR_SUCCESS; } @@ -209,19 +195,15 @@ oxr_space_ref_relation(struct oxr_logger *log, } else if (baseSpc == XR_REFERENCE_SPACE_TYPE_VIEW) { } else { - OXR_WARN_ONCE( - log, - "unsupported base space in space_ref_relation"); - out_relation->relation_flags = - XRT_SPACE_RELATION_BITMASK_NONE; + OXR_WARN_ONCE(log, "unsupported base space in space_ref_relation"); + out_relation->relation_flags = XRT_SPACE_RELATION_BITMASK_NONE; return XR_SUCCESS; } } else if (baseSpc == XR_REFERENCE_SPACE_TYPE_VIEW) { oxr_session_get_view_relation_at(log, sess, time, out_relation); if (!ensure_initial_head_relation(log, sess, out_relation)) { - out_relation->relation_flags = - XRT_SPACE_RELATION_BITMASK_NONE; + out_relation->relation_flags = XRT_SPACE_RELATION_BITMASK_NONE; return XR_SUCCESS; } if (space == XR_REFERENCE_SPACE_TYPE_STAGE) { @@ -231,36 +213,26 @@ oxr_space_ref_relation(struct oxr_logger *log, } else if (space == XR_REFERENCE_SPACE_TYPE_VIEW) { } else { - OXR_WARN_ONCE( - log, - "unsupported base space in space_ref_relation"); - out_relation->relation_flags = - XRT_SPACE_RELATION_BITMASK_NONE; + OXR_WARN_ONCE(log, "unsupported base space in space_ref_relation"); + out_relation->relation_flags = XRT_SPACE_RELATION_BITMASK_NONE; return XR_SUCCESS; } math_pose_invert(&out_relation->pose, &out_relation->pose); } else if (space == XR_REFERENCE_SPACE_TYPE_STAGE) { if (baseSpc == XR_REFERENCE_SPACE_TYPE_LOCAL) { - math_pose_invert(&sess->initial_head_relation.pose, - &out_relation->pose); + math_pose_invert(&sess->initial_head_relation.pose, &out_relation->pose); } else { - OXR_WARN_ONCE( - log, - "unsupported base space in space_ref_relation"); - out_relation->relation_flags = - XRT_SPACE_RELATION_BITMASK_NONE; + OXR_WARN_ONCE(log, "unsupported base space in space_ref_relation"); + out_relation->relation_flags = XRT_SPACE_RELATION_BITMASK_NONE; return XR_SUCCESS; } } else if (space == XR_REFERENCE_SPACE_TYPE_LOCAL) { if (baseSpc == XR_REFERENCE_SPACE_TYPE_STAGE) { out_relation->pose = sess->initial_head_relation.pose; } else { - OXR_WARN_ONCE( - log, - "unsupported base space in space_ref_relation"); - out_relation->relation_flags = - XRT_SPACE_RELATION_BITMASK_NONE; + OXR_WARN_ONCE(log, "unsupported base space in space_ref_relation"); + out_relation->relation_flags = XRT_SPACE_RELATION_BITMASK_NONE; return XR_SUCCESS; } } else { @@ -275,8 +247,7 @@ static void remove_angular_and_linear_stuff(struct xrt_space_relation *out_relation) { const enum xrt_space_relation_flags flags = - XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT | - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT; + XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT | XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT; out_relation->relation_flags &= ~flags; out_relation->linear_velocity = (struct xrt_vec3){0, 0, 0}; @@ -315,8 +286,7 @@ oxr_space_action_relation(struct oxr_logger *log, } // Internal error check. - if (act_spc == NULL || act_spc->is_reference || ref_spc == NULL || - !ref_spc->is_reference) { + if (act_spc == NULL || act_spc->is_reference || ref_spc == NULL || !ref_spc->is_reference) { return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "This is bad!"); } @@ -330,8 +300,7 @@ oxr_space_action_relation(struct oxr_logger *log, return XR_SUCCESS; } - oxr_action_get_pose_input(log, sess, act_spc->act_key, - &act_spc->sub_paths, &input); + oxr_action_get_pose_input(log, sess, act_spc->act_key, &act_spc->sub_paths, &input); // If the input isn't active. if (input == NULL) { @@ -339,8 +308,7 @@ oxr_space_action_relation(struct oxr_logger *log, return XR_SUCCESS; } - oxr_xdev_get_space_relation(log, sess->sys->inst, input->xdev, - input->input->name, at_time, out_relation); + oxr_xdev_get_space_relation(log, sess->sys->inst, input->xdev, input->input->name, at_time, out_relation); if (baseSpc->type == XR_REFERENCE_SPACE_TYPE_LOCAL) { global_to_local_space(sess, out_relation); @@ -369,8 +337,7 @@ get_pure_space_relation(struct oxr_logger *log, struct oxr_session *sess = spc->sess; if (spc->is_reference && baseSpc->is_reference) { - return oxr_space_ref_relation( - log, sess, spc->type, baseSpc->type, time, out_relation); + return oxr_space_ref_relation(log, sess, spc->type, baseSpc->type, time, out_relation); } if (!spc->is_reference && !baseSpc->is_reference) { // @todo Deal with action to action by keeping a true_space that @@ -401,8 +368,7 @@ print_pose(struct oxr_session *sess, const char *prefix, struct xrt_pose *pose) struct xrt_vec3 *p = &pose->position; struct xrt_quat *q = &pose->orientation; - U_LOG_D("%s (%f, %f, %f) (%f, %f, %f, %f)", prefix, p->x, p->y, p->z, - q->x, q->y, q->z, q->w); + U_LOG_D("%s (%f, %f, %f) (%f, %f, %f, %f)", prefix, p->x, p->y, p->z, q->x, q->y, q->z, q->w); } static void @@ -453,11 +419,8 @@ xrt_to_xr_space_location_flags(enum xrt_space_relation_flags relation_flags) } XrResult -oxr_space_locate(struct oxr_logger *log, - struct oxr_space *spc, - struct oxr_space *baseSpc, - XrTime time, - XrSpaceLocation *location) +oxr_space_locate( + struct oxr_logger *log, struct oxr_space *spc, struct oxr_space *baseSpc, XrTime time, XrSpaceLocation *location) { if (spc->sess->sys->inst->debug_spaces) { U_LOG_D("%s", __func__); @@ -491,8 +454,7 @@ oxr_space_locate(struct oxr_logger *log, safe_copy.xrt = result.pose; location->pose = safe_copy.oxr; - location->locationFlags = - xrt_to_xr_space_location_flags(result.relation_flags); + location->locationFlags = xrt_to_xr_space_location_flags(result.relation_flags); XrSpaceVelocity *vel = (XrSpaceVelocity *)location->next; if (vel) { @@ -504,10 +466,8 @@ oxr_space_locate(struct oxr_logger *log, vel->angularVelocity.y = result.angular_velocity.y; vel->angularVelocity.z = result.angular_velocity.z; - vel->velocityFlags |= (location->locationFlags & - XR_SPACE_VELOCITY_LINEAR_VALID_BIT); - vel->velocityFlags |= (location->locationFlags & - XR_SPACE_VELOCITY_ANGULAR_VALID_BIT); + vel->velocityFlags |= (location->locationFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT); + vel->velocityFlags |= (location->locationFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT); } #if 0 @@ -519,8 +479,7 @@ oxr_space_locate(struct oxr_logger *log, *(XrVector3f *)&result.angular_acceleration; #endif - print_pose(spc->sess, "\trelation->pose", - (struct xrt_pose *)&location->pose); + print_pose(spc->sess, "\trelation->pose", (struct xrt_pose *)&location->pose); return oxr_session_success_result(spc->sess); } diff --git a/src/xrt/state_trackers/oxr/oxr_subaction.h b/src/xrt/state_trackers/oxr/oxr_subaction.h index 1e2d2fb68..3a027de74 100644 --- a/src/xrt/state_trackers/oxr/oxr_subaction.h +++ b/src/xrt/state_trackers/oxr/oxr_subaction.h @@ -20,10 +20,10 @@ * * @note Keep this synchronized with OXR_ACTION_GET_FILLER! */ -#define OXR_FOR_EACH_VALID_SUBACTION_PATH(_) \ - _(left) \ - _(right) \ - _(head) \ +#define OXR_FOR_EACH_VALID_SUBACTION_PATH(_) \ + _(left) \ + _(right) \ + _(head) \ _(gamepad) @@ -35,8 +35,8 @@ * * @note Keep this synchronized with OXR_ACTION_GET_FILLER! */ -#define OXR_FOR_EACH_SUBACTION_PATH(_) \ - OXR_FOR_EACH_VALID_SUBACTION_PATH(_) \ +#define OXR_FOR_EACH_SUBACTION_PATH(_) \ + OXR_FOR_EACH_VALID_SUBACTION_PATH(_) \ _(user) /*! @@ -52,10 +52,10 @@ * Most of the time you can just use OXR_FOR_EACH_VALID_SUBACTION_PATH() or * OXR_FOR_EACH_SUBACTION_PATH() */ -#define OXR_FOR_EACH_VALID_SUBACTION_PATH_DETAILED(_) \ - _(left, LEFT, "/user/hand/left") \ - _(right, RIGHT, "/user/hand/right") \ - _(head, HEAD, "/user/head") \ +#define OXR_FOR_EACH_VALID_SUBACTION_PATH_DETAILED(_) \ + _(left, LEFT, "/user/hand/left") \ + _(right, RIGHT, "/user/hand/right") \ + _(head, HEAD, "/user/head") \ _(gamepad, GAMEPAD, "/user/gamepad") /*! @@ -68,6 +68,6 @@ * Most of the time you can just use OXR_FOR_EACH_VALID_SUBACTION_PATH() or * OXR_FOR_EACH_SUBACTION_PATH() */ -#define OXR_FOR_EACH_SUBACTION_PATH_DETAILED(_) \ - OXR_FOR_EACH_VALID_SUBACTION_PATH_DETAILED(_) \ +#define OXR_FOR_EACH_SUBACTION_PATH_DETAILED(_) \ + OXR_FOR_EACH_VALID_SUBACTION_PATH_DETAILED(_) \ _(user, USER, "/user") diff --git a/src/xrt/state_trackers/oxr/oxr_swapchain.c b/src/xrt/state_trackers/oxr/oxr_swapchain.c index 45a725efe..c60ab0a79 100644 --- a/src/xrt/state_trackers/oxr/oxr_swapchain.c +++ b/src/xrt/state_trackers/oxr/oxr_swapchain.c @@ -27,31 +27,25 @@ oxr_swapchain_acquire_image(struct oxr_logger *log, { uint32_t index; if (sc->acquired.num >= sc->swapchain->num_images) { - return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, - "All images have been acquired"); + return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "All images have been acquired"); } if (sc->is_static && (sc->released.yes || sc->waited.yes)) { - return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, - "Can only acquire once on a static swapchain"); + return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "Can only acquire once on a static swapchain"); } struct xrt_swapchain *xsc = (struct xrt_swapchain *)sc->swapchain; xrt_result_t res = xsc->acquire_image(xsc, &index); if (res == XRT_ERROR_IPC_FAILURE) { - return oxr_error(log, XR_ERROR_INSTANCE_LOST, - "Call to xsc->acquire_image failed"); + return oxr_error(log, XR_ERROR_INSTANCE_LOST, "Call to xsc->acquire_image failed"); } if (res != XRT_SUCCESS) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Call to xsc->acquire_image failed"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Call to xsc->acquire_image failed"); } if (sc->images[index].state != OXR_IMAGE_STATE_READY) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "Internal acquire call returned non-ready image."); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Internal acquire call returned non-ready image."); } sc->acquired.num++; @@ -71,19 +65,14 @@ oxr_swapchain_acquire_image(struct oxr_logger *log, } static XrResult -oxr_swapchain_wait_image(struct oxr_logger *log, - struct oxr_swapchain *sc, - const XrSwapchainImageWaitInfo *waitInfo) +oxr_swapchain_wait_image(struct oxr_logger *log, struct oxr_swapchain *sc, const XrSwapchainImageWaitInfo *waitInfo) { if (sc->waited.yes) { - return oxr_error( - log, XR_ERROR_CALL_ORDER_INVALID, - "Swapchain has already been waited, call release"); + return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "Swapchain has already been waited, call release"); } if (u_index_fifo_is_empty(&sc->acquired.fifo)) { - return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, - "No image acquired"); + return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "No image acquired"); } uint32_t index; @@ -93,12 +82,10 @@ oxr_swapchain_wait_image(struct oxr_logger *log, xrt_result_t res = xsc->wait_image(xsc, waitInfo->timeout, index); if (res == XRT_ERROR_IPC_FAILURE) { - return oxr_error(log, XR_ERROR_INSTANCE_LOST, - "Call to xsc->wait_image failed"); + return oxr_error(log, XR_ERROR_INSTANCE_LOST, "Call to xsc->wait_image failed"); } if (res != XRT_SUCCESS) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Call to xsc->wait_image failed"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Call to xsc->wait_image failed"); } // The app can only wait on one image. @@ -115,8 +102,7 @@ oxr_swapchain_release_image(struct oxr_logger *log, const XrSwapchainImageReleaseInfo *releaseInfo) { if (!sc->waited.yes) { - return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, - "No swapchain images waited on"); + return oxr_error(log, XR_ERROR_CALL_ORDER_INVALID, "No swapchain images waited on"); } sc->waited.yes = false; @@ -125,12 +111,10 @@ oxr_swapchain_release_image(struct oxr_logger *log, struct xrt_swapchain *xsc = (struct xrt_swapchain *)sc->swapchain; xrt_result_t res = xsc->release_image(xsc, index); if (res == XRT_ERROR_IPC_FAILURE) { - return oxr_error(log, XR_ERROR_INSTANCE_LOST, - "Call to xsc->release_image failed"); + return oxr_error(log, XR_ERROR_INSTANCE_LOST, "Call to xsc->release_image failed"); } if (res != XRT_SUCCESS) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Call to xsc->release_image failed"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Call to xsc->release_image failed"); } // Only decerement here. @@ -229,14 +213,12 @@ oxr_create_swapchain(struct oxr_logger *log, "but not supported"); } if (xret != XRT_SUCCESS) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "Failed to create swapchain"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Failed to create swapchain"); } assert(xsc != NULL); struct oxr_swapchain *sc = NULL; - OXR_ALLOCATE_HANDLE_OR_RETURN(log, sc, OXR_XR_DEBUG_SWAPCHAIN, - oxr_swapchain_destroy, &sess->handle); + OXR_ALLOCATE_HANDLE_OR_RETURN(log, sc, OXR_XR_DEBUG_SWAPCHAIN, oxr_swapchain_destroy, &sess->handle); sc->sess = sess; sc->swapchain = xsc; sc->width = createInfo->width; @@ -245,8 +227,7 @@ oxr_create_swapchain(struct oxr_logger *log, sc->acquire_image = oxr_swapchain_acquire_image; sc->wait_image = oxr_swapchain_wait_image; sc->release_image = oxr_swapchain_release_image; - sc->is_static = (createInfo->createFlags & - XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT) != 0; + sc->is_static = (createInfo->createFlags & XR_SWAPCHAIN_CREATE_STATIC_IMAGE_BIT) != 0; *out_swapchain = sc; diff --git a/src/xrt/state_trackers/oxr/oxr_swapchain_gl.c b/src/xrt/state_trackers/oxr/oxr_swapchain_gl.c index 2c821a589..55746234a 100644 --- a/src/xrt/state_trackers/oxr/oxr_swapchain_gl.c +++ b/src/xrt/state_trackers/oxr/oxr_swapchain_gl.c @@ -18,8 +18,7 @@ #include "oxr_logger.h" -#if defined(XR_USE_GRAPHICS_API_OPENGL) || \ - defined(XR_USE_GRAPHICS_API_OPENGL_ES) +#if defined(XR_USE_GRAPHICS_API_OPENGL) || defined(XR_USE_GRAPHICS_API_OPENGL_ES) static XrResult oxr_swapchain_gl_destroy(struct oxr_logger *log, struct oxr_swapchain *sc) @@ -54,8 +53,7 @@ oxr_swapchain_gl_enumerate_images_gl(struct oxr_logger *log, struct xrt_swapchain_gl *xsc = (struct xrt_swapchain_gl *)sc->swapchain; for (uint32_t i = 0; i < count; i++) { if (images[i].type != images[0].type) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "Images array contains mixed types"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "Images array contains mixed types"); } images[i].image = xsc->images[i]; } @@ -75,8 +73,7 @@ oxr_swapchain_gl_enumerate_images_gles(struct oxr_logger *log, struct xrt_swapchain_gl *xsc = (struct xrt_swapchain_gl *)sc->swapchain; for (uint32_t i = 0; i < count; i++) { if (images[i].type != images[0].type) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "Images array contains mixed types"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "Images array contains mixed types"); } images[i].image = xsc->images[i]; } @@ -95,17 +92,13 @@ oxr_swapchain_gl_enumerate_images(struct oxr_logger *log, switch (images[0].type) { #if defined(XR_USE_GRAPHICS_API_OPENGL) case XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR: - return oxr_swapchain_gl_enumerate_images_gl( - log, sc, count, (XrSwapchainImageOpenGLKHR *)images); + return oxr_swapchain_gl_enumerate_images_gl(log, sc, count, (XrSwapchainImageOpenGLKHR *)images); #endif // XR_USE_GRAPHICS_API_OPENGL #if defined(XR_USE_GRAPHICS_API_OPENGL_ES) case XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR: - return oxr_swapchain_gl_enumerate_images_gles( - log, sc, count, (XrSwapchainImageOpenGLESKHR *)images); + return oxr_swapchain_gl_enumerate_images_gles(log, sc, count, (XrSwapchainImageOpenGLESKHR *)images); #endif // XR_USE_GRAPHICS_API_OPENGL_ES - default: - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "Unsupported XrSwapchainImageBaseHeader type"); + default: return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "Unsupported XrSwapchainImageBaseHeader type"); } } diff --git a/src/xrt/state_trackers/oxr/oxr_swapchain_vk.c b/src/xrt/state_trackers/oxr/oxr_swapchain_vk.c index 0ec1903d1..2a4199726 100644 --- a/src/xrt/state_trackers/oxr/oxr_swapchain_vk.c +++ b/src/xrt/state_trackers/oxr/oxr_swapchain_vk.c @@ -46,10 +46,8 @@ oxr_swapchain_vk_enumerate_images(struct oxr_logger *log, uint32_t count, XrSwapchainImageBaseHeader *images) { - struct xrt_swapchain_vk *xscvk = - (struct xrt_swapchain_vk *)sc->swapchain; - XrSwapchainImageVulkanKHR *vk_imgs = - (XrSwapchainImageVulkanKHR *)images; + struct xrt_swapchain_vk *xscvk = (struct xrt_swapchain_vk *)sc->swapchain; + XrSwapchainImageVulkanKHR *vk_imgs = (XrSwapchainImageVulkanKHR *)images; for (uint32_t i = 0; i < count; i++) { vk_imgs[i].image = xscvk->images[i]; diff --git a/src/xrt/state_trackers/oxr/oxr_system.c b/src/xrt/state_trackers/oxr/oxr_system.c index 4d0cf6c58..33ba6e1e3 100644 --- a/src/xrt/state_trackers/oxr/oxr_system.c +++ b/src/xrt/state_trackers/oxr/oxr_system.c @@ -26,9 +26,7 @@ DEBUG_GET_ONCE_NUM_OPTION(scale_percentage, "OXR_VIEWPORT_SCALE_PERCENTAGE", 100 // clang-format on static bool -oxr_system_matches(struct oxr_logger *log, - struct oxr_system *sys, - XrFormFactor form_factor) +oxr_system_matches(struct oxr_logger *log, struct oxr_system *sys, XrFormFactor form_factor) { return form_factor == sys->form_factor; } @@ -41,10 +39,8 @@ oxr_system_select(struct oxr_logger *log, struct oxr_system **out_selected) { if (num_systems == 0) { - return oxr_error( - log, XR_ERROR_FORM_FACTOR_UNSUPPORTED, - "(getInfo->formFactor) no system available (given: %i)", - form_factor); + return oxr_error(log, XR_ERROR_FORM_FACTOR_UNSUPPORTED, + "(getInfo->formFactor) no system available (given: %i)", form_factor); } struct oxr_system *selected = NULL; @@ -68,22 +64,16 @@ oxr_system_select(struct oxr_logger *log, } XrResult -oxr_system_verify_id(struct oxr_logger *log, - const struct oxr_instance *inst, - XrSystemId systemId) +oxr_system_verify_id(struct oxr_logger *log, const struct oxr_instance *inst, XrSystemId systemId) { if (systemId != 1) { - return oxr_error(log, XR_ERROR_SYSTEM_INVALID, - "Invalid system %" PRIu64, systemId); + return oxr_error(log, XR_ERROR_SYSTEM_INVALID, "Invalid system %" PRIu64, systemId); } return XR_SUCCESS; } XrResult -oxr_system_get_by_id(struct oxr_logger *log, - struct oxr_instance *inst, - XrSystemId systemId, - struct oxr_system **system) +oxr_system_get_by_id(struct oxr_logger *log, struct oxr_instance *inst, XrSystemId systemId, struct oxr_system **system) { XrResult result = oxr_system_verify_id(log, inst, systemId); if (result != XR_SUCCESS) { @@ -97,10 +87,7 @@ oxr_system_get_by_id(struct oxr_logger *log, } XrResult -oxr_system_fill_in(struct oxr_logger *log, - struct oxr_instance *inst, - XrSystemId systemId, - struct oxr_system *sys) +oxr_system_fill_in(struct oxr_logger *log, struct oxr_instance *inst, XrSystemId systemId, struct oxr_system *sys) { //! @todo handle other subaction paths? @@ -183,8 +170,7 @@ oxr_system_fill_in(struct oxr_logger *log, } bool -oxr_system_get_hand_tracking_support(struct oxr_logger *log, - struct oxr_instance *inst) +oxr_system_get_hand_tracking_support(struct oxr_logger *log, struct oxr_instance *inst) { struct oxr_system *sys = &inst->system; struct xrt_device *left = GET_XDEV_BY_ROLE(sys, left); @@ -196,9 +182,7 @@ oxr_system_get_hand_tracking_support(struct oxr_logger *log, } XrResult -oxr_system_get_properties(struct oxr_logger *log, - struct oxr_system *sys, - XrSystemProperties *properties) +oxr_system_get_properties(struct oxr_logger *log, struct oxr_system *sys, XrSystemProperties *properties) { properties->vendorId = 42; properties->systemId = sys->systemId; @@ -206,8 +190,7 @@ oxr_system_get_properties(struct oxr_logger *log, struct xrt_device *xdev = GET_XDEV_BY_ROLE(sys, head); // The magical 247 number, is to silence warnings. - snprintf(properties->systemName, XR_MAX_SYSTEM_NAME_SIZE, - "Monado: %.*s", 247, xdev->str); + snprintf(properties->systemName, XR_MAX_SYSTEM_NAME_SIZE, "Monado: %.*s", 247, xdev->str); // Get from compositor. struct xrt_compositor_info *info = &sys->xcn->base.info; @@ -215,24 +198,17 @@ oxr_system_get_properties(struct oxr_logger *log, properties->graphicsProperties.maxLayerCount = info->max_layers; properties->graphicsProperties.maxSwapchainImageWidth = 1024 * 16; properties->graphicsProperties.maxSwapchainImageHeight = 1024 * 16; - properties->trackingProperties.orientationTracking = - xdev->orientation_tracking_supported; - properties->trackingProperties.positionTracking = - xdev->position_tracking_supported; + properties->trackingProperties.orientationTracking = xdev->orientation_tracking_supported; + properties->trackingProperties.positionTracking = xdev->position_tracking_supported; - XrSystemHandTrackingPropertiesEXT *hand_tracking_props = - OXR_GET_OUTPUT_FROM_CHAIN( - properties, XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT, - XrSystemHandTrackingPropertiesEXT); + XrSystemHandTrackingPropertiesEXT *hand_tracking_props = OXR_GET_OUTPUT_FROM_CHAIN( + properties, XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT, XrSystemHandTrackingPropertiesEXT); if (hand_tracking_props) { if (!sys->inst->extensions.EXT_hand_tracking) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "XR_EXT_hand_tracking is not enabled."); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "XR_EXT_hand_tracking is not enabled."); } - hand_tracking_props->supportsHandTracking = - oxr_system_get_hand_tracking_support(log, sys->inst); + hand_tracking_props->supportsHandTracking = oxr_system_get_hand_tracking_support(log, sys->inst); } return XR_SUCCESS; @@ -245,10 +221,8 @@ oxr_system_enumerate_view_confs(struct oxr_logger *log, uint32_t *viewConfigurationTypeCountOutput, XrViewConfigurationType *viewConfigurationTypes) { - OXR_TWO_CALL_HELPER(log, viewConfigurationTypeCapacityInput, - viewConfigurationTypeCountOutput, - viewConfigurationTypes, 1, &sys->view_config_type, - XR_SUCCESS); + OXR_TWO_CALL_HELPER(log, viewConfigurationTypeCapacityInput, viewConfigurationTypeCountOutput, + viewConfigurationTypes, 1, &sys->view_config_type, XR_SUCCESS); } XrResult @@ -260,23 +234,18 @@ oxr_system_enumerate_blend_modes(struct oxr_logger *log, XrEnvironmentBlendMode *environmentBlendModes) { //! @todo Take into account viewConfigurationType - OXR_TWO_CALL_HELPER(log, environmentBlendModeCapacityInput, - environmentBlendModeCountOutput, - environmentBlendModes, sys->num_blend_modes, - sys->blend_modes, XR_SUCCESS); + OXR_TWO_CALL_HELPER(log, environmentBlendModeCapacityInput, environmentBlendModeCountOutput, + environmentBlendModes, sys->num_blend_modes, sys->blend_modes, XR_SUCCESS); } XrResult -oxr_system_get_view_conf_properties( - struct oxr_logger *log, - struct oxr_system *sys, - XrViewConfigurationType viewConfigurationType, - XrViewConfigurationProperties *configurationProperties) +oxr_system_get_view_conf_properties(struct oxr_logger *log, + struct oxr_system *sys, + XrViewConfigurationType viewConfigurationType, + XrViewConfigurationProperties *configurationProperties) { if (viewConfigurationType != sys->view_config_type) { - return oxr_error(log, - XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED, - "Invalid view configuration type"); + return oxr_error(log, XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED, "Invalid view configuration type"); } // clang-format off @@ -288,8 +257,7 @@ oxr_system_get_view_conf_properties( } static void -view_configuration_view_fill_in(XrViewConfigurationView *target_view, - XrViewConfigurationView *source_view) +view_configuration_view_fill_in(XrViewConfigurationView *target_view, XrViewConfigurationView *source_view) { // clang-format off target_view->recommendedImageRectWidth = source_view->recommendedImageRectWidth; @@ -302,21 +270,17 @@ view_configuration_view_fill_in(XrViewConfigurationView *target_view, } XrResult -oxr_system_enumerate_view_conf_views( - struct oxr_logger *log, - struct oxr_system *sys, - XrViewConfigurationType viewConfigurationType, - uint32_t viewCapacityInput, - uint32_t *viewCountOutput, - XrViewConfigurationView *views) +oxr_system_enumerate_view_conf_views(struct oxr_logger *log, + struct oxr_system *sys, + XrViewConfigurationType viewConfigurationType, + uint32_t viewCapacityInput, + uint32_t *viewCountOutput, + XrViewConfigurationView *views) { if (viewConfigurationType != sys->view_config_type) { - return oxr_error(log, - XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED, - "Invalid view configuration type"); + return oxr_error(log, XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED, "Invalid view configuration type"); } - OXR_TWO_CALL_FILL_IN_HELPER(log, viewCapacityInput, viewCountOutput, - views, 2, view_configuration_view_fill_in, + OXR_TWO_CALL_FILL_IN_HELPER(log, viewCapacityInput, viewCountOutput, views, 2, view_configuration_view_fill_in, sys->views, XR_SUCCESS); } diff --git a/src/xrt/state_trackers/oxr/oxr_two_call.h b/src/xrt/state_trackers/oxr/oxr_two_call.h index ac51093fd..012ddace1 100644 --- a/src/xrt/state_trackers/oxr/oxr_two_call.h +++ b/src/xrt/state_trackers/oxr/oxr_two_call.h @@ -15,50 +15,43 @@ extern "C" { #endif -#define OXR_TWO_CALL_HELPER(log, cnt_input, cnt_output, output, count, data, \ - sval) \ - do { \ - if (cnt_output == NULL) { \ - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, \ - #cnt_output); \ - } \ - *cnt_output = count; \ - \ - if (cnt_input == 0) { \ - return sval; \ - } \ - if (cnt_input < count) { \ - return oxr_error(log, XR_ERROR_SIZE_INSUFFICIENT, \ - #cnt_input); \ - } \ - for (uint32_t i = 0; i < count; i++) { \ - (output)[i] = (data)[i]; \ - } \ - return sval; \ +#define OXR_TWO_CALL_HELPER(log, cnt_input, cnt_output, output, count, data, sval) \ + do { \ + if (cnt_output == NULL) { \ + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, #cnt_output); \ + } \ + *cnt_output = count; \ + \ + if (cnt_input == 0) { \ + return sval; \ + } \ + if (cnt_input < count) { \ + return oxr_error(log, XR_ERROR_SIZE_INSUFFICIENT, #cnt_input); \ + } \ + for (uint32_t i = 0; i < count; i++) { \ + (output)[i] = (data)[i]; \ + } \ + return sval; \ } while (false) //! Calls fill_fn(&output_struct[i], &source_struct[i]) to fill output_structs -#define OXR_TWO_CALL_FILL_IN_HELPER(log, cnt_input, cnt_output, \ - output_structs, count, fill_fn, \ - source_structs, sval) \ - do { \ - if (cnt_output == NULL) { \ - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, \ - #cnt_output); \ - } \ - *cnt_output = count; \ - \ - if (cnt_input == 0) { \ - return sval; \ - } \ - if (cnt_input < count) { \ - return oxr_error(log, XR_ERROR_SIZE_INSUFFICIENT, \ - #cnt_input); \ - } \ - for (uint32_t i = 0; i < count; i++) { \ - fill_fn(&output_structs[i], &source_structs[i]); \ - } \ - return sval; \ +#define OXR_TWO_CALL_FILL_IN_HELPER(log, cnt_input, cnt_output, output_structs, count, fill_fn, source_structs, sval) \ + do { \ + if (cnt_output == NULL) { \ + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, #cnt_output); \ + } \ + *cnt_output = count; \ + \ + if (cnt_input == 0) { \ + return sval; \ + } \ + if (cnt_input < count) { \ + return oxr_error(log, XR_ERROR_SIZE_INSUFFICIENT, #cnt_input); \ + } \ + for (uint32_t i = 0; i < count; i++) { \ + fill_fn(&output_structs[i], &source_structs[i]); \ + } \ + return sval; \ } while (false) #ifdef __cplusplus diff --git a/src/xrt/state_trackers/oxr/oxr_verify.c b/src/xrt/state_trackers/oxr/oxr_verify.c index 74ea8fabb..ec6d42590 100644 --- a/src/xrt/state_trackers/oxr/oxr_verify.c +++ b/src/xrt/state_trackers/oxr/oxr_verify.c @@ -60,25 +60,18 @@ contains_zero(const char *path, uint32_t size) } XrResult -oxr_verify_fixed_size_single_level_path(struct oxr_logger *log, - const char *path, - uint32_t array_size, - const char *name) +oxr_verify_fixed_size_single_level_path(struct oxr_logger *log, const char *path, uint32_t array_size, const char *name) { if (array_size == 0) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "(%s) internal runtime error", name); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "(%s) internal runtime error", name); } if (path[0] == '\0') { - return oxr_error(log, XR_ERROR_NAME_INVALID, - "(%s) can not be empty", name); + return oxr_error(log, XR_ERROR_NAME_INVALID, "(%s) can not be empty", name); } if (!contains_zero(path, array_size)) { - return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, - "(%s) must include zero termination '\\0'.", - name); + return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, "(%s) must include zero termination '\\0'.", name); } size_t length = strlen(path); @@ -90,34 +83,26 @@ oxr_verify_fixed_size_single_level_path(struct oxr_logger *log, continue; } - return oxr_error( - log, XR_ERROR_PATH_FORMAT_INVALID, - "(%s) 0x%02x is not a valid character at position %u", name, - c, (uint32_t)i); + return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, + "(%s) 0x%02x is not a valid character at position %u", name, c, (uint32_t)i); } return XR_SUCCESS; } XrResult -oxr_verify_localized_name(struct oxr_logger *log, - const char *string, - uint32_t array_size, - const char *name) +oxr_verify_localized_name(struct oxr_logger *log, const char *string, uint32_t array_size, const char *name) { if (array_size == 0) { - return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, - "(%s) internal runtime error", name); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "(%s) internal runtime error", name); } if (string[0] == '\0') { - return oxr_error(log, XR_ERROR_LOCALIZED_NAME_INVALID, - "(%s) can not be empty", name); + return oxr_error(log, XR_ERROR_LOCALIZED_NAME_INVALID, "(%s) can not be empty", name); } if (!contains_zero(string, array_size)) { - return oxr_error(log, XR_ERROR_LOCALIZED_NAME_INVALID, - "(%s) must include zero termination '\\0'.", + return oxr_error(log, XR_ERROR_LOCALIZED_NAME_INVALID, "(%s) must include zero termination '\\0'.", name); } @@ -134,9 +119,7 @@ enum verify_state }; XrResult -oxr_verify_full_path_c(struct oxr_logger *log, - const char *path, - const char *name) +oxr_verify_full_path_c(struct oxr_logger *log, const char *path, const char *name) { // XR_MAX_PATH_LENGTH is max including null terminator, // length will not include null terminator @@ -152,18 +135,14 @@ oxr_verify_full_path_c(struct oxr_logger *log, } XrResult -oxr_verify_full_path(struct oxr_logger *log, - const char *path, - size_t length, - const char *name) +oxr_verify_full_path(struct oxr_logger *log, const char *path, size_t length, const char *name) { enum verify_state state = VERIFY_START; bool valid = true; if (length >= XR_MAX_PATH_LENGTH) { char formatted_path[XR_MAX_PATH_LENGTH + 6]; - snprintf(formatted_path, XR_MAX_PATH_LENGTH + 6, "%s[...]", - path); + snprintf(formatted_path, XR_MAX_PATH_LENGTH + 6, "%s[...]", path); return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, "(%s) is too long for a path, must be shorter " "than %u characters", @@ -175,8 +154,7 @@ oxr_verify_full_path(struct oxr_logger *log, switch (state) { case VERIFY_START: if (c != '/') { - return oxr_error(log, - XR_ERROR_PATH_FORMAT_INVALID, + return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, "(%s) does not start with a " "fowrward slash", name); @@ -190,35 +168,26 @@ oxr_verify_full_path(struct oxr_logger *log, state = VERIFY_SLASHDOTS; break; case '/': - return oxr_error( - log, XR_ERROR_PATH_FORMAT_INVALID, - "(%s) '//' is not a valid in a path", name); - default: - valid = valid_path_char(c); - state = VERIFY_MIDDLE; + return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, + "(%s) '//' is not a valid in a path", name); + default: valid = valid_path_char(c); state = VERIFY_MIDDLE; } break; case VERIFY_MIDDLE: switch (c) { case '/': state = VERIFY_SLASH; break; - default: - valid = valid_path_char(c); - state = VERIFY_MIDDLE; + default: valid = valid_path_char(c); state = VERIFY_MIDDLE; } break; case VERIFY_SLASHDOTS: switch (c) { case '/': - return oxr_error( - log, XR_ERROR_PATH_FORMAT_INVALID, - "(%s) '/.[.]*/' is not a valid in a path", - name); + return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, + "(%s) '/.[.]*/' is not a valid in a path", name); case '.': // It's valid, more ShashDot(s). break; - default: - valid = valid_path_char(c); - state = VERIFY_MIDDLE; + default: valid = valid_path_char(c); state = VERIFY_MIDDLE; } break; } @@ -238,9 +207,7 @@ oxr_verify_full_path(struct oxr_logger *log, switch (state) { case VERIFY_START: // Empty string - return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, - "(%s) a empty string is not a valid path", - name); + return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, "(%s) a empty string is not a valid path", name); case VERIFY_SLASH: // Is this '/foo/' or '/' if (length > 1) { @@ -248,24 +215,20 @@ oxr_verify_full_path(struct oxr_logger *log, return XR_SUCCESS; } // It was '/' - return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, - "(%s) the string '%s' is not a valid path", - name, path); + return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, "(%s) the string '%s' is not a valid path", name, + path); case VERIFY_SLASHDOTS: // Does the path ends with '/..' - return oxr_error( - log, XR_ERROR_PATH_FORMAT_INVALID, - "(%s) strings ending with '/.[.]*' is not a valid", name); + return oxr_error(log, XR_ERROR_PATH_FORMAT_INVALID, "(%s) strings ending with '/.[.]*' is not a valid", + name); case VERIFY_MIDDLE: // '/foo/bar' okay! return XR_SUCCESS; default: // We should not end up here. - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "(%s) internal runtime error validating path (%s)", name, - path); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "(%s) internal runtime error validating path (%s)", + name, path); } } @@ -294,13 +257,13 @@ subaction_path_no_dups(struct oxr_logger *log, variable, index); } -#define HANDLE_SUBACTION_PATH(X) \ - if (path == inst->path_cache.X) { \ - if (sub_paths->X) { \ - duplicate = true; \ - } else { \ - sub_paths->X = true; \ - } \ +#define HANDLE_SUBACTION_PATH(X) \ + if (path == inst->path_cache.X) { \ + if (sub_paths->X) { \ + duplicate = true; \ + } else { \ + sub_paths->X = true; \ + } \ } else OXR_FOR_EACH_VALID_SUBACTION_PATH(HANDLE_SUBACTION_PATH) @@ -323,9 +286,8 @@ subaction_path_no_dups(struct oxr_logger *log, oxr_path_get_string(log, inst, path, &str, &length); - return oxr_error(log, XR_ERROR_PATH_UNSUPPORTED, - "(%s[%u] == '%s') duplicate paths", variable, - index, str); + return oxr_error(log, XR_ERROR_PATH_UNSUPPORTED, "(%s[%u] == '%s') duplicate paths", variable, index, + str); } return XR_SUCCESS; @@ -344,8 +306,7 @@ oxr_verify_subaction_paths_create(struct oxr_logger *log, for (uint32_t i = 0; i < countSubactionPaths; i++) { XrPath path = subactionPaths[i]; - XrResult ret = subaction_path_no_dups(log, inst, &sub_paths, - path, variable, i); + XrResult ret = subaction_path_no_dups(log, inst, &sub_paths, path, variable, i); if (ret != XR_SUCCESS) { return ret; } @@ -355,15 +316,12 @@ oxr_verify_subaction_paths_create(struct oxr_logger *log, } XrResult -oxr_verify_subaction_path_sync(struct oxr_logger *log, - struct oxr_instance *inst, - XrPath path, - uint32_t index) +oxr_verify_subaction_path_sync(struct oxr_logger *log, struct oxr_instance *inst, XrPath path, uint32_t index) { -#define VERIFY_PATH(X) \ - else if (path == inst->path_cache.X) \ - { \ - return XR_SUCCESS; \ +#define VERIFY_PATH(X) \ + else if (path == inst->path_cache.X) \ + { \ + return XR_SUCCESS; \ } if (path == XR_NULL_PATH) { return XR_SUCCESS; @@ -392,10 +350,10 @@ oxr_verify_subaction_path_get(struct oxr_logger *log, { struct oxr_sub_paths sub_paths = {0}; -#define GET_PATH(X) \ - else if (path == inst->path_cache.X) \ - { \ - sub_paths.X = true; \ +#define GET_PATH(X) \ + else if (path == inst->path_cache.X) \ + { \ + sub_paths.X = true; \ } if (path == XR_NULL_PATH) { @@ -415,9 +373,9 @@ oxr_verify_subaction_path_get(struct oxr_logger *log, #undef GET_PATH bool fail = false; -#define CHECK_CREATION_TIME(X) \ - if (sub_paths.X && !act_sub_paths->X) { \ - fail = true; \ +#define CHECK_CREATION_TIME(X) \ + if (sub_paths.X && !act_sub_paths->X) { \ + fail = true; \ } OXR_FOR_EACH_SUBACTION_PATH(CHECK_CREATION_TIME); @@ -459,8 +417,7 @@ oxr_verify_view_config_type(struct oxr_logger *log, return XR_SUCCESS; } - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "(%s == 0x%08x) invalid view configuration type", + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(%s == 0x%08x) invalid view configuration type", view_conf_name, view_conf); } @@ -470,13 +427,11 @@ oxr_verify_XrSessionCreateInfo(struct oxr_logger *log, const XrSessionCreateInfo *createInfo) { if (createInfo->type != XR_TYPE_SESSION_CREATE_INFO) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "(createInfo->type)"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(createInfo->type)"); } if (createInfo->createFlags != 0) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "Non-zero session create flags"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "Non-zero session create flags"); } XrResult result = oxr_system_verify_id(log, inst, createInfo->systemId); @@ -485,35 +440,29 @@ oxr_verify_XrSessionCreateInfo(struct oxr_logger *log, } #if defined(OXR_HAVE_KHR_opengl_enable) && defined(XR_USE_PLATFORM_XLIB) - XrGraphicsBindingOpenGLXlibKHR const *opengl_xlib = - OXR_GET_INPUT_FROM_CHAIN(createInfo, - XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR, - XrGraphicsBindingOpenGLXlibKHR); + XrGraphicsBindingOpenGLXlibKHR const *opengl_xlib = OXR_GET_INPUT_FROM_CHAIN( + createInfo, XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR, XrGraphicsBindingOpenGLXlibKHR); if (opengl_xlib != NULL) { OXR_VERIFY_EXTENSION(log, inst, KHR_opengl_enable); - return oxr_verify_XrGraphicsBindingOpenGLXlibKHR(log, - opengl_xlib); + return oxr_verify_XrGraphicsBindingOpenGLXlibKHR(log, opengl_xlib); } #endif // defined(OXR_HAVE_KHR_opengl_enable) && defined(XR_USE_PLATFORM_XLIB) #if defined(OXR_HAVE_KHR_vulkan_enable) || defined(OXR_HAVE_KHR_vulkan_enable2) /* XR_TYPE_GRAPHICS_BINDING_VULKAN2_KHR aliased to * XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR */ - XrGraphicsBindingVulkanKHR const *vulkan = OXR_GET_INPUT_FROM_CHAIN( - createInfo, XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR, - XrGraphicsBindingVulkanKHR); + XrGraphicsBindingVulkanKHR const *vulkan = + OXR_GET_INPUT_FROM_CHAIN(createInfo, XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR, XrGraphicsBindingVulkanKHR); if (vulkan != NULL) { - OXR_VERIFY_EXTENSIONS_OR(log, inst, KHR_vulkan_enable, - KHR_vulkan_enable2); + OXR_VERIFY_EXTENSIONS_OR(log, inst, KHR_vulkan_enable, KHR_vulkan_enable2); return oxr_verify_XrGraphicsBindingVulkanKHR(log, vulkan); } #endif // defined(OXR_HAVE_KHR_vulkan_enable) || // defined(OXR_HAVE_KHR_vulkan_enable2) #if defined(OXR_HAVE_MNDX_egl_enable) && defined(XR_USE_PLATFORM_EGL) - XrGraphicsBindingEGLMNDX const *egl = OXR_GET_INPUT_FROM_CHAIN( - createInfo, XR_TYPE_GRAPHICS_BINDING_EGL_MNDX, - XrGraphicsBindingEGLMNDX); + XrGraphicsBindingEGLMNDX const *egl = + OXR_GET_INPUT_FROM_CHAIN(createInfo, XR_TYPE_GRAPHICS_BINDING_EGL_MNDX, XrGraphicsBindingEGLMNDX); if (egl != NULL) { OXR_VERIFY_EXTENSION(log, inst, MNDX_egl_enable); return oxr_verify_XrGraphicsBindingEGLMNDX(log, egl); @@ -521,14 +470,11 @@ oxr_verify_XrSessionCreateInfo(struct oxr_logger *log, #endif // defined(OXR_HAVE_MNDX_egl_enable) && defined(XR_USE_PLATFORM_EGL_KHR) #if defined(XR_USE_PLATFORM_ANDROID) && defined(XR_USE_GRAPHICS_API_OPENGL_ES) - XrGraphicsBindingOpenGLESAndroidKHR const *opengles_android = - OXR_GET_INPUT_FROM_CHAIN( - createInfo, XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR, - XrGraphicsBindingOpenGLESAndroidKHR); + XrGraphicsBindingOpenGLESAndroidKHR const *opengles_android = OXR_GET_INPUT_FROM_CHAIN( + createInfo, XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR, XrGraphicsBindingOpenGLESAndroidKHR); if (opengles_android != NULL) { OXR_VERIFY_EXTENSION(log, inst, KHR_opengl_es_enable); - return oxr_verify_XrGraphicsBindingOpenGLESAndroidKHR( - log, opengles_android); + return oxr_verify_XrGraphicsBindingOpenGLESAndroidKHR(log, opengles_android); } #endif // OXR_HAVE_KHR_vulkan_enable @@ -556,27 +502,22 @@ oxr_verify_XrSessionCreateInfo(struct oxr_logger *log, #if defined(XR_USE_PLATFORM_XLIB) && defined(XR_USE_GRAPHICS_API_OPENGL) XrResult -oxr_verify_XrGraphicsBindingOpenGLXlibKHR( - struct oxr_logger *log, const XrGraphicsBindingOpenGLXlibKHR *next) +oxr_verify_XrGraphicsBindingOpenGLXlibKHR(struct oxr_logger *log, const XrGraphicsBindingOpenGLXlibKHR *next) { if (next->type != XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "Graphics binding has invalid type"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "Graphics binding has invalid type"); } if (next->xDisplay == NULL) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "xDisplay is NULL"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "xDisplay is NULL"); } if (next->glxContext == NULL) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "glxContext is NULL"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "glxContext is NULL"); } if (next->glxDrawable == NULL) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "glxDrawable is NULL"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "glxDrawable is NULL"); } @@ -589,14 +530,12 @@ oxr_verify_XrGraphicsBindingOpenGLXlibKHR( #ifdef XR_USE_GRAPHICS_API_VULKAN XrResult -oxr_verify_XrGraphicsBindingVulkanKHR(struct oxr_logger *log, - const XrGraphicsBindingVulkanKHR *next) +oxr_verify_XrGraphicsBindingVulkanKHR(struct oxr_logger *log, const XrGraphicsBindingVulkanKHR *next) { /* XR_TYPE_GRAPHICS_BINDING_VULKAN2_KHR aliased to * XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR */ if (next->type != XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "Graphics binding has invalid type"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "Graphics binding has invalid type"); } return XR_SUCCESS; @@ -608,39 +547,29 @@ oxr_verify_XrGraphicsBindingVulkanKHR(struct oxr_logger *log, #ifdef XR_USE_PLATFORM_EGL XrResult -oxr_verify_XrGraphicsBindingEGLMNDX(struct oxr_logger *log, - const XrGraphicsBindingEGLMNDX *next) +oxr_verify_XrGraphicsBindingEGLMNDX(struct oxr_logger *log, const XrGraphicsBindingEGLMNDX *next) { // Here for internal error checking if (next->type != XR_TYPE_GRAPHICS_BINDING_EGL_MNDX) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "XrGraphicsBindingEGLMNDX::type is invalid '%i'", - next->type); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "XrGraphicsBindingEGLMNDX::type is invalid '%i'", + next->type); } if (next->getProcAddress == NULL) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "XrGraphicsBindingEGLMNDX::getProcAddress cannot be NULL"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, + "XrGraphicsBindingEGLMNDX::getProcAddress cannot be NULL"); } if (next->display == NULL) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "XrGraphicsBindingEGLMNDX::display cannot be NULL"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "XrGraphicsBindingEGLMNDX::display cannot be NULL"); } if (next->config == NULL) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "XrGraphicsBindingEGLMNDX::config cannot be NULL"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "XrGraphicsBindingEGLMNDX::config cannot be NULL"); } if (next->context == NULL) { - return oxr_error( - log, XR_ERROR_VALIDATION_FAILURE, - "XrGraphicsBindingEGLMNDX::context cannot be NULL"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "XrGraphicsBindingEGLMNDX::context cannot be NULL"); } return XR_SUCCESS; @@ -650,12 +579,10 @@ oxr_verify_XrGraphicsBindingEGLMNDX(struct oxr_logger *log, #if defined(XR_USE_PLATFORM_ANDROID) && defined(XR_USE_GRAPHICS_API_OPENGL_ES) XrResult -oxr_verify_XrGraphicsBindingOpenGLESAndroidKHR( - struct oxr_logger *log, const XrGraphicsBindingOpenGLESAndroidKHR *next) +oxr_verify_XrGraphicsBindingOpenGLESAndroidKHR(struct oxr_logger *log, const XrGraphicsBindingOpenGLESAndroidKHR *next) { if (next->type != XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR) { - return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, - "Graphics binding has invalid type"); + return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "Graphics binding has invalid type"); } return XR_SUCCESS; diff --git a/src/xrt/state_trackers/oxr/oxr_vulkan.c b/src/xrt/state_trackers/oxr/oxr_vulkan.c index 62aa174fa..9f41244b7 100644 --- a/src/xrt/state_trackers/oxr/oxr_vulkan.c +++ b/src/xrt/state_trackers/oxr/oxr_vulkan.c @@ -32,9 +32,8 @@ oxr_vk_get_instance_exts(struct oxr_logger *log, { size_t length = strlen(xrt_gfx_vk_instance_extensions) + 1; - OXR_TWO_CALL_HELPER(log, namesCapacityInput, namesCountOutput, - namesString, length, xrt_gfx_vk_instance_extensions, - XR_SUCCESS); + OXR_TWO_CALL_HELPER(log, namesCapacityInput, namesCountOutput, namesString, length, + xrt_gfx_vk_instance_extensions, XR_SUCCESS); } XrResult @@ -46,9 +45,8 @@ oxr_vk_get_device_exts(struct oxr_logger *log, { size_t length = strlen(xrt_gfx_vk_device_extensions) + 1; - OXR_TWO_CALL_HELPER(log, namesCapacityInput, namesCountOutput, - namesString, length, xrt_gfx_vk_device_extensions, - XR_SUCCESS); + OXR_TWO_CALL_HELPER(log, namesCapacityInput, namesCountOutput, namesString, length, + xrt_gfx_vk_device_extensions, XR_SUCCESS); } XrResult @@ -59,10 +57,8 @@ oxr_vk_get_requirements(struct oxr_logger *log, struct xrt_api_requirements ver; xrt_gfx_vk_get_versions(&ver); - graphicsRequirements->minApiVersionSupported = - XR_MAKE_VERSION(ver.min_major, ver.min_minor, ver.min_patch); - graphicsRequirements->maxApiVersionSupported = - XR_MAKE_VERSION(ver.max_major, ver.max_minor, ver.max_patch); + graphicsRequirements->minApiVersionSupported = XR_MAKE_VERSION(ver.min_major, ver.min_minor, ver.min_patch); + graphicsRequirements->maxApiVersionSupported = XR_MAKE_VERSION(ver.max_major, ver.max_minor, ver.max_patch); sys->gotten_requirements = true; @@ -83,10 +79,8 @@ static const char *required_vk_instance_extensions[] = { // This should match the list in comp_compositor, except it shouldn't include // VK_KHR_SWAPCHAIN_EXTENSION_NAME static const char *required_vk_device_extensions[] = { - VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME, - VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME, - VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME, - VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME, + VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME, VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME, + VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME, VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME, // Platform version of "external_memory" @@ -104,8 +98,7 @@ static const char *required_vk_device_extensions[] = { // Platform version of "external_fence" and "external_semaphore" #if defined(XRT_GRAPHICS_SYNC_HANDLE_IS_FD) - VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, - VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME, + VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME, #elif defined(XRT_GRAPHICS_SYNC_HANDLE_IS_WIN32_HANDLE) VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME, @@ -140,8 +133,7 @@ find_to_add(char const *const *enabled, } static bool -extend_instance_extensions(struct oxr_logger *log, - VkInstanceCreateInfo *create_info) +extend_instance_extensions(struct oxr_logger *log, VkInstanceCreateInfo *create_info) { uint32_t num_required = ARRAY_SIZE(required_vk_instance_extensions); @@ -151,8 +143,7 @@ extend_instance_extensions(struct oxr_logger *log, uint32_t num_enabled = create_info->enabledExtensionCount; char const *const *enabled = create_info->ppEnabledExtensionNames; - find_to_add(enabled, num_enabled, required_vk_instance_extensions, - num_required, to_add, &num_to_add); + find_to_add(enabled, num_enabled, required_vk_instance_extensions, num_required, to_add, &num_to_add); enum u_logging_level ll = debug_get_log_option_compositor_log(); @@ -187,8 +178,7 @@ extend_instance_extensions(struct oxr_logger *log, } static bool -extend_device_extensions(struct oxr_logger *log, - VkDeviceCreateInfo *create_info) +extend_device_extensions(struct oxr_logger *log, VkDeviceCreateInfo *create_info) { uint32_t num_required = ARRAY_SIZE(required_vk_device_extensions); @@ -198,8 +188,7 @@ extend_device_extensions(struct oxr_logger *log, uint32_t num_enabled = create_info->enabledExtensionCount; char const *const *enabled = create_info->ppEnabledExtensionNames; - find_to_add(enabled, num_enabled, required_vk_device_extensions, - num_required, to_add, &num_to_add); + find_to_add(enabled, num_enabled, required_vk_device_extensions, num_required, to_add, &num_to_add); enum u_logging_level ll = debug_get_log_option_compositor_log(); @@ -241,25 +230,21 @@ oxr_vk_create_vulkan_instance(struct oxr_logger *log, VkResult *vulkanResult) { - PFN_vkGetInstanceProcAddr GetInstanceProcAddr = - createInfo->pfnGetInstanceProcAddr; + PFN_vkGetInstanceProcAddr GetInstanceProcAddr = createInfo->pfnGetInstanceProcAddr; - PFN_vkCreateInstance CreateInstance = - (PFN_vkCreateInstance)GetInstanceProcAddr(NULL, "vkCreateInstance"); + PFN_vkCreateInstance CreateInstance = (PFN_vkCreateInstance)GetInstanceProcAddr(NULL, "vkCreateInstance"); if (!CreateInstance) { //! @todo: clarify in spec *vulkanResult = VK_ERROR_INITIALIZATION_FAILED; return XR_SUCCESS; } - const VkAllocationCallbacks *vulkanAllocator = - createInfo->vulkanAllocator; + const VkAllocationCallbacks *vulkanAllocator = createInfo->vulkanAllocator; VkInstanceCreateInfo modified_info = *createInfo->vulkanCreateInfo; bool free_list = extend_instance_extensions(log, &modified_info); - *vulkanResult = - CreateInstance(&modified_info, vulkanAllocator, vulkanInstance); + *vulkanResult = CreateInstance(&modified_info, vulkanAllocator, vulkanInstance); if (free_list) { free((void *)modified_info.ppEnabledExtensionNames); @@ -277,27 +262,23 @@ oxr_vk_create_vulkan_device(struct oxr_logger *log, VkDevice *vulkanDevice, VkResult *vulkanResult) { - PFN_vkGetInstanceProcAddr GetInstanceProcAddr = - createInfo->pfnGetInstanceProcAddr; + PFN_vkGetInstanceProcAddr GetInstanceProcAddr = createInfo->pfnGetInstanceProcAddr; PFN_vkCreateDevice CreateDevice = - (PFN_vkCreateDevice)GetInstanceProcAddr( - sys->vulkan_enable2_instance, "vkCreateDevice"); + (PFN_vkCreateDevice)GetInstanceProcAddr(sys->vulkan_enable2_instance, "vkCreateDevice"); if (!CreateDevice) { //! @todo: clarify in spec *vulkanResult = VK_ERROR_INITIALIZATION_FAILED; return XR_SUCCESS; } - const VkAllocationCallbacks *vulkanAllocator = - createInfo->vulkanAllocator; + const VkAllocationCallbacks *vulkanAllocator = createInfo->vulkanAllocator; VkPhysicalDevice physical_device = createInfo->vulkanPhysicalDevice; VkDeviceCreateInfo modified_info = *createInfo->vulkanCreateInfo; bool free_list = extend_device_extensions(log, &modified_info); - *vulkanResult = CreateDevice(physical_device, &modified_info, - vulkanAllocator, vulkanDevice); + *vulkanResult = CreateDevice(physical_device, &modified_info, vulkanAllocator, vulkanDevice); if (free_list) { free((void *)modified_info.ppEnabledExtensionNames); @@ -322,63 +303,53 @@ oxr_vk_get_physical_device(struct oxr_logger *log, vk_ret = vkEnumeratePhysicalDevices(vkInstance, &count, NULL); if (vk_ret != VK_SUCCESS) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "Call to vkEnumeratePhysicalDevices returned %u", vk_ret); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Call to vkEnumeratePhysicalDevices returned %u", + vk_ret); } if (count == 0) { - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "Call to vkEnumeratePhysicalDevices returned zero " - "VkPhysicalDevices"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "Call to vkEnumeratePhysicalDevices returned zero " + "VkPhysicalDevices"); } VkPhysicalDevice *phys = U_TYPED_ARRAY_CALLOC(VkPhysicalDevice, count); vk_ret = vkEnumeratePhysicalDevices(vkInstance, &count, phys); if (vk_ret != VK_SUCCESS) { free(phys); - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "Call to vkEnumeratePhysicalDevices returned %u", vk_ret); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Call to vkEnumeratePhysicalDevices returned %u", + vk_ret); } if (count == 0) { free(phys); - return oxr_error( - log, XR_ERROR_RUNTIME_FAILURE, - "Call to vkEnumeratePhysicalDevices returned zero " - "VkPhysicalDevices"); + return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, + "Call to vkEnumeratePhysicalDevices returned zero " + "VkPhysicalDevices"); } char suggested_uuid_str[XRT_GPU_UUID_SIZE * 3 + 1] = {0}; for (int i = 0; i < XRT_GPU_UUID_SIZE; i++) { - sprintf(suggested_uuid_str + i * 3, "%02x ", - sys->xcn->base.info.client_vk_deviceUUID[i]); + sprintf(suggested_uuid_str + i * 3, "%02x ", sys->xcn->base.info.client_vk_deviceUUID[i]); } enum u_logging_level ll = debug_get_log_option_compositor_log(); int gpu_index = -1; for (uint32_t i = 0; i < count; i++) { - VkPhysicalDeviceIDProperties pdidp = { - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; + VkPhysicalDeviceIDProperties pdidp = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; - VkPhysicalDeviceProperties2 pdp2 = { - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, - .pNext = &pdidp}; + VkPhysicalDeviceProperties2 pdp2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, + .pNext = &pdidp}; vkGetPhysicalDeviceProperties2(phys[i], &pdp2); char uuid_str[XRT_GPU_UUID_SIZE * 3 + 1] = {0}; if (ll <= U_LOGGING_DEBUG) { for (int i = 0; i < XRT_GPU_UUID_SIZE; i++) { - sprintf(uuid_str + i * 3, "%02x ", - pdidp.deviceUUID[i]); + sprintf(uuid_str + i * 3, "%02x ", pdidp.deviceUUID[i]); } oxr_log(log, "GPU %d: uuid %s", i, uuid_str); } - if (memcmp(pdidp.deviceUUID, - sys->xcn->base.info.client_vk_deviceUUID, - XRT_GPU_UUID_SIZE) == 0) { + if (memcmp(pdidp.deviceUUID, sys->xcn->base.info.client_vk_deviceUUID, XRT_GPU_UUID_SIZE) == 0) { gpu_index = i; if (ll <= U_LOGGING_DEBUG) { oxr_log(log, @@ -391,9 +362,7 @@ oxr_vk_get_physical_device(struct oxr_logger *log, } if (gpu_index == -1) { - oxr_warn( - log, - "Did not find runtime suggested GPU, fall back to GPU 0"); + oxr_warn(log, "Did not find runtime suggested GPU, fall back to GPU 0"); gpu_index = 0; } diff --git a/src/xrt/state_trackers/oxr/oxr_xdev.c b/src/xrt/state_trackers/oxr/oxr_xdev.c index 1c3049c18..2df44cc1a 100644 --- a/src/xrt/state_trackers/oxr/oxr_xdev.c +++ b/src/xrt/state_trackers/oxr/oxr_xdev.c @@ -42,9 +42,7 @@ oxr_xdev_update(struct xrt_device *xdev) } bool -oxr_xdev_find_input(struct xrt_device *xdev, - enum xrt_input_name name, - struct xrt_input **out_input) +oxr_xdev_find_input(struct xrt_device *xdev, enum xrt_input_name name, struct xrt_input **out_input) { *out_input = NULL; if (xdev == NULL) { @@ -63,9 +61,7 @@ oxr_xdev_find_input(struct xrt_device *xdev, } bool -oxr_xdev_find_output(struct xrt_device *xdev, - enum xrt_output_name name, - struct xrt_output **out_output) +oxr_xdev_find_output(struct xrt_device *xdev, enum xrt_output_name name, struct xrt_output **out_output) { if (xdev == NULL) { return false; @@ -91,8 +87,7 @@ oxr_xdev_get_space_graph(struct oxr_logger *log, struct xrt_space_graph *xsg) { // Convert at_time to monotonic and give to device. - uint64_t at_timestamp_ns = - time_state_ts_to_monotonic_ns(inst->timekeeping, at_time); + uint64_t at_timestamp_ns = time_state_ts_to_monotonic_ns(inst->timekeeping, at_time); struct xrt_space_relation *rel = m_space_graph_reserve(xsg); xrt_device_get_tracked_pose(xdev, name, at_timestamp_ns, rel); @@ -110,8 +105,7 @@ oxr_xdev_get_hand_tracking_at(struct oxr_logger *log, struct xrt_hand_joint_set *out_value) { //! Convert at_time to monotonic and give to device. - uint64_t at_timestamp_ns = - time_state_ts_to_monotonic_ns(inst->timekeeping, at_time); + uint64_t at_timestamp_ns = time_state_ts_to_monotonic_ns(inst->timekeeping, at_time); struct xrt_hand_joint_set value; diff --git a/src/xrt/state_trackers/prober/p_dump.c b/src/xrt/state_trackers/prober/p_dump.c index de9c24967..feca050c0 100644 --- a/src/xrt/state_trackers/prober/p_dump.c +++ b/src/xrt/state_trackers/prober/p_dump.c @@ -35,23 +35,20 @@ print_ports(char *tmp, size_t size, uint8_t *ports, int num) return 1; } case 4: { - snprintf(tmp, size, "%i.%i.%i.%i", ports[0], ports[1], ports[2], - ports[3]); + snprintf(tmp, size, "%i.%i.%i.%i", ports[0], ports[1], ports[2], ports[3]); return 1; } case 5: { - snprintf(tmp, size, "%i.%i.%i.%i.%i", ports[0], ports[1], - ports[2], ports[3], ports[4]); + snprintf(tmp, size, "%i.%i.%i.%i.%i", ports[0], ports[1], ports[2], ports[3], ports[4]); return 1; } case 6: { - snprintf(tmp, size, "%i.%i.%i.%i.%i.%i", ports[0], ports[1], - ports[2], ports[3], ports[4], ports[5]); + snprintf(tmp, size, "%i.%i.%i.%i.%i.%i", ports[0], ports[1], ports[2], ports[3], ports[4], ports[5]); return 1; } case 7: { - snprintf(tmp, size, "%i.%i.%i.%i.%i.%i.%i", ports[0], ports[1], - ports[2], ports[3], ports[4], ports[5], ports[6]); + snprintf(tmp, size, "%i.%i.%i.%i.%i.%i.%i", ports[0], ports[1], ports[2], ports[3], ports[4], ports[5], + ports[6]); return 1; } default: return 0; @@ -70,19 +67,16 @@ p_dump_device(struct prober *p, struct prober_device *pdev, int id) { char tmp[1024]; - if (pdev->usb.bus != 0 && pdev->usb.addr == 0 && - pdev->base.vendor_id != 0 && pdev->base.product_id == 0) { + if (pdev->usb.bus != 0 && pdev->usb.addr == 0 && pdev->base.vendor_id != 0 && pdev->base.product_id == 0) { return; } - U_LOG_I("\t% 3i: 0x%04x:0x%04x", id, pdev->base.vendor_id, - pdev->base.product_id); + U_LOG_I("\t% 3i: 0x%04x:0x%04x", id, pdev->base.vendor_id, pdev->base.product_id); U_LOG_I("\t\tptr: %p", (void *)pdev); U_LOG_I("\t\tusb_dev_class: %02x", pdev->base.usb_dev_class); - if (pdev->usb.serial != NULL || pdev->usb.product != NULL || - pdev->usb.manufacturer != NULL) { + if (pdev->usb.serial != NULL || pdev->usb.product != NULL || pdev->usb.manufacturer != NULL) { U_LOG_I("\t\tusb.product: %s", pdev->usb.product); U_LOG_I("\t\tusb.manufacturer: %s", pdev->usb.manufacturer); U_LOG_I("\t\tusb.serial: %s", pdev->usb.serial); @@ -94,8 +88,7 @@ p_dump_device(struct prober *p, struct prober_device *pdev, int id) } if (pdev->bluetooth.id != 0) { - U_LOG_I("\t\tbluetooth.id: %012" PRIx64 "", - pdev->bluetooth.id); + U_LOG_I("\t\tbluetooth.id: %012" PRIx64 "", pdev->bluetooth.id); } int num = pdev->usb.num_ports; @@ -124,13 +117,11 @@ p_dump_device(struct prober *p, struct prober_device *pdev, int id) } if (desc->manufacturer != NULL) { - U_LOG_I("\t\tmanufacturer: '%s'", - desc->manufacturer); + U_LOG_I("\t\tmanufacturer: '%s'", desc->manufacturer); } if (desc->serialNumber != NULL) { - U_LOG_I("\t\tserial: '%s'", - desc->serialNumber); + U_LOG_I("\t\tserial: '%s'", desc->serialNumber); } uvc_free_device_descriptor(desc); diff --git a/src/xrt/state_trackers/prober/p_json.c b/src/xrt/state_trackers/prober/p_json.c index 64f8ae7ad..d220c3552 100644 --- a/src/xrt/state_trackers/prober/p_json.c +++ b/src/xrt/state_trackers/prober/p_json.c @@ -51,8 +51,7 @@ p_json_open_or_create_main_file(struct prober *p) { #ifdef XRT_OS_LINUX char tmp[1024]; - ssize_t ret = - u_file_get_path_in_config_dir("config_v0.json", tmp, sizeof(tmp)); + ssize_t ret = u_file_get_path_in_config_dir("config_v0.json", tmp, sizeof(tmp)); if (ret <= 0) { U_LOG_E( "Could not load or create config file no $HOME " @@ -167,9 +166,7 @@ is_json_ok(struct prober *p) } static bool -parse_active(const char *str, - const char *from, - enum p_active_config *out_active) +parse_active(const char *str, const char *from, enum p_active_config *out_active) { if (strcmp(str, "none") == 0) { *out_active = P_ACTIVE_CONFIG_NONE; @@ -195,8 +192,7 @@ p_json_get_active(struct prober *p, enum p_active_config *out_active) } char tmp[256]; - if (!is_json_ok(p) || - !get_obj_str(p->json.root, "active", tmp, sizeof(tmp))) { + if (!is_json_ok(p) || !get_obj_str(p->json.root, "active", tmp, sizeof(tmp))) { *out_active = P_ACTIVE_CONFIG_NONE; return; } @@ -262,12 +258,10 @@ p_json_get_tracking_settings(struct prober *p, struct xrt_settings_tracking *s) return false; } - bad |= !get_obj_str(t, "camera_name", s->camera_name, - sizeof(s->camera_name)); + bad |= !get_obj_str(t, "camera_name", s->camera_name, sizeof(s->camera_name)); bad |= !get_obj_int(t, "camera_mode", &s->camera_mode); bad |= !get_obj_str(t, "camera_type", tmp, sizeof(tmp)); - bad |= !get_obj_str(t, "calibration_path", s->calibration_path, - sizeof(s->calibration_path)); + bad |= !get_obj_str(t, "calibration_path", s->calibration_path, sizeof(s->calibration_path)); if (bad) { return false; } diff --git a/src/xrt/state_trackers/prober/p_libusb.c b/src/xrt/state_trackers/prober/p_libusb.c index 034545814..61165c878 100644 --- a/src/xrt/state_trackers/prober/p_libusb.c +++ b/src/xrt/state_trackers/prober/p_libusb.c @@ -66,8 +66,7 @@ p_libusb_probe(struct prober *p) uint16_t product = desc.idProduct; uint8_t ports[8]; - int num = - libusb_get_port_numbers(device, ports, ARRAY_SIZE(ports)); + int num = libusb_get_port_numbers(device, ports, ARRAY_SIZE(ports)); ret = p_dev_get_usb_dev(p, bus, addr, vendor, product, &pdev); @@ -95,7 +94,7 @@ p_libusb_probe(struct prober *p) return 0; } -#define ENUM_TO_STR(r) \ +#define ENUM_TO_STR(r) \ case r: return #r static const char * @@ -156,12 +155,10 @@ p_libusb_get_string_descriptor(struct prober *p, libusb_device_handle *dev_handle = NULL; result = libusb_open(usb_dev, &dev_handle); if (result < 0) { - P_ERROR(p, "libusb_open failed: %s", - p_libusb_error_to_string((enum libusb_error)result)); + P_ERROR(p, "libusb_open failed: %s", p_libusb_error_to_string((enum libusb_error)result)); return result; } - int string_length = libusb_get_string_descriptor_ascii( - dev_handle, which, buffer, length); + int string_length = libusb_get_string_descriptor_ascii(dev_handle, which, buffer, length); if (string_length < 0) { P_ERROR(p, "libusb_get_string_descriptor_ascii failed!"); } @@ -177,8 +174,7 @@ p_libusb_can_open(struct prober *p, struct prober_device *pdev) libusb_device_handle *dev_handle = NULL; result = libusb_open(usb_dev, &dev_handle); if (result < 0) { - P_ERROR(p, "libusb_open failed: %s", - p_libusb_error_to_string((enum libusb_error)result)); + P_ERROR(p, "libusb_open failed: %s", p_libusb_error_to_string((enum libusb_error)result)); return false; } diff --git a/src/xrt/state_trackers/prober/p_libuvc.c b/src/xrt/state_trackers/prober/p_libuvc.c index 0e1768a44..8641102ba 100644 --- a/src/xrt/state_trackers/prober/p_libuvc.c +++ b/src/xrt/state_trackers/prober/p_libuvc.c @@ -81,8 +81,8 @@ p_libuvc_probe(struct prober *p) "\t\tserial: %s\n" "\t\tmanuf: %s\n" "\t\tproduct: %s", - (void *)pdev, ret, vendor, product, bus, addr, - desc->serialNumber, desc->manufacturer, desc->product); + (void *)pdev, ret, vendor, product, bus, addr, desc->serialNumber, desc->manufacturer, + desc->product); uvc_free_device_descriptor(desc); diff --git a/src/xrt/state_trackers/prober/p_prober.c b/src/xrt/state_trackers/prober/p_prober.c index 05935cbb9..d0b73da1b 100644 --- a/src/xrt/state_trackers/prober/p_prober.c +++ b/src/xrt/state_trackers/prober/p_prober.c @@ -60,9 +60,7 @@ static int dump(struct xrt_prober *xp); static int -select_device(struct xrt_prober *xp, - struct xrt_device **xdevs, - size_t num_xdevs); +select_device(struct xrt_prober *xp, struct xrt_device **xdevs, size_t num_xdevs); static int open_hid_interface(struct xrt_prober *xp, @@ -77,9 +75,7 @@ open_video_device(struct xrt_prober *xp, struct xrt_fs **out_xfs); static int -list_video_devices(struct xrt_prober *xp, - xrt_prober_list_video_cb cb, - void *ptr); +list_video_devices(struct xrt_prober *xp, xrt_prober_list_video_cb cb, void *ptr); static int get_string_descriptor(struct xrt_prober *xp, struct xrt_prober_device *xpdev, @@ -101,8 +97,7 @@ destroy(struct xrt_prober **xp); */ int -xrt_prober_create_with_lists(struct xrt_prober **out_xp, - struct xrt_prober_entry_lists *lists) +xrt_prober_create_with_lists(struct xrt_prober **out_xp, struct xrt_prober_entry_lists *lists) { struct prober *p = U_TYPED_CALLOC(struct prober); @@ -117,7 +112,7 @@ xrt_prober_create_with_lists(struct xrt_prober **out_xp, return 0; } -#define ENUM_TO_STR(r) \ +#define ENUM_TO_STR(r) \ case r: return #r const char * @@ -170,20 +165,17 @@ p_dev_get_usb_dev(struct prober *p, for (size_t i = 0; i < p->num_devices; i++) { struct prober_device *pdev = &p->devices[i]; - if (pdev->base.bus != XRT_BUS_TYPE_USB || - pdev->usb.bus != bus || pdev->usb.addr != addr) { + if (pdev->base.bus != XRT_BUS_TYPE_USB || pdev->usb.bus != bus || pdev->usb.addr != addr) { continue; } - if (pdev->base.vendor_id != vendor_id || - pdev->base.product_id != product_id) { + if (pdev->base.vendor_id != vendor_id || pdev->base.product_id != product_id) { P_ERROR(p, "USB device with same address but different " "vendor and product found!\n" "\tvendor: %04x %04x\n" "\tproduct: %04x %04x", - pdev->base.vendor_id, vendor_id, - pdev->base.product_id, product_id); + pdev->base.vendor_id, vendor_id, pdev->base.product_id, product_id); continue; } @@ -203,31 +195,25 @@ p_dev_get_usb_dev(struct prober *p, } int -p_dev_get_bluetooth_dev(struct prober *p, - uint64_t id, - uint16_t vendor_id, - uint16_t product_id, - struct prober_device **out_pdev) +p_dev_get_bluetooth_dev( + struct prober *p, uint64_t id, uint16_t vendor_id, uint16_t product_id, struct prober_device **out_pdev) { struct prober_device *pdev; for (size_t i = 0; i < p->num_devices; i++) { struct prober_device *pdev = &p->devices[i]; - if (pdev->base.bus != XRT_BUS_TYPE_BLUETOOTH || - pdev->bluetooth.id != id) { + if (pdev->base.bus != XRT_BUS_TYPE_BLUETOOTH || pdev->bluetooth.id != id) { continue; } - if (pdev->base.vendor_id != vendor_id || - pdev->base.product_id != product_id) { + if (pdev->base.vendor_id != vendor_id || pdev->base.product_id != product_id) { P_ERROR(p, "Bluetooth device with same address but " "different vendor and product found!\n" "\tvendor: %04x %04x\n" "\tproduct: %04x %04x", - pdev->base.vendor_id, vendor_id, - pdev->base.product_id, product_id); + pdev->base.vendor_id, vendor_id, pdev->base.product_id, product_id); continue; } @@ -256,14 +242,13 @@ p_dev_get_bluetooth_dev(struct prober *p, static void fill_out_product(struct prober *p, struct prober_device *pdev) { - const char *bus = - pdev->base.bus == XRT_BUS_TYPE_BLUETOOTH ? "bluetooth" : "usb"; + const char *bus = pdev->base.bus == XRT_BUS_TYPE_BLUETOOTH ? "bluetooth" : "usb"; char *str = NULL; int ret = 0; do { - ret = snprintf(str, ret, "Unknown %s device: %04x:%04x", bus, - pdev->base.vendor_id, pdev->base.product_id); + ret = snprintf(str, ret, "Unknown %s device: %04x:%04x", bus, pdev->base.vendor_id, + pdev->base.product_id); if (ret <= 0) { return; } @@ -280,8 +265,7 @@ fill_out_product(struct prober *p, struct prober_device *pdev) static void add_device(struct prober *p, struct prober_device **out_dev) { - U_ARRAY_REALLOC_OR_FREE(p->devices, struct prober_device, - (p->num_devices + 1)); + U_ARRAY_REALLOC_OR_FREE(p->devices, struct prober_device, (p->num_devices + 1)); struct prober_device *dev = &p->devices[p->num_devices++]; U_ZERO(dev); @@ -292,8 +276,7 @@ add_device(struct prober *p, struct prober_device **out_dev) static void add_usb_entry(struct prober *p, struct xrt_prober_entry *entry) { - U_ARRAY_REALLOC_OR_FREE(p->entries, struct xrt_prober_entry *, - (p->num_entries + 1)); + U_ARRAY_REALLOC_OR_FREE(p->entries, struct xrt_prober_entry *, (p->num_entries + 1)); p->entries[p->num_entries++] = entry; } @@ -302,8 +285,7 @@ collect_entries(struct prober *p) { struct xrt_prober_entry_lists *lists = p->lists; while (lists) { - for (size_t j = 0; lists->entries != NULL && lists->entries[j]; - j++) { + for (size_t j = 0; lists->entries != NULL && lists->entries[j]; j++) { struct xrt_prober_entry *entry = lists->entries[j]; for (size_t k = 0; entry[k].found != NULL; k++) { add_usb_entry(p, &entry[k]); @@ -545,11 +527,8 @@ dump(struct xrt_prober *xp) } static void -handle_found_device(struct prober *p, - struct xrt_device **xdevs, - size_t num_xdevs, - bool *have_hmd, - struct xrt_device *xdev) +handle_found_device( + struct prober *p, struct xrt_device **xdevs, size_t num_xdevs, bool *have_hmd, struct xrt_device *xdev) { P_DEBUG(p, "Found '%s' %p", xdev->str, (void *)xdev); @@ -579,14 +558,10 @@ handle_found_device(struct prober *p, } static void -add_from_devices(struct prober *p, - struct xrt_device **xdevs, - size_t num_xdevs, - bool *have_hmd) +add_from_devices(struct prober *p, struct xrt_device **xdevs, size_t num_xdevs, bool *have_hmd) { // Build a list of all current probed devices. - struct xrt_prober_device **dev_list = - U_TYPED_ARRAY_CALLOC(struct xrt_prober_device *, p->num_devices); + struct xrt_prober_device **dev_list = U_TYPED_ARRAY_CALLOC(struct xrt_prober_device *, p->num_devices); for (size_t i = 0; i < p->num_devices; i++) { dev_list[i] = &p->devices[i].base; } @@ -597,34 +572,26 @@ add_from_devices(struct prober *p, for (size_t k = 0; k < p->num_entries; k++) { struct xrt_prober_entry *entry = p->entries[k]; - if (pdev->base.vendor_id != entry->vendor_id || - pdev->base.product_id != entry->product_id) { + if (pdev->base.vendor_id != entry->vendor_id || pdev->base.product_id != entry->product_id) { continue; } - struct xrt_device - *new_xdevs[XRT_MAX_DEVICES_PER_PROBE] = {NULL}; - int num_found = - entry->found(&p->base, dev_list, p->num_devices, i, - NULL, &(new_xdevs[0])); + struct xrt_device *new_xdevs[XRT_MAX_DEVICES_PER_PROBE] = {NULL}; + int num_found = entry->found(&p->base, dev_list, p->num_devices, i, NULL, &(new_xdevs[0])); if (num_found <= 0) { continue; } - for (int created_idx = 0; created_idx < num_found; - ++created_idx) { + for (int created_idx = 0; created_idx < num_found; ++created_idx) { if (new_xdevs[created_idx] == NULL) { - P_DEBUG( - p, - "Leaving device creation loop " - "early: found function reported %i " - "created, but only %i non-null", - num_found, created_idx); + P_DEBUG(p, + "Leaving device creation loop " + "early: found function reported %i " + "created, but only %i non-null", + num_found, created_idx); continue; } - handle_found_device(p, xdevs, num_xdevs, - have_hmd, - new_xdevs[created_idx]); + handle_found_device(p, xdevs, num_xdevs, have_hmd, new_xdevs[created_idx]); } } } @@ -634,10 +601,7 @@ add_from_devices(struct prober *p, } static void -add_from_auto_probers(struct prober *p, - struct xrt_device **xdevs, - size_t num_xdevs, - bool *have_hmd) +add_from_auto_probers(struct prober *p, struct xrt_device **xdevs, size_t num_xdevs, bool *have_hmd) { for (int i = 0; i < MAX_AUTO_PROBERS && p->auto_probers[i]; i++) { /* @@ -648,8 +612,7 @@ add_from_auto_probers(struct prober *p, bool no_hmds = *have_hmd; struct xrt_device *xdev = - p->auto_probers[i]->lelo_dallas_autoprobe( - p->auto_probers[i], NULL, no_hmds, &p->base); + p->auto_probers[i]->lelo_dallas_autoprobe(p->auto_probers[i], NULL, no_hmds, &p->base); if (xdev == NULL) { continue; } @@ -659,10 +622,7 @@ add_from_auto_probers(struct prober *p, } static void -add_from_remote(struct prober *p, - struct xrt_device **xdevs, - size_t num_xdevs, - bool *have_hmd) +add_from_remote(struct prober *p, struct xrt_device **xdevs, size_t num_xdevs, bool *have_hmd) { if (num_xdevs < 3) { return; @@ -680,9 +640,7 @@ add_from_remote(struct prober *p, } static int -select_device(struct xrt_prober *xp, - struct xrt_device **xdevs, - size_t num_xdevs) +select_device(struct xrt_prober *xp, struct xrt_device **xdevs, size_t num_xdevs) { struct prober *p = (struct prober *)xp; enum p_active_config active; @@ -696,9 +654,7 @@ select_device(struct xrt_prober *xp, add_from_devices(p, xdevs, num_xdevs, &have_hmd); add_from_auto_probers(p, xdevs, num_xdevs, &have_hmd); break; - case P_ACTIVE_CONFIG_REMOTE: - add_from_remote(p, xdevs, num_xdevs, &have_hmd); - break; + case P_ACTIVE_CONFIG_REMOTE: add_from_remote(p, xdevs, num_xdevs, &have_hmd); break; default: assert(false); } @@ -761,8 +717,7 @@ open_hid_interface(struct xrt_prober *xp, ret = os_hid_open_hidraw(hidraw->path, out_hid_dev); if (ret != 0) { - U_LOG_E("Failed to open device '%s' got '%i'", - hidraw->path, ret); + U_LOG_E("Failed to open device '%s' got '%i'", hidraw->path, ret); return ret; } @@ -785,8 +740,7 @@ open_video_device(struct xrt_prober *xp, struct xrt_frame_context *xfctx, struct xrt_fs **out_xfs) { - XRT_MAYBE_UNUSED struct prober_device *pdev = - (struct prober_device *)xpdev; + XRT_MAYBE_UNUSED struct prober_device *pdev = (struct prober_device *)xpdev; #if defined(XRT_HAVE_VF) const char *path = debug_get_option_vf_path(); @@ -817,9 +771,7 @@ open_video_device(struct xrt_prober *xp, } static int -list_video_devices(struct xrt_prober *xp, - xrt_prober_list_video_cb cb, - void *ptr) +list_video_devices(struct xrt_prober *xp, xrt_prober_list_video_cb cb, void *ptr) { struct prober *p = (struct prober *)xp; @@ -848,8 +800,7 @@ list_video_devices(struct xrt_prober *xp, fill_out_product(p, pdev); } - cb(xp, &pdev->base, pdev->usb.product, pdev->usb.manufacturer, - pdev->usb.serial, ptr); + cb(xp, &pdev->base, pdev->usb.product, pdev->usb.manufacturer, pdev->usb.serial, ptr); } return 0; @@ -863,13 +814,11 @@ get_string_descriptor(struct xrt_prober *xp, int length) { XRT_MAYBE_UNUSED struct prober *p = (struct prober *)xp; - XRT_MAYBE_UNUSED struct prober_device *pdev = - (struct prober_device *)xpdev; + XRT_MAYBE_UNUSED struct prober_device *pdev = (struct prober_device *)xpdev; XRT_MAYBE_UNUSED int ret; #ifdef XRT_HAVE_LIBUSB if (pdev->usb.dev != NULL) { - ret = p_libusb_get_string_descriptor(p, pdev, which_string, - buffer, length); + ret = p_libusb_get_string_descriptor(p, pdev, which_string, buffer, length); if (ret >= 0) { return ret; } @@ -884,8 +833,7 @@ static bool can_open(struct xrt_prober *xp, struct xrt_prober_device *xpdev) { XRT_MAYBE_UNUSED struct prober *p = (struct prober *)xp; - XRT_MAYBE_UNUSED struct prober_device *pdev = - (struct prober_device *)xpdev; + XRT_MAYBE_UNUSED struct prober_device *pdev = (struct prober_device *)xpdev; #ifdef XRT_HAVE_LIBUSB if (pdev->usb.dev != NULL) { return p_libusb_can_open(p, pdev); diff --git a/src/xrt/state_trackers/prober/p_prober.h b/src/xrt/state_trackers/prober/p_prober.h index 1259b1cd5..4c3547714 100644 --- a/src/xrt/state_trackers/prober/p_prober.h +++ b/src/xrt/state_trackers/prober/p_prober.h @@ -238,11 +238,8 @@ p_dev_get_usb_dev(struct prober *p, * @public @memberof prober */ int -p_dev_get_bluetooth_dev(struct prober *p, - uint64_t id, - uint16_t vendor_id, - uint16_t product_id, - struct prober_device **out_pdev); +p_dev_get_bluetooth_dev( + struct prober *p, uint64_t id, uint16_t vendor_id, uint16_t product_id, struct prober_device **out_pdev); /*! * @name Tracking systems diff --git a/src/xrt/state_trackers/prober/p_tracking.c b/src/xrt/state_trackers/prober/p_tracking.c index c5c2532c4..a6479dbf5 100644 --- a/src/xrt/state_trackers/prober/p_tracking.c +++ b/src/xrt/state_trackers/prober/p_tracking.c @@ -111,13 +111,11 @@ on_video_device(struct xrt_prober *xp, return; } - if (strcmp(product, fact->settings.camera_name) != 0 && - strcmp(product, "Video File") != 0) { + if (strcmp(product, fact->settings.camera_name) != 0 && strcmp(product, "Video File") != 0) { return; } - xrt_prober_open_video_device(&fact->p->base, pdev, &fact->xfctx, - &fact->xfs); + xrt_prober_open_video_device(&fact->p->base, pdev, &fact->xfctx, &fact->xfs); } static void @@ -225,8 +223,7 @@ p_factory_ensure_frameserver(struct p_factory *fact) u_sink_quirk_create(&fact->xfctx, xsink, &qp, &xsink); // Start the stream now. - xrt_fs_stream_start(fact->xfs, xsink, XRT_FS_CAPTURE_TYPE_TRACKING, - fact->settings.camera_mode); + xrt_fs_stream_start(fact->xfs, xsink, XRT_FS_CAPTURE_TYPE_TRACKING, fact->settings.camera_mode); } #endif @@ -349,8 +346,7 @@ p_tracking_init(struct prober *p) fact->origin.offset.position.y = 1.0f; fact->p = p; - snprintf(fact->origin.name, sizeof(fact->origin.name), - "PSVR & PSMV tracking"); + snprintf(fact->origin.name, sizeof(fact->origin.name), "PSVR & PSMV tracking"); u_var_add_root(fact, "Tracking Factory", false); u_var_add_pose(fact, &fact->origin.offset, "offset"); diff --git a/src/xrt/state_trackers/prober/p_udev.c b/src/xrt/state_trackers/prober/p_udev.c index d500a10a0..4167e8fbf 100644 --- a/src/xrt/state_trackers/prober/p_udev.c +++ b/src/xrt/state_trackers/prober/p_udev.c @@ -49,22 +49,16 @@ static void p_udev_enumerate_v4l2(struct prober *p, struct udev *udev); static void -p_udev_add_v4l(struct prober_device *pdev, - uint32_t v4l_index, - uint32_t usb_iface, - const char *path); +p_udev_add_v4l(struct prober_device *pdev, uint32_t v4l_index, uint32_t usb_iface, const char *path); static void p_udev_enumerate_hidraw(struct prober *p, struct udev *udev); static void -p_udev_add_hidraw(struct prober_device *pdev, - uint32_t interface, - const char *path); +p_udev_add_hidraw(struct prober_device *pdev, uint32_t interface, const char *path); static int -p_udev_get_interface_number(struct udev_device *raw_dev, - uint16_t *interface_number); +p_udev_get_interface_number(struct udev_device *raw_dev, uint16_t *interface_number); static int p_udev_get_and_parse_uevent(struct udev_device *raw_dev, @@ -90,9 +84,7 @@ p_udev_try_usb_relation_get_address(struct udev_device *raw_dev, struct udev_device **out_usb_device); static int -p_udev_get_vendor_id_product(struct udev_device *usb_device_dev, - uint16_t *vendor_id, - uint16_t *product_id); +p_udev_get_vendor_id_product(struct udev_device *usb_device_dev, uint16_t *vendor_id, uint16_t *product_id); static int p_udev_get_usb_device_info(struct udev_device *usb_device_dev, @@ -103,24 +95,16 @@ p_udev_get_usb_device_info(struct udev_device *usb_device_dev, uint16_t *usb_addr); static int -p_udev_get_usb_device_address_path(struct udev_device *usb_dev, - uint16_t *out_usb_bus, - uint16_t *out_usb_addr); +p_udev_get_usb_device_address_path(struct udev_device *usb_dev, uint16_t *out_usb_bus, uint16_t *out_usb_addr); static int -p_udev_get_usb_device_address_sysfs(struct udev_device *usb_dev, - uint16_t *out_usb_bus, - uint16_t *out_usb_addr); +p_udev_get_usb_device_address_sysfs(struct udev_device *usb_dev, uint16_t *out_usb_bus, uint16_t *out_usb_addr); static int -p_udev_get_sysattr_u16_base16(struct udev_device *dev, - const char *name, - uint16_t *out_value); +p_udev_get_sysattr_u16_base16(struct udev_device *dev, const char *name, uint16_t *out_value); static int -p_udev_get_sysattr_u32_base10(struct udev_device *dev, - const char *name, - uint32_t *out_value); +p_udev_get_sysattr_u32_base10(struct udev_device *dev, const char *name, uint32_t *out_value); XRT_MAYBE_UNUSED static void p_udev_dump_device(struct udev_device *udev_dev, const char *name); @@ -198,20 +182,16 @@ p_udev_enumerate_usb(struct prober *p, struct udev *udev) // Product name. product = udev_device_get_sysattr_value(raw_dev, "product"); // Manufacturer name. - manufacturer = - udev_device_get_sysattr_value(raw_dev, "manufacturer"); + manufacturer = udev_device_get_sysattr_value(raw_dev, "manufacturer"); - ret = p_udev_get_usb_device_info(raw_dev, &dev_class, - &vendor_id, &product_id, - &usb_bus, &usb_addr); + ret = p_udev_get_usb_device_info(raw_dev, &dev_class, &vendor_id, &product_id, &usb_bus, &usb_addr); if (ret != 0) { P_ERROR(p, "Failed to get usb device info"); goto next; } - ret = p_dev_get_usb_dev(p, usb_bus, usb_addr, vendor_id, - product_id, &pdev); + ret = p_dev_get_usb_dev(p, usb_bus, usb_addr, vendor_id, product_id, &pdev); P_TRACE(p, "usb\n" @@ -226,9 +206,8 @@ p_udev_enumerate_usb(struct prober *p, struct udev *udev) "\t\tserial: '%s'\n" "\t\tproduct: '%s'\n" "\t\tmanufacturer: '%s'", - (void *)pdev, ret, sysfs_path, dev_path, dev_class, - vendor_id, product_id, usb_bus, usb_addr, serial, - product, manufacturer); + (void *)pdev, ret, sysfs_path, dev_path, dev_class, vendor_id, product_id, usb_bus, usb_addr, + serial, product, manufacturer); if (ret != 0) { P_ERROR(p, "p_dev_get_usb_device failed!"); @@ -236,8 +215,7 @@ p_udev_enumerate_usb(struct prober *p, struct udev *udev) } // Add info to usb device. - p_udev_add_usb(pdev, dev_class, product, manufacturer, serial, - dev_path); + p_udev_add_usb(pdev, dev_class, product, manufacturer, serial, dev_path); next: udev_device_unref(raw_dev); @@ -308,12 +286,10 @@ p_udev_enumerate_v4l2(struct prober *p, struct udev *udev) // The thing we will open. dev_path = udev_device_get_devnode(raw_dev); - ret = p_udev_try_usb_relation_get_address( - raw_dev, &dev_class, &vendor_id, &product_id, &usb_bus, - &usb_addr, &usb_device); + ret = p_udev_try_usb_relation_get_address(raw_dev, &dev_class, &vendor_id, &product_id, &usb_bus, + &usb_addr, &usb_device); if (ret != 0) { - P_DEBUG(p, "skipping non-usb v4l device '%s'", - dev_path); + P_DEBUG(p, "skipping non-usb v4l device '%s'", dev_path); goto next; } @@ -322,8 +298,7 @@ p_udev_enumerate_v4l2(struct prober *p, struct udev *udev) // Product name. product = udev_device_get_sysattr_value(usb_device, "product"); // Manufacturer name. - manufacturer = - udev_device_get_sysattr_value(usb_device, "manufacturer"); + manufacturer = udev_device_get_sysattr_value(usb_device, "manufacturer"); // USB interface. ret = p_udev_get_interface_number(raw_dev, &usb_iface); @@ -336,15 +311,13 @@ p_udev_enumerate_v4l2(struct prober *p, struct udev *udev) } // USB interface. - ret = - p_udev_get_sysattr_u32_base10(raw_dev, "index", &v4l_index); + ret = p_udev_get_sysattr_u32_base10(raw_dev, "index", &v4l_index); if (ret != 0) { P_ERROR(p, "Failed to get v4l index."); goto next; } - ret = p_dev_get_usb_dev(p, usb_bus, usb_addr, vendor_id, - product_id, &pdev); + ret = p_dev_get_usb_dev(p, usb_bus, usb_addr, vendor_id, product_id, &pdev); P_TRACE(p, "v4l\n" @@ -360,9 +333,8 @@ p_udev_enumerate_v4l2(struct prober *p, struct udev *udev) "\t\tserial: '%s'\n" "\t\tproduct: '%s'\n" "\t\tmanufacturer: '%s'", - (void *)pdev, ret, sysfs_path, dev_path, vendor_id, - product_id, v4l_index, usb_iface, usb_bus, usb_addr, - serial, product, manufacturer); + (void *)pdev, ret, sysfs_path, dev_path, vendor_id, product_id, v4l_index, usb_iface, usb_bus, + usb_addr, serial, product, manufacturer); if (ret != 0) { P_ERROR(p, "p_dev_get_usb_device failed!"); @@ -380,14 +352,10 @@ p_udev_enumerate_v4l2(struct prober *p, struct udev *udev) } static void -p_udev_add_v4l(struct prober_device *pdev, - uint32_t v4l_index, - uint32_t usb_iface, - const char *path) +p_udev_add_v4l(struct prober_device *pdev, uint32_t v4l_index, uint32_t usb_iface, const char *path) { #ifdef XRT_HAVE_V4L2 - U_ARRAY_REALLOC_OR_FREE(pdev->v4ls, struct prober_v4l, - (pdev->num_v4ls + 1)); + U_ARRAY_REALLOC_OR_FREE(pdev->v4ls, struct prober_v4l, (pdev->num_v4ls + 1)); struct prober_v4l *v4l = &pdev->v4ls[pdev->num_v4ls++]; U_ZERO(v4l); @@ -432,16 +400,14 @@ p_udev_enumerate_hidraw(struct prober *p, struct udev *udev) dev_path = udev_device_get_devnode(raw_dev); // Bus type, vendor_id and product_id. - ret = p_udev_get_and_parse_uevent( - raw_dev, &bus_type, &vendor_id, &product_id, &bluetooth_id); + ret = p_udev_get_and_parse_uevent(raw_dev, &bus_type, &vendor_id, &product_id, &bluetooth_id); if (ret != 0) { P_ERROR(p, "Failed to get uevent info from device"); goto next; } // Get USB bus and address to de-duplicate devices. - ret = p_udev_get_usb_hid_address(raw_dev, bus_type, &dev_class, - &usb_bus, &usb_addr); + ret = p_udev_get_usb_hid_address(raw_dev, bus_type, &dev_class, &usb_bus, &usb_addr); if (ret != 0) { P_ERROR(p, "Failed to get USB bus and addr."); goto next; @@ -451,10 +417,7 @@ p_udev_enumerate_hidraw(struct prober *p, struct udev *udev) case HIDRAW_BUS_BLUETOOTH: case HIDRAW_BUS_USB: break; case HIDRAW_BUS_I2C_MAYBE_QUESTION_MARK: goto next; - default: - P_ERROR(p, "Unknown hidraw bus_type: '%i', ignoring.", - bus_type); - goto next; + default: P_ERROR(p, "Unknown hidraw bus_type: '%i', ignoring.", bus_type); goto next; } // HID interface. @@ -468,11 +431,9 @@ p_udev_enumerate_hidraw(struct prober *p, struct udev *udev) } if (bus_type == HIDRAW_BUS_BLUETOOTH) { - ret = p_dev_get_bluetooth_dev( - p, bluetooth_id, vendor_id, product_id, &pdev); + ret = p_dev_get_bluetooth_dev(p, bluetooth_id, vendor_id, product_id, &pdev); } else if (bus_type == HIDRAW_BUS_USB) { - ret = p_dev_get_usb_dev(p, usb_bus, usb_addr, vendor_id, - product_id, &pdev); + ret = p_dev_get_usb_dev(p, usb_bus, usb_addr, vendor_id, product_id, &pdev); } else { // Right now only support USB & Bluetooth devices. P_ERROR(p, @@ -494,9 +455,8 @@ p_udev_enumerate_hidraw(struct prober *p, struct udev *udev) "\t\tusb_bus: %i\n" "\t\tusb_addr: %i\n" "\t\tbluetooth_id: %012" PRIx64, - (void *)pdev, ret, sysfs_path, dev_path, bus_type, - vendor_id, product_id, interface, usb_bus, usb_addr, - bluetooth_id); + (void *)pdev, ret, sysfs_path, dev_path, bus_type, vendor_id, product_id, interface, usb_bus, + usb_addr, bluetooth_id); if (ret != 0) { P_ERROR(p, "p_dev_get_usb_device failed!"); @@ -514,12 +474,9 @@ p_udev_enumerate_hidraw(struct prober *p, struct udev *udev) } static void -p_udev_add_hidraw(struct prober_device *pdev, - uint32_t interface, - const char *path) +p_udev_add_hidraw(struct prober_device *pdev, uint32_t interface, const char *path) { - U_ARRAY_REALLOC_OR_FREE(pdev->hidraws, struct prober_hidraw, - (pdev->num_hidraws + 1)); + U_ARRAY_REALLOC_OR_FREE(pdev->hidraws, struct prober_hidraw, (pdev->num_hidraws + 1)); struct prober_hidraw *hidraw = &pdev->hidraws[pdev->num_hidraws++]; U_ZERO(hidraw); @@ -544,14 +501,12 @@ p_udev_get_usb_hid_address(struct udev_device *raw_dev, // Get the first USB device parent. // No we should not unref intf_dev, valgrind agrees. - usb_dev = udev_device_get_parent_with_subsystem_devtype(raw_dev, "usb", - "usb_device"); + usb_dev = udev_device_get_parent_with_subsystem_devtype(raw_dev, "usb", "usb_device"); if (usb_dev == NULL) { return -1; } - return p_udev_get_usb_device_info(usb_dev, out_dev_class, &dummy_vendor, - &dummy_product, out_usb_bus, + return p_udev_get_usb_device_info(usb_dev, out_dev_class, &dummy_vendor, &dummy_product, out_usb_bus, out_usb_addr); } @@ -563,8 +518,7 @@ p_udev_get_interface_number(struct udev_device *raw_dev, uint16_t *interface) // Make udev find the handle to the interface node. // No we should not unref intf_dev, valgrind agrees. - intf_dev = udev_device_get_parent_with_subsystem_devtype( - raw_dev, "usb", "usb_interface"); + intf_dev = udev_device_get_parent_with_subsystem_devtype(raw_dev, "usb", "usb_interface"); if (intf_dev == NULL) { return -1; } @@ -598,8 +552,7 @@ p_udev_get_and_parse_uevent(struct udev_device *raw_dev, int ret; // Dig through and find the regular hid node. - hid_dev = - udev_device_get_parent_with_subsystem_devtype(raw_dev, "hid", NULL); + hid_dev = udev_device_get_parent_with_subsystem_devtype(raw_dev, "hid", NULL); if (hid_dev == NULL) { return -1; } @@ -618,8 +571,7 @@ p_udev_get_and_parse_uevent(struct udev_device *raw_dev, line = strtok_r(tmp, "\n", &saveptr); while (line != NULL) { if (strncmp(line, "HID_ID=", 7) == 0) { - ret = sscanf(line + 7, "%x:%hx:%hx", &bus_type, - &vendor_id, &product_id); + ret = sscanf(line + 7, "%x:%hx:%hx", &bus_type, &vendor_id, &product_id); if (ret == 3) { ok = true; } @@ -639,9 +591,8 @@ p_udev_get_and_parse_uevent(struct udev_device *raw_dev, uint64_t v; } extract = {{0}}; - ret = sscanf(serial_utf8, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", - &extract.arr[5], &extract.arr[4], &extract.arr[3], - &extract.arr[2], &extract.arr[1], &extract.arr[0]); + ret = sscanf(serial_utf8, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &extract.arr[5], &extract.arr[4], + &extract.arr[3], &extract.arr[2], &extract.arr[1], &extract.arr[0]); if (ret == 6) { bluetooth_serial = extract.v; } @@ -671,10 +622,8 @@ p_udev_try_usb_relation_get_address(struct udev_device *raw_dev, struct udev_device *parent_dev, *usb_interface, *usb_device; parent_dev = udev_device_get_parent(raw_dev); - usb_interface = udev_device_get_parent_with_subsystem_devtype( - raw_dev, "usb", "usb_interface"); - usb_device = udev_device_get_parent_with_subsystem_devtype( - raw_dev, "usb", "usb_device"); + usb_interface = udev_device_get_parent_with_subsystem_devtype(raw_dev, "usb", "usb_interface"); + usb_device = udev_device_get_parent_with_subsystem_devtype(raw_dev, "usb", "usb_device"); // Huh, device has no direct parent? if (parent_dev == NULL) { @@ -694,9 +643,8 @@ p_udev_try_usb_relation_get_address(struct udev_device *raw_dev, return -1; } - int ret = p_udev_get_usb_device_info(usb_device, out_dev_class, - out_vendor_id, out_product_id, - out_usb_bus, out_usb_addr); + int ret = p_udev_get_usb_device_info(usb_device, out_dev_class, out_vendor_id, out_product_id, out_usb_bus, + out_usb_addr); if (ret != 0) { return ret; } @@ -707,9 +655,7 @@ p_udev_try_usb_relation_get_address(struct udev_device *raw_dev, } static int -p_udev_get_vendor_id_product(struct udev_device *usb_dev, - uint16_t *out_vendor_id, - uint16_t *out_product_id) +p_udev_get_vendor_id_product(struct udev_device *usb_dev, uint16_t *out_vendor_id, uint16_t *out_product_id) { uint16_t vendor_id, product_id; int ret; @@ -747,15 +693,13 @@ p_udev_get_usb_device_info(struct udev_device *usb_dev, return ret; } - ret = - p_udev_get_sysattr_u16_base16(usb_dev, "bDeviceClass", &dev_class); + ret = p_udev_get_sysattr_u16_base16(usb_dev, "bDeviceClass", &dev_class); if (ret != 0) { return ret; } // We emulate what libusb does with regards to device bus and address. - if (p_udev_get_usb_device_address_path(usb_dev, out_usb_bus, - out_usb_addr) == 0) { + if (p_udev_get_usb_device_address_path(usb_dev, out_usb_bus, out_usb_addr) == 0) { *out_dev_class = (uint8_t)dev_class; *out_vendor_id = vendor_id; *out_product_id = product_id; @@ -763,8 +707,7 @@ p_udev_get_usb_device_info(struct udev_device *usb_dev, } // If for some reason we can't read the dev path fallback to sysfs. - if (p_udev_get_usb_device_address_sysfs(usb_dev, out_usb_bus, - out_usb_addr) == 0) { + if (p_udev_get_usb_device_address_sysfs(usb_dev, out_usb_bus, out_usb_addr) == 0) { *out_dev_class = (uint8_t)dev_class; *out_vendor_id = vendor_id; *out_product_id = product_id; @@ -775,9 +718,7 @@ p_udev_get_usb_device_info(struct udev_device *usb_dev, } static int -p_udev_get_usb_device_address_path(struct udev_device *usb_dev, - uint16_t *out_usb_bus, - uint16_t *out_usb_addr) +p_udev_get_usb_device_address_path(struct udev_device *usb_dev, uint16_t *out_usb_bus, uint16_t *out_usb_addr) { uint16_t bus = 0, addr = 0; @@ -798,9 +739,7 @@ p_udev_get_usb_device_address_path(struct udev_device *usb_dev, } static int -p_udev_get_usb_device_address_sysfs(struct udev_device *usb_dev, - uint16_t *out_usb_bus, - uint16_t *out_usb_addr) +p_udev_get_usb_device_address_sysfs(struct udev_device *usb_dev, uint16_t *out_usb_bus, uint16_t *out_usb_addr) { uint16_t usb_bus = 0, usb_addr = 0; int ret; @@ -822,9 +761,7 @@ p_udev_get_usb_device_address_sysfs(struct udev_device *usb_dev, } static int -p_udev_get_sysattr_u16_base16(struct udev_device *dev, - const char *name, - uint16_t *out_value) +p_udev_get_sysattr_u16_base16(struct udev_device *dev, const char *name, uint16_t *out_value) { const char *str = udev_device_get_sysattr_value(dev, name); if (str == NULL) { @@ -837,9 +774,7 @@ p_udev_get_sysattr_u16_base16(struct udev_device *dev, } static int -p_udev_get_sysattr_u32_base10(struct udev_device *dev, - const char *name, - uint32_t *out_value) +p_udev_get_sysattr_u32_base10(struct udev_device *dev, const char *name, uint32_t *out_value) { const char *str = udev_device_get_sysattr_value(dev, name); if (str == NULL) { @@ -869,6 +804,5 @@ p_udev_dump_device(struct udev_device *udev_dev, const char *name) U_LOG_I("\t\tsysnum: %s", udev_device_get_sysnum(udev_dev)); U_LOG_I("\t\tsyspath: %s", udev_device_get_syspath(udev_dev)); U_LOG_I("\t\tsubsystem: %s", udev_device_get_subsystem(udev_dev)); - U_LOG_I("\t\tsysfs.product: %s", - udev_device_get_sysattr_value(udev_dev, "product")); + U_LOG_I("\t\tsysfs.product: %s", udev_device_get_sysattr_value(udev_dev, "product")); } diff --git a/src/xrt/state_trackers/steamvr_drv/ovrd_driver.cpp b/src/xrt/state_trackers/steamvr_drv/ovrd_driver.cpp index b9df633ff..84954050c 100644 --- a/src/xrt/state_trackers/steamvr_drv/ovrd_driver.cpp +++ b/src/xrt/state_trackers/steamvr_drv/ovrd_driver.cpp @@ -36,13 +36,9 @@ extern "C" { //! When set, all controllers pretend to be Index controllers. Provides best //! compatibility with legacy games due to steamvr's legacy binding for Index //! controllers, but input mapping may be incomplete or not ideal. -DEBUG_GET_ONCE_BOOL_OPTION(emulate_index_controller, - "STEAMVR_EMULATE_INDEX_CONTROLLER", - true) +DEBUG_GET_ONCE_BOOL_OPTION(emulate_index_controller, "STEAMVR_EMULATE_INDEX_CONTROLLER", true) -DEBUG_GET_ONCE_NUM_OPTION(scale_percentage, - "XRT_COMPOSITOR_SCALE_PERCENTAGE", - 140) +DEBUG_GET_ONCE_NUM_OPTION(scale_percentage, "XRT_COMPOSITOR_SCALE_PERCENTAGE", 140) //#define DUMP_POSE //#define DUMP_POSE_CONTROLLERS @@ -88,36 +84,31 @@ copy_quat(struct xrt_quat *from, vr::HmdQuaternion_t *to) static void apply_pose(struct xrt_space_relation *rel, vr::DriverPose_t *m_pose) { - if ((rel->relation_flags & - XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT) != 0) { + if ((rel->relation_flags & XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT) != 0) { copy_quat(&rel->pose.orientation, &m_pose->qRotation); } else { m_pose->result = vr::TrackingResult_Running_OutOfRange; m_pose->poseIsValid = false; } - if ((rel->relation_flags & XRT_SPACE_RELATION_POSITION_TRACKED_BIT) != - 0) { + if ((rel->relation_flags & XRT_SPACE_RELATION_POSITION_TRACKED_BIT) != 0) { copy_vec3(&rel->pose.position, m_pose->vecPosition); } else { } - if ((rel->relation_flags & - XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT) != 0) { + if ((rel->relation_flags & XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT) != 0) { // linear velocity in world space copy_vec3(&rel->linear_velocity, m_pose->vecVelocity); } - if ((rel->relation_flags & - XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT) != 0) { + if ((rel->relation_flags & XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT) != 0) { // angular velocity reported by monado in world space, // expected by steamvr to be in "controller space" struct xrt_quat orientation_inv; math_quat_invert(&rel->pose.orientation, &orientation_inv); struct xrt_vec3 vel; - math_quat_rotate_derivative(&orientation_inv, - &rel->angular_velocity, &vel); + math_quat_rotate_derivative(&orientation_inv, &rel->angular_velocity, &vel); copy_vec3(&vel, m_pose->vecAngularVelocity); } @@ -126,17 +117,14 @@ apply_pose(struct xrt_space_relation *rel, vr::DriverPose_t *m_pose) class CDeviceDriver_Monado_Controller : public vr::ITrackedDeviceServerDriver { public: - CDeviceDriver_Monado_Controller(struct xrt_instance *xinst, - struct xrt_device *xdev, - enum xrt_hand hand) + CDeviceDriver_Monado_Controller(struct xrt_instance *xinst, struct xrt_device *xdev, enum xrt_hand hand) : m_xdev(xdev), m_hand(hand) { ovrd_log("Creating Controller %s\n", xdev->str); m_handed_controller = true; - m_emulate_index_controller = - debug_get_bool_option_emulate_index_controller(); + m_emulate_index_controller = debug_get_bool_option_emulate_index_controller(); if (m_emulate_index_controller) { ovrd_log("Emulating Index Controller\n"); @@ -168,13 +156,9 @@ public: "right"; } break; - case XRT_DEVICE_VIVE_WAND: - m_render_model = "vr_controller_vive_1_5"; - break; + case XRT_DEVICE_VIVE_WAND: m_render_model = "vr_controller_vive_1_5"; break; case XRT_DEVICE_VIVE_TRACKER_GEN1: - case XRT_DEVICE_VIVE_TRACKER_GEN2: - m_render_model = "{htc}vr_tracker_vive_1_0"; - break; + case XRT_DEVICE_VIVE_TRACKER_GEN2: m_render_model = "{htc}vr_tracker_vive_1_0"; break; case XRT_DEVICE_PSMV: case XRT_DEVICE_HYDRA: case XRT_DEVICE_DAYDREAM: @@ -192,47 +176,33 @@ public: enum xrt_input_name monado_input_name, struct MonadoInputComponent *component) { - m_controls[m_control_count].monado_input_type = - monado_input_type; - m_controls[m_control_count].steamvr_control_path = - steamvr_control_path; - m_controls[m_control_count].monado_input_name = - monado_input_name; + m_controls[m_control_count].monado_input_type = monado_input_type; + m_controls[m_control_count].steamvr_control_path = steamvr_control_path; + m_controls[m_control_count].monado_input_name = monado_input_name; if (component != NULL) { m_controls[m_control_count].component = *component; } else { - m_controls[m_control_count].component.has_component = - false; + m_controls[m_control_count].component.has_component = false; } if (monado_input_type == XRT_INPUT_TYPE_BOOLEAN) { - vr::VRDriverInput()->CreateBooleanComponent( - m_ulPropertyContainer, steamvr_control_path, - &m_controls[m_control_count].control_handle); + vr::VRDriverInput()->CreateBooleanComponent(m_ulPropertyContainer, steamvr_control_path, + &m_controls[m_control_count].control_handle); - } else if (monado_input_type == - XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE) { + } else if (monado_input_type == XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE) { vr::VRDriverInput()->CreateScalarComponent( - m_ulPropertyContainer, steamvr_control_path, - &m_controls[m_control_count].control_handle, - vr::VRScalarType_Absolute, - vr::VRScalarUnits_NormalizedTwoSided); + m_ulPropertyContainer, steamvr_control_path, &m_controls[m_control_count].control_handle, + vr::VRScalarType_Absolute, vr::VRScalarUnits_NormalizedTwoSided); - } else if (monado_input_type == - XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE) { + } else if (monado_input_type == XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE) { vr::VRDriverInput()->CreateScalarComponent( - m_ulPropertyContainer, steamvr_control_path, - &m_controls[m_control_count].control_handle, - vr::VRScalarType_Absolute, - vr::VRScalarUnits_NormalizedOneSided); + m_ulPropertyContainer, steamvr_control_path, &m_controls[m_control_count].control_handle, + vr::VRScalarType_Absolute, vr::VRScalarUnits_NormalizedOneSided); - } else if (monado_input_type == - XRT_INPUT_TYPE_VEC2_MINUS_ONE_TO_ONE) { + } else if (monado_input_type == XRT_INPUT_TYPE_VEC2_MINUS_ONE_TO_ONE) { vr::VRDriverInput()->CreateScalarComponent( - m_ulPropertyContainer, steamvr_control_path, - &m_controls[m_control_count].control_handle, - vr::VRScalarType_Absolute, - vr::VRScalarUnits_NormalizedTwoSided); + m_ulPropertyContainer, steamvr_control_path, &m_controls[m_control_count].control_handle, + vr::VRScalarType_Absolute, vr::VRScalarUnits_NormalizedTwoSided); } ovrd_log("Added input %s\n", steamvr_control_path); @@ -244,150 +214,107 @@ public: { switch (this->m_xdev->name) { case XRT_DEVICE_INDEX_CONTROLLER: { - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/trigger/value", + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/trigger/value", XRT_INPUT_INDEX_TRIGGER_VALUE, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/trigger/click", - XRT_INPUT_INDEX_TRIGGER_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/trigger/touch", - XRT_INPUT_INDEX_TRIGGER_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/trigger/click", XRT_INPUT_INDEX_TRIGGER_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/trigger/touch", XRT_INPUT_INDEX_TRIGGER_TOUCH, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/system/click", - XRT_INPUT_INDEX_SYSTEM_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/system/touch", - XRT_INPUT_INDEX_SYSTEM_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/system/click", XRT_INPUT_INDEX_SYSTEM_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/system/touch", XRT_INPUT_INDEX_SYSTEM_TOUCH, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/click", - XRT_INPUT_INDEX_A_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/touch", - XRT_INPUT_INDEX_A_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/click", XRT_INPUT_INDEX_A_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/touch", XRT_INPUT_INDEX_A_TOUCH, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/click", - XRT_INPUT_INDEX_B_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/touch", - XRT_INPUT_INDEX_B_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/click", XRT_INPUT_INDEX_B_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/touch", XRT_INPUT_INDEX_B_TOUCH, NULL); - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/grip/force", - XRT_INPUT_INDEX_SQUEEZE_FORCE, NULL); + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/grip/force", XRT_INPUT_INDEX_SQUEEZE_FORCE, + NULL); - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/grip/value", - XRT_INPUT_INDEX_SQUEEZE_VALUE, NULL); + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/grip/value", XRT_INPUT_INDEX_SQUEEZE_VALUE, + NULL); struct MonadoInputComponent x = {true, true, false}; struct MonadoInputComponent y = {true, false, true}; - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/thumbstick/click", - XRT_INPUT_INDEX_THUMBSTICK_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/thumbstick/click", XRT_INPUT_INDEX_THUMBSTICK_CLICK, + NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/thumbstick/touch", - XRT_INPUT_INDEX_THUMBSTICK_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/thumbstick/touch", XRT_INPUT_INDEX_THUMBSTICK_TOUCH, + NULL); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/thumbstick/x", + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/thumbstick/x", XRT_INPUT_INDEX_THUMBSTICK, &x); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/thumbstick/y", + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/thumbstick/y", XRT_INPUT_INDEX_THUMBSTICK, &y); - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/trackpad/force", + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/trackpad/force", XRT_INPUT_INDEX_TRACKPAD_FORCE, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/trackpad/touch", - XRT_INPUT_INDEX_TRACKPAD_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/trackpad/touch", XRT_INPUT_INDEX_TRACKPAD_TOUCH, + NULL); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/trackpad/x", - XRT_INPUT_INDEX_TRACKPAD, &x); + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/trackpad/x", XRT_INPUT_INDEX_TRACKPAD, + &x); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/trackpad/y", - XRT_INPUT_INDEX_TRACKPAD, &y); + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/trackpad/y", XRT_INPUT_INDEX_TRACKPAD, + &y); - vr::VRDriverInput()->CreateHapticComponent( - m_ulPropertyContainer, "/output/haptic", - &m_hapticHandle); + vr::VRDriverInput()->CreateHapticComponent(m_ulPropertyContainer, "/output/haptic", + &m_hapticHandle); } break; case XRT_DEVICE_VIVE_WAND: { - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/trigger/value", + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/trigger/value", XRT_INPUT_VIVE_TRIGGER_VALUE, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/trigger/click", - XRT_INPUT_VIVE_TRIGGER_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/trigger/click", XRT_INPUT_VIVE_TRIGGER_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/system/click", - XRT_INPUT_VIVE_SYSTEM_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/system/click", XRT_INPUT_VIVE_SYSTEM_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/click", - XRT_INPUT_VIVE_TRACKPAD_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/click", XRT_INPUT_VIVE_TRACKPAD_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/click", - XRT_INPUT_VIVE_MENU_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/click", XRT_INPUT_VIVE_MENU_CLICK, NULL); struct MonadoInputComponent x = {true, true, false}; struct MonadoInputComponent y = {true, false, true}; - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/trackpad/touch", - XRT_INPUT_VIVE_TRACKPAD_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/trackpad/touch", XRT_INPUT_VIVE_TRACKPAD_TOUCH, + NULL); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/trackpad/x", XRT_INPUT_VIVE_TRACKPAD, + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/trackpad/x", XRT_INPUT_VIVE_TRACKPAD, &x); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/trackpad/y", XRT_INPUT_VIVE_TRACKPAD, + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/trackpad/y", XRT_INPUT_VIVE_TRACKPAD, &y); - vr::VRDriverInput()->CreateHapticComponent( - m_ulPropertyContainer, "/output/haptic", - &m_hapticHandle); + vr::VRDriverInput()->CreateHapticComponent(m_ulPropertyContainer, "/output/haptic", + &m_hapticHandle); } break; case XRT_DEVICE_VIVE_TRACKER_GEN1: case XRT_DEVICE_VIVE_TRACKER_GEN2: break; case XRT_DEVICE_PSMV: { - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/trigger/value", + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/trigger/value", XRT_INPUT_PSMV_TRIGGER_VALUE, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/trigger/click", - XRT_INPUT_PSMV_MOVE_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/trigger/click", XRT_INPUT_PSMV_MOVE_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/system/click", - XRT_INPUT_PSMV_PS_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/system/click", XRT_INPUT_PSMV_PS_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/click", - XRT_INPUT_PSMV_CROSS_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/click", XRT_INPUT_PSMV_CROSS_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/click", - XRT_INPUT_PSMV_SQUARE_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/click", XRT_INPUT_PSMV_SQUARE_CLICK, NULL); - vr::VRDriverInput()->CreateHapticComponent( - m_ulPropertyContainer, "/output/haptic", - &m_hapticHandle); + vr::VRDriverInput()->CreateHapticComponent(m_ulPropertyContainer, "/output/haptic", + &m_hapticHandle); } break; @@ -403,83 +330,59 @@ public: { switch (this->m_xdev->name) { case XRT_DEVICE_INDEX_CONTROLLER: { - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/trigger/value", + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/trigger/value", XRT_INPUT_INDEX_TRIGGER_VALUE, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/trigger/click", - XRT_INPUT_INDEX_TRIGGER_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/trigger/touch", - XRT_INPUT_INDEX_TRIGGER_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/trigger/click", XRT_INPUT_INDEX_TRIGGER_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/trigger/touch", XRT_INPUT_INDEX_TRIGGER_TOUCH, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/system/click", - XRT_INPUT_INDEX_SYSTEM_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/system/touch", - XRT_INPUT_INDEX_SYSTEM_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/system/click", XRT_INPUT_INDEX_SYSTEM_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/system/touch", XRT_INPUT_INDEX_SYSTEM_TOUCH, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/click", - XRT_INPUT_INDEX_A_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/touch", - XRT_INPUT_INDEX_A_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/click", XRT_INPUT_INDEX_A_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/a/touch", XRT_INPUT_INDEX_A_TOUCH, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/click", - XRT_INPUT_INDEX_B_CLICK, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/touch", - XRT_INPUT_INDEX_B_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/click", XRT_INPUT_INDEX_B_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/b/touch", XRT_INPUT_INDEX_B_TOUCH, NULL); - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/grip/force", - XRT_INPUT_INDEX_SQUEEZE_FORCE, NULL); + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/grip/force", XRT_INPUT_INDEX_SQUEEZE_FORCE, + NULL); - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/grip/value", - XRT_INPUT_INDEX_SQUEEZE_VALUE, NULL); + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/grip/value", XRT_INPUT_INDEX_SQUEEZE_VALUE, + NULL); struct MonadoInputComponent x = {true, true, false}; struct MonadoInputComponent y = {true, false, true}; - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/thumbstick/click", - XRT_INPUT_INDEX_THUMBSTICK_CLICK, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/thumbstick/click", XRT_INPUT_INDEX_THUMBSTICK_CLICK, + NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/thumbstick/touch", - XRT_INPUT_INDEX_THUMBSTICK_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/thumbstick/touch", XRT_INPUT_INDEX_THUMBSTICK_TOUCH, + NULL); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/thumbstick/x", + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/thumbstick/x", XRT_INPUT_INDEX_THUMBSTICK, &x); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/thumbstick/y", + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/thumbstick/y", XRT_INPUT_INDEX_THUMBSTICK, &y); - AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, - "/input/trackpad/force", + AddControl(XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE, "/input/trackpad/force", XRT_INPUT_INDEX_TRACKPAD_FORCE, NULL); - AddControl(XRT_INPUT_TYPE_BOOLEAN, - "/input/trackpad/touch", - XRT_INPUT_INDEX_TRACKPAD_TOUCH, NULL); + AddControl(XRT_INPUT_TYPE_BOOLEAN, "/input/trackpad/touch", XRT_INPUT_INDEX_TRACKPAD_TOUCH, + NULL); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/trackpad/x", - XRT_INPUT_INDEX_TRACKPAD, &x); + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/trackpad/x", XRT_INPUT_INDEX_TRACKPAD, + &x); - AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, - "/input/trackpad/y", - XRT_INPUT_INDEX_TRACKPAD, &y); + AddControl(XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE, "/input/trackpad/y", XRT_INPUT_INDEX_TRACKPAD, + &y); - vr::VRDriverInput()->CreateHapticComponent( - m_ulPropertyContainer, "/output/haptic", - &m_hapticHandle); + vr::VRDriverInput()->CreateHapticComponent(m_ulPropertyContainer, "/output/haptic", + &m_hapticHandle); } break; @@ -497,24 +400,19 @@ public: void PoseUpdateThreadFunction() { - ovrd_log("Starting controller pose update thread for %s\n", - m_xdev->str); + ovrd_log("Starting controller pose update thread for %s\n", m_xdev->str); while (m_poseUpdating) { //! @todo figure out the best pose update rate - std::this_thread::sleep_for( - std::chrono::milliseconds(1)); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (m_unObjectId != vr::k_unTrackedDeviceIndexInvalid) { - vr::VRServerDriverHost() - ->TrackedDevicePoseUpdated( - m_unObjectId, GetPose(), - sizeof(vr::DriverPose_t)); + vr::VRServerDriverHost()->TrackedDevicePoseUpdated(m_unObjectId, GetPose(), + sizeof(vr::DriverPose_t)); } } - ovrd_log("Stopping controller pose update thread for %s\n", - m_xdev->str); + ovrd_log("Stopping controller pose update thread for %s\n", m_xdev->str); } vr::EVRInitError @@ -586,13 +484,9 @@ public: ovrd_log("Controller %d activated\n", m_unObjectId); - m_poseUpdateThread = new std::thread( - &CDeviceDriver_Monado_Controller::PoseUpdateThreadFunction, - this); + m_poseUpdateThread = new std::thread(&CDeviceDriver_Monado_Controller::PoseUpdateThreadFunction, this); if (!m_poseUpdateThread) { - ovrd_log( - "Unable to create pose updated thread for %s\n", - m_xdev->str); + ovrd_log("Unable to create pose updated thread for %s\n", m_xdev->str); return vr::VRInitError_Driver_Failed; } @@ -625,9 +519,7 @@ public: /** debug request from a client */ void - DebugRequest(const char *pchRequest, - char *pchResponseBuffer, - uint32_t unResponseBufferSize) + DebugRequest(const char *pchRequest, char *pchResponseBuffer, uint32_t unResponseBufferSize) { if (unResponseBufferSize >= 1) pchResponseBuffer[0] = 0; @@ -673,11 +565,9 @@ public: apply_pose(&rel, &m_pose); #ifdef DUMP_POSE_CONTROLLERS - ovrd_log("get controller %d pose %f %f %f %f, %f %f %f\n", - m_unObjectId, m_pose.qRotation.x, m_pose.qRotation.y, - m_pose.qRotation.z, m_pose.qRotation.w, - m_pose.vecPosition[0], m_pose.vecPosition[1], - m_pose.vecPosition[2]); + ovrd_log("get controller %d pose %f %f %f %f, %f %f %f\n", m_unObjectId, m_pose.qRotation.x, + m_pose.qRotation.y, m_pose.qRotation.z, m_pose.qRotation.w, m_pose.vecPosition[0], + m_pose.vecPosition[1], m_pose.vecPosition[2]); #endif vr::HmdQuaternion_t identityquat{1, 0, 0, 0}; @@ -701,8 +591,7 @@ public: // ovrd_log("Update %d: %s\n", i, // m_controls[i].steamvr_control_path); - enum xrt_input_name input_name = - m_controls[i].monado_input_name; + enum xrt_input_name input_name = m_controls[i].monado_input_name; struct xrt_input *input = NULL; for (uint32_t ii = 0; ii < m_xdev->num_inputs; ii++) { @@ -713,44 +602,34 @@ public: } if (input == NULL) { - ovrd_log("Input for %s not found!\n", - m_controls[i].steamvr_control_path); + ovrd_log("Input for %s not found!\n", m_controls[i].steamvr_control_path); continue; } - vr::VRInputComponentHandle_t handle = - m_controls[i].control_handle; + vr::VRInputComponentHandle_t handle = m_controls[i].control_handle; - if (m_controls[i].monado_input_type == - XRT_INPUT_TYPE_BOOLEAN) { + if (m_controls[i].monado_input_type == XRT_INPUT_TYPE_BOOLEAN) { bool state = input->value.boolean; - vr::VRDriverInput()->UpdateBooleanComponent( - handle, state, 0); + vr::VRDriverInput()->UpdateBooleanComponent(handle, state, 0); // ovrd_log("Update %s: %d\n", // m_controls[i].steamvr_control_path, state); // U_LOG_D("Update %s: %d", // m_controls[i].steamvr_control_path, // state); } - if (m_controls[i].monado_input_type == - XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE || - m_controls[i].monado_input_type == - XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE) { + if (m_controls[i].monado_input_type == XRT_INPUT_TYPE_VEC1_MINUS_ONE_TO_ONE || + m_controls[i].monado_input_type == XRT_INPUT_TYPE_VEC1_ZERO_TO_ONE) { float value; - if (m_controls[i].component.has_component && - m_controls[i].component.x) { + if (m_controls[i].component.has_component && m_controls[i].component.x) { value = input->value.vec2.x; - } else if (m_controls[i] - .component.has_component && - m_controls[i].component.y) { + } else if (m_controls[i].component.has_component && m_controls[i].component.y) { value = input->value.vec2.y; } else { value = input->value.vec1.x; } - vr::VRDriverInput()->UpdateScalarComponent( - handle, value, 0); + vr::VRDriverInput()->UpdateScalarComponent(handle, value, 0); // ovrd_log("Update %s: %f\n", // m_controls[i].steamvr_control_path, // state->x); @@ -771,8 +650,7 @@ public: } bool - TriggerHapticPulse(uint32_t unAxisId, - uint16_t usPulseDurationMicroseconds) + TriggerHapticPulse(uint32_t unAxisId, uint16_t usPulseDurationMicroseconds) { // deprecated API return false; @@ -820,22 +698,17 @@ private: * */ -class CDeviceDriver_Monado : public vr::ITrackedDeviceServerDriver, - public vr::IVRDisplayComponent +class CDeviceDriver_Monado : public vr::ITrackedDeviceServerDriver, public vr::IVRDisplayComponent { public: - CDeviceDriver_Monado(struct xrt_instance *xinst, - struct xrt_device *xdev) - : m_xdev(xdev) + CDeviceDriver_Monado(struct xrt_instance *xinst, struct xrt_device *xdev) : m_xdev(xdev) { //! @todo latency m_flSecondsFromVsyncToPhotons = 0.011; - float ns = - (float)m_xdev->hmd->screens->nominal_frame_interval_ns; + float ns = (float)m_xdev->hmd->screens->nominal_frame_interval_ns; m_flDisplayFrequency = 1. / ns * 1000. * 1000. * 1000.; - ovrd_log("display frequency from device: %f\n", - m_flDisplayFrequency); + ovrd_log("display frequency from device: %f\n", m_flDisplayFrequency); // steamvr can really misbehave when freq is inf or so if (m_flDisplayFrequency < 0 || m_flDisplayFrequency > 1000) { @@ -848,18 +721,15 @@ public: struct xrt_vec3 ipd_vec = {ipd_meters, 0, 0}; for (int view = 0; view < 2; view++) { - xdev->get_view_pose(xdev, &ipd_vec, view, - &m_view_pose[view]); + xdev->get_view_pose(xdev, &ipd_vec, view, &m_view_pose[view]); } //! @todo more versatile IPD calculation - float actual_ipd = - -m_view_pose[0].position.x + m_view_pose[1].position.x; + float actual_ipd = -m_view_pose[0].position.x + m_view_pose[1].position.x; m_flIPD = actual_ipd; - ovrd_log("Seconds from Vsync to Photons: %f\n", - m_flSecondsFromVsyncToPhotons); + ovrd_log("Seconds from Vsync to Photons: %f\n", m_flSecondsFromVsyncToPhotons); ovrd_log("Display Frequency: %f\n", m_flDisplayFrequency); ovrd_log("IPD: %f\n", m_flIPD); }; @@ -908,8 +778,7 @@ private: }; static void -create_translation_rotation_matrix(struct xrt_pose *pose, - struct vr::HmdMatrix34_t *res) +create_translation_rotation_matrix(struct xrt_pose *pose, struct vr::HmdMatrix34_t *res) { struct xrt_vec3 t = pose->position; struct xrt_quat r = pose->orientation; @@ -935,8 +804,8 @@ CDeviceDriver_Monado::PoseUpdateThreadFunction() while (m_poseUpdating) { //! @todo figure out the best pose update rate std::this_thread::sleep_for(std::chrono::milliseconds(1)); - vr::VRServerDriverHost()->TrackedDevicePoseUpdated( - m_trackedDeviceIndex, GetPose(), sizeof(vr::DriverPose_t)); + vr::VRServerDriverHost()->TrackedDevicePoseUpdated(m_trackedDeviceIndex, GetPose(), + sizeof(vr::DriverPose_t)); } ovrd_log("Stopping HMD pose update thread\n"); } @@ -972,15 +841,12 @@ CDeviceDriver_Monado::Activate(vr::TrackedDeviceIndex_t unObjectId) create_translation_rotation_matrix(&m_view_pose[0], &left); vr::HmdMatrix34_t right; create_translation_rotation_matrix(&m_view_pose[1], &right); - vr::VRServerDriverHost()->TrackedDeviceDisplayTransformUpdated( - m_trackedDeviceIndex, left, right); + vr::VRServerDriverHost()->TrackedDeviceDisplayTransformUpdated(m_trackedDeviceIndex, left, right); - m_poseUpdateThread = new std::thread( - &CDeviceDriver_Monado::PoseUpdateThreadFunction, this); + m_poseUpdateThread = new std::thread(&CDeviceDriver_Monado::PoseUpdateThreadFunction, this); if (!m_poseUpdateThread) { - ovrd_log("Unable to create pose updated thread for %s\n", - m_xdev->str); + ovrd_log("Unable to create pose updated thread for %s\n", m_xdev->str); return vr::VRInitError_Driver_Failed; } @@ -1014,9 +880,7 @@ CDeviceDriver_Monado::GetComponent(const char *pchComponentNameAndVersion) } void -CDeviceDriver_Monado::DebugRequest(const char *pchRequest, - char *pchResponseBuffer, - uint32_t unResponseBufferSize) +CDeviceDriver_Monado::DebugRequest(const char *pchRequest, char *pchResponseBuffer, uint32_t unResponseBufferSize) { //! @todo } @@ -1038,8 +902,7 @@ CDeviceDriver_Monado::GetPose() timepoint_ns now_ns = os_monotonic_get_ns(); struct xrt_space_relation rel; - xrt_device_get_tracked_pose(m_xdev, XRT_INPUT_GENERIC_HEAD_POSE, now_ns, - &rel); + xrt_device_get_tracked_pose(m_xdev, XRT_INPUT_GENERIC_HEAD_POSE, now_ns, &rel); struct xrt_pose *offset = &m_xdev->tracking_origin->offset; @@ -1057,17 +920,15 @@ CDeviceDriver_Monado::GetPose() t.qWorldFromDriverRotation = HmdQuaternion_Init(1, 0, 0, 0); t.qDriverFromHeadRotation = HmdQuaternion_Init(1, 0, 0, 0); - t.poseIsValid = - rel.relation_flags & XRT_SPACE_RELATION_ORIENTATION_VALID_BIT; + t.poseIsValid = rel.relation_flags & XRT_SPACE_RELATION_ORIENTATION_VALID_BIT; t.result = vr::TrackingResult_Running_OK; t.deviceIsConnected = true; apply_pose(&rel, &t); #ifdef DUMP_POSE - ovrd_log("get hmd pose %f %f %f %f, %f %f %f\n", t.qRotation.x, - t.qRotation.y, t.qRotation.z, t.qRotation.w, t.vecPosition[0], - t.vecPosition[1], t.vecPosition[2]); + ovrd_log("get hmd pose %f %f %f %f, %f %f %f\n", t.qRotation.x, t.qRotation.y, t.qRotation.z, t.qRotation.w, + t.vecPosition[0], t.vecPosition[1], t.vecPosition[2]); #endif //! @todo @@ -1083,10 +944,7 @@ CDeviceDriver_Monado::GetPose() } void -CDeviceDriver_Monado::GetWindowBounds(int32_t *pnX, - int32_t *pnY, - uint32_t *pnWidth, - uint32_t *pnHeight) +CDeviceDriver_Monado::GetWindowBounds(int32_t *pnX, int32_t *pnY, uint32_t *pnWidth, uint32_t *pnHeight) { // offset in extended mode, e.g. to the right of a 1920x1080 monitor *pnX = 1920; @@ -1112,8 +970,7 @@ CDeviceDriver_Monado::IsDisplayRealDisplay() } void -CDeviceDriver_Monado::GetRecommendedRenderTargetSize(uint32_t *pnWidth, - uint32_t *pnHeight) +CDeviceDriver_Monado::GetRecommendedRenderTargetSize(uint32_t *pnWidth, uint32_t *pnHeight) { int scale = debug_get_num_option_scale_percentage(); float fscale = (float)scale / 100.f; @@ -1123,16 +980,12 @@ CDeviceDriver_Monado::GetRecommendedRenderTargetSize(uint32_t *pnWidth, *pnWidth = m_xdev->hmd->screens[0].w_pixels * fscale; *pnHeight = m_xdev->hmd->screens[0].h_pixels * fscale; - ovrd_log("Render Target Size: %dx%d (%fx)\n", *pnWidth, *pnHeight, - fscale); + ovrd_log("Render Target Size: %dx%d (%fx)\n", *pnWidth, *pnHeight, fscale); } void -CDeviceDriver_Monado::GetEyeOutputViewport(vr::EVREye eEye, - uint32_t *pnX, - uint32_t *pnY, - uint32_t *pnWidth, - uint32_t *pnHeight) +CDeviceDriver_Monado::GetEyeOutputViewport( + vr::EVREye eEye, uint32_t *pnX, uint32_t *pnY, uint32_t *pnWidth, uint32_t *pnHeight) { *pnWidth = m_xdev->hmd->views[eEye].viewport.w_pixels; *pnHeight = m_xdev->hmd->views[eEye].viewport.h_pixels; @@ -1140,23 +993,17 @@ CDeviceDriver_Monado::GetEyeOutputViewport(vr::EVREye eEye, *pnX = m_xdev->hmd->views[eEye].viewport.x_pixels; *pnY = m_xdev->hmd->views[eEye].viewport.y_pixels; - ovrd_log("Output Viewport for eye %d: %dx%d offset %dx%d\n", eEye, - *pnWidth, *pnHeight, *pnX, *pnY); + ovrd_log("Output Viewport for eye %d: %dx%d offset %dx%d\n", eEye, *pnWidth, *pnHeight, *pnX, *pnY); } void -CDeviceDriver_Monado::GetProjectionRaw(vr::EVREye eEye, - float *pfLeft, - float *pfRight, - float *pfTop, - float *pfBottom) +CDeviceDriver_Monado::GetProjectionRaw(vr::EVREye eEye, float *pfLeft, float *pfRight, float *pfTop, float *pfBottom) { *pfLeft = tanf(m_xdev->hmd->views[eEye].fov.angle_left); *pfRight = tanf(m_xdev->hmd->views[eEye].fov.angle_right); *pfTop = tanf(-m_xdev->hmd->views[eEye].fov.angle_up); *pfBottom = tanf(-m_xdev->hmd->views[eEye].fov.angle_down); - ovrd_log("Projection Raw: L%f R%f T%f B%f\n", *pfLeft, *pfRight, *pfTop, - *pfBottom); + ovrd_log("Projection Raw: L%f R%f T%f B%f\n", *pfLeft, *pfRight, *pfTop, *pfBottom); } vr::DistortionCoordinates_t @@ -1179,8 +1026,7 @@ CDeviceDriver_Monado::ComputeDistortion(vr::EVREye eEye, float fU, float fV) struct xrt_uv_triplet d; if (!m_xdev->compute_distortion(m_xdev, eEye, U, V, &d)) { - ovrd_log("Failed to compute distortion for view %d at %f,%f!\n", - eEye, U, V); + ovrd_log("Failed to compute distortion for view %d at %f,%f!\n", eEye, U, V); vr::DistortionCoordinates_t coordinates; coordinates.rfBlue[0] = U; @@ -1280,8 +1126,7 @@ CServerDriver_Monado::Init(vr::IVRDriverContext *pDriverContext) ovrd_log("Selected HMD %s\n", m_xhmd->str); m_MonadoDeviceDriver = new CDeviceDriver_Monado(m_xinst, m_xhmd); //! @todo provide a serial number - vr::VRServerDriverHost()->TrackedDeviceAdded( - m_xhmd->str, vr::TrackedDeviceClass_HMD, m_MonadoDeviceDriver); + vr::VRServerDriverHost()->TrackedDeviceAdded(m_xhmd->str, vr::TrackedDeviceClass_HMD, m_MonadoDeviceDriver); struct xrt_device *left_xdev = NULL; if (left != XRT_DEVICE_ROLE_UNASSIGNED) { @@ -1300,18 +1145,14 @@ CServerDriver_Monado::Init(vr::IVRDriverContext *pDriverContext) u_device_setup_tracking_origins(m_xhmd, left_xdev, right_xdev, &offset); if (left != XRT_DEVICE_ROLE_UNASSIGNED) { - m_left = new CDeviceDriver_Monado_Controller(m_xinst, left_xdev, - XRT_HAND_LEFT); - vr::VRServerDriverHost()->TrackedDeviceAdded( - m_left->GetSerialNumber().c_str(), - vr::TrackedDeviceClass_Controller, m_left); + m_left = new CDeviceDriver_Monado_Controller(m_xinst, left_xdev, XRT_HAND_LEFT); + vr::VRServerDriverHost()->TrackedDeviceAdded(m_left->GetSerialNumber().c_str(), + vr::TrackedDeviceClass_Controller, m_left); } if (right != XRT_DEVICE_ROLE_UNASSIGNED) { - m_right = new CDeviceDriver_Monado_Controller( - m_xinst, right_xdev, XRT_HAND_RIGHT); - vr::VRServerDriverHost()->TrackedDeviceAdded( - m_right->GetSerialNumber().c_str(), - vr::TrackedDeviceClass_Controller, m_right); + m_right = new CDeviceDriver_Monado_Controller(m_xinst, right_xdev, XRT_HAND_RIGHT); + vr::VRServerDriverHost()->TrackedDeviceAdded(m_right->GetSerialNumber().c_str(), + vr::TrackedDeviceClass_Controller, m_right); } return vr::VRInitError_None; @@ -1353,12 +1194,10 @@ CServerDriver_Monado::HandleHapticEvent(vr::VREvent_t *event) ovrd_log("Haptic vibration %fs %fHz %famp\n", duration, freq, amp); struct xrt_device *xdev = NULL; - if (m_left && m_left->m_ulPropertyContainer == - event->data.hapticVibration.containerHandle) { + if (m_left && m_left->m_ulPropertyContainer == event->data.hapticVibration.containerHandle) { xdev = m_left->m_xdev; ovrd_log("Haptic vibration left\n"); - } else if (m_right && m_right->m_ulPropertyContainer == - event->data.hapticVibration.containerHandle) { + } else if (m_right && m_right->m_ulPropertyContainer == event->data.hapticVibration.containerHandle) { xdev = m_right->m_xdev; ovrd_log("Haptic vibration right\n"); } else { @@ -1376,15 +1215,9 @@ CServerDriver_Monado::HandleHapticEvent(vr::VREvent_t *event) if (xdev != NULL) { enum xrt_output_name name; switch (xdev->name) { - case XRT_DEVICE_INDEX_CONTROLLER: - name = XRT_OUTPUT_NAME_INDEX_HAPTIC; - break; - case XRT_DEVICE_VIVE_WAND: - name = XRT_OUTPUT_NAME_VIVE_HAPTIC; - break; - case XRT_DEVICE_PSMV: - name = XRT_OUTPUT_NAME_PSMV_RUMBLE_VIBRATION; - break; + case XRT_DEVICE_INDEX_CONTROLLER: name = XRT_OUTPUT_NAME_INDEX_HAPTIC; break; + case XRT_DEVICE_VIVE_WAND: name = XRT_OUTPUT_NAME_VIVE_HAPTIC; break; + case XRT_DEVICE_PSMV: name = XRT_OUTPUT_NAME_PSMV_RUMBLE_VIBRATION; break; default: //! @todo name = XRT_OUTPUT_NAME_PSMV_RUMBLE_VIBRATION; @@ -1407,34 +1240,21 @@ CServerDriver_Monado::RunFrame() // https://github.com/ValveSoftware/openvr/issues/719#issuecomment-358038640 struct vr::VREvent_t event; - while (vr::VRServerDriverHost()->PollNextEvent( - &event, sizeof(struct vr::VREvent_t))) { + while (vr::VRServerDriverHost()->PollNextEvent(&event, sizeof(struct vr::VREvent_t))) { switch (event.eventType) { - case vr::VREvent_Input_HapticVibration: - HandleHapticEvent(&event); - break; + case vr::VREvent_Input_HapticVibration: HandleHapticEvent(&event); break; case vr::VREvent_PropertyChanged: // ovrd_log("Property changed\n"); break; case vr::VREvent_TrackedDeviceActivated: - ovrd_log("Device activated %d\n", - event.trackedDeviceIndex); + ovrd_log("Device activated %d\n", event.trackedDeviceIndex); break; case vr::VREvent_TrackedDeviceUserInteractionStarted: - ovrd_log("Device interaction started %d\n", - event.trackedDeviceIndex); - break; - case vr::VREvent_IpdChanged: - ovrd_log("ipd changed to %fm\n", - event.data.ipd.ipdMeters); - break; - case vr::VREvent_ActionBindingReloaded: - ovrd_log("action binding reloaded\n"); - break; - case vr::VREvent_StatusUpdate: - ovrd_log("EVRState: %d\n", - event.data.status.statusState); + ovrd_log("Device interaction started %d\n", event.trackedDeviceIndex); break; + case vr::VREvent_IpdChanged: ovrd_log("ipd changed to %fm\n", event.data.ipd.ipdMeters); break; + case vr::VREvent_ActionBindingReloaded: ovrd_log("action binding reloaded\n"); break; + case vr::VREvent_StatusUpdate: ovrd_log("EVRState: %d\n", event.data.status.statusState); break; case vr::VREvent_TrackedDeviceRoleChanged: // device roles are for legacy input diff --git a/src/xrt/targets/cli/cli_cmd_lighthouse.c b/src/xrt/targets/cli/cli_cmd_lighthouse.c index 4f8b8ab51..509f82607 100644 --- a/src/xrt/targets/cli/cli_cmd_lighthouse.c +++ b/src/xrt/targets/cli/cli_cmd_lighthouse.c @@ -41,8 +41,7 @@ cli_cmd_lighthouse(int argc, const char **argv) } P("Turning lighthouse %s!\n", str); - os_ble_broadcast_write_value("00001523-1212-efde-1523-785feabcd124", - "00001525-1212-efde-1523-785feabcd124", + os_ble_broadcast_write_value("00001523-1212-efde-1523-785feabcd124", "00001525-1212-efde-1523-785feabcd124", value); return 0; #else diff --git a/src/xrt/targets/common/target_instance.c b/src/xrt/targets/common/target_instance.c index ea42ed784..8acefd1a0 100644 --- a/src/xrt/targets/common/target_instance.c +++ b/src/xrt/targets/common/target_instance.c @@ -15,8 +15,7 @@ t_instance_create_native_compositor(struct xrt_instance *xinst, struct xrt_device *xdev, struct xrt_compositor_native **out_xcn) { - struct xrt_compositor_native *xcn = - xrt_gfx_provider_create_native(xdev); + struct xrt_compositor_native *xcn = xrt_gfx_provider_create_native(xdev); if (xcn == NULL) { return -1; @@ -34,8 +33,7 @@ t_instance_create_native_compositor(struct xrt_instance *xinst, */ int -xrt_instance_create(struct xrt_instance_info *i_info, - struct xrt_instance **out_xinst) +xrt_instance_create(struct xrt_instance_info *i_info, struct xrt_instance **out_xinst) { struct xrt_prober *xp = NULL; @@ -46,8 +44,7 @@ xrt_instance_create(struct xrt_instance_info *i_info, struct t_instance *tinst = U_TYPED_CALLOC(struct t_instance); tinst->base.select = t_instance_select; - tinst->base.create_native_compositor = - t_instance_create_native_compositor; + tinst->base.create_native_compositor = t_instance_create_native_compositor; tinst->base.get_prober = t_instance_get_prober; tinst->base.destroy = t_instance_destroy; tinst->xp = xp; diff --git a/src/xrt/targets/common/target_instance_no_comp.c b/src/xrt/targets/common/target_instance_no_comp.c index e04f9744c..a8252820b 100644 --- a/src/xrt/targets/common/target_instance_no_comp.c +++ b/src/xrt/targets/common/target_instance_no_comp.c @@ -28,8 +28,7 @@ t_instance_create_native_compositor_stub(struct xrt_instance *xinst, */ int -xrt_instance_create(struct xrt_instance_info *i_info, - struct xrt_instance **out_xinst) +xrt_instance_create(struct xrt_instance_info *i_info, struct xrt_instance **out_xinst) { struct xrt_prober *xp = NULL; @@ -40,8 +39,7 @@ xrt_instance_create(struct xrt_instance_info *i_info, struct t_instance *tinst = U_TYPED_CALLOC(struct t_instance); tinst->base.select = t_instance_select; - tinst->base.create_native_compositor = - t_instance_create_native_compositor_stub; + tinst->base.create_native_compositor = t_instance_create_native_compositor_stub; tinst->base.get_prober = t_instance_get_prober; tinst->base.destroy = t_instance_destroy; tinst->xp = xp; diff --git a/src/xrt/targets/common/target_instance_parts.h b/src/xrt/targets/common/target_instance_parts.h index 96cd43fa7..a168ec8cd 100644 --- a/src/xrt/targets/common/target_instance_parts.h +++ b/src/xrt/targets/common/target_instance_parts.h @@ -49,9 +49,7 @@ t_instance(struct xrt_instance *xinst) */ static int -t_instance_select(struct xrt_instance *xinst, - struct xrt_device **xdevs, - size_t num_xdevs) +t_instance_select(struct xrt_instance *xinst, struct xrt_device **xdevs, size_t num_xdevs) { struct t_instance *tinst = t_instance(xinst); diff --git a/src/xrt/targets/common/target_lists.c b/src/xrt/targets/common/target_lists.c index 7a7a016d7..75033b6fd 100644 --- a/src/xrt/targets/common/target_lists.c +++ b/src/xrt/targets/common/target_lists.c @@ -107,10 +107,8 @@ struct xrt_prober_entry target_entry_list[] = { {HTC_VID, VIVE_PID, vive_found, "HTC Vive"}, {HTC_VID, VIVE_PRO_MAINBOARD_PID, vive_found, "HTC Vive Pro"}, {VALVE_VID, VIVE_PRO_LHR_PID, vive_found, "Valve Index"}, - {VALVE_VID, VIVE_WATCHMAN_DONGLE, vive_controller_found, - "HTC Vive Watchman Wireless Device"}, - {VALVE_VID, VIVE_WATCHMAN_DONGLE_GEN2, vive_controller_found, - "Valve Watchman Wireless Device"}, + {VALVE_VID, VIVE_WATCHMAN_DONGLE, vive_controller_found, "HTC Vive Watchman Wireless Device"}, + {VALVE_VID, VIVE_WATCHMAN_DONGLE_GEN2, vive_controller_found, "Valve Watchman Wireless Device"}, #endif {0x0000, 0x0000, NULL, NULL}, // Terminate diff --git a/src/xrt/targets/ctl/main.c b/src/xrt/targets/ctl/main.c index e7caabc6c..06f68b850 100644 --- a/src/xrt/targets/ctl/main.c +++ b/src/xrt/targets/ctl/main.c @@ -231,8 +231,7 @@ do_connect(struct ipc_connection *ipc_c) struct ipc_app_state cs; cs.pid = getpid(); - snprintf(cs.info.application_name, sizeof(cs.info.application_name), - "%s", "monado-ctl"); + snprintf(cs.info.application_name, sizeof(cs.info.application_name), "%s", "monado-ctl"); xrt_result_t xret = ipc_call_system_set_client_info(ipc_c, &cs); if (xret != XRT_SUCCESS) { diff --git a/src/xrt/targets/gui/gui_sdl2.c b/src/xrt/targets/gui/gui_sdl2.c index 13b031178..2ab5faf69 100644 --- a/src/xrt/targets/gui/gui_sdl2.c +++ b/src/xrt/targets/gui/gui_sdl2.c @@ -67,10 +67,8 @@ gui_sdl2_init(struct sdl2_program *p) int h = 1080; SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, - SDL_GL_CONTEXT_PROFILE_CORE); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, - SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); diff --git a/src/xrt/targets/gui/gui_sdl2_imgui.c b/src/xrt/targets/gui/gui_sdl2_imgui.c index d4cfb2ae6..2289be172 100644 --- a/src/xrt/targets/gui/gui_sdl2_imgui.c +++ b/src/xrt/targets/gui/gui_sdl2_imgui.c @@ -84,8 +84,7 @@ gui_sdl2_imgui_loop(struct sdl2_program *p) p->base.stopped = true; } - if (event.type == SDL_WINDOWEVENT && - event.window.event == SDL_WINDOWEVENT_CLOSE && + if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(p->win)) { p->base.stopped = true; } @@ -110,8 +109,7 @@ gui_sdl2_imgui_loop(struct sdl2_program *p) igRender(); // Clear the background. - glViewport(0, 0, (int)io->DisplaySize.x, - (int)io->DisplaySize.y); + glViewport(0, 0, (int)io->DisplaySize.x, (int)io->DisplaySize.y); glClearColor(gui.clear.r, gui.clear.g, gui.clear.b, 1.0f); glClear(GL_COLOR_BUFFER_BIT); diff --git a/src/xrt/targets/openxr/oxr_sdl2_hack.c b/src/xrt/targets/openxr/oxr_sdl2_hack.c index d944bad91..9996c38e3 100644 --- a/src/xrt/targets/openxr/oxr_sdl2_hack.c +++ b/src/xrt/targets/openxr/oxr_sdl2_hack.c @@ -83,10 +83,8 @@ sdl2_window_init(struct sdl2_program *p) SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, - SDL_GL_CONTEXT_PROFILE_CORE); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, - SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); int window_flags = 0; window_flags |= SDL_WINDOW_SHOWN; @@ -162,8 +160,7 @@ sdl2_loop(struct sdl2_program *p) p->base.stopped = true; } - if (event.type == SDL_WINDOWEVENT && - event.window.event == SDL_WINDOWEVENT_CLOSE && + if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(p->win)) { p->base.stopped = true; } @@ -188,8 +185,7 @@ sdl2_loop(struct sdl2_program *p) igRender(); // Clear the background. - glViewport(0, 0, (int)io->DisplaySize.x, - (int)io->DisplaySize.y); + glViewport(0, 0, (int)io->DisplaySize.x, (int)io->DisplaySize.y); glClearColor(gui.clear.r, gui.clear.g, gui.clear.b, 1.0f); glClear(GL_COLOR_BUFFER_BIT); diff --git a/src/xrt/targets/openxr/target.c b/src/xrt/targets/openxr/target.c index 1b94484e5..703c0cfb8 100644 --- a/src/xrt/targets/openxr/target.c +++ b/src/xrt/targets/openxr/target.c @@ -14,12 +14,10 @@ // Forward declaration int -ipc_instance_create(struct xrt_instance_info *i_info, - struct xrt_instance **out_xinst); +ipc_instance_create(struct xrt_instance_info *i_info, struct xrt_instance **out_xinst); int -xrt_instance_create(struct xrt_instance_info *i_info, - struct xrt_instance **out_xinst) +xrt_instance_create(struct xrt_instance_info *i_info, struct xrt_instance **out_xinst) { return ipc_instance_create(i_info, out_xinst); } diff --git a/src/xrt/targets/service-lib/service_target.cpp b/src/xrt/targets/service-lib/service_target.cpp index aeea27886..937c70744 100644 --- a/src/xrt/targets/service-lib/service_target.cpp +++ b/src/xrt/targets/service-lib/service_target.cpp @@ -25,9 +25,7 @@ using wrap::android::view::Surface; extern "C" void -Java_org_freedesktop_monado_ipc_MonadoImpl_nativeAddClient(JNIEnv *env, - jobject thiz, - int fd) +Java_org_freedesktop_monado_ipc_MonadoImpl_nativeAddClient(JNIEnv *env, jobject thiz, int fd) { jni::init(env); jni::Object monadoImpl(thiz); @@ -37,9 +35,7 @@ Java_org_freedesktop_monado_ipc_MonadoImpl_nativeAddClient(JNIEnv *env, } extern "C" void -Java_org_freedesktop_monado_ipc_MonadoImpl_nativeAppSurface(JNIEnv *env, - jobject thiz, - jobject surface) +Java_org_freedesktop_monado_ipc_MonadoImpl_nativeAppSurface(JNIEnv *env, jobject thiz, jobject surface) { jni::init(env); Surface surf(surface);