refactor: further cleanup

Signed-off-by: Schmarni <marnistromer@gmail.com>
This commit is contained in:
Schmarni
2025-04-26 16:10:20 +02:00
parent 6284d4bf31
commit fd1809ecc6
10 changed files with 40 additions and 43 deletions

View File

@@ -7,18 +7,13 @@ use bevy_mod_openxr::{add_xr_plugins, init::OxrInitPlugin, types::OxrExtensions}
fn main() { fn main() {
App::new() App::new()
.add_plugins(add_xr_plugins(DefaultPlugins).set(OxrInitPlugin { .add_plugins(add_xr_plugins(DefaultPlugins).set(OxrInitPlugin {
app_info: default(),
exts: { exts: {
let mut exts = OxrExtensions::default(); let mut exts = OxrExtensions::default();
exts.enable_fb_passthrough(); exts.enable_fb_passthrough();
exts.enable_hand_tracking(); exts.enable_hand_tracking();
exts exts
}, },
blend_modes: default(), ..default()
backends: default(),
formats: default(),
resolutions: default(),
synchronous_pipeline_compilation: default(),
})) }))
.add_plugins(bevy_xr_utils::hand_gizmos::HandGizmosPlugin) .add_plugins(bevy_xr_utils::hand_gizmos::HandGizmosPlugin)
.add_systems(Startup, setup) .add_systems(Startup, setup)

View File

@@ -29,7 +29,7 @@ pub(crate) fn run_action_binding_sugestion(world: &mut World) {
} }
fn bind_actions(instance: Res<OxrInstance>, mut actions: EventReader<OxrSuggestActionBinding>) { fn bind_actions(instance: Res<OxrInstance>, mut actions: EventReader<OxrSuggestActionBinding>) {
let mut bindings: HashMap<&str, Vec<ActionSuggestedBinding>, _> = HashMap::new(); let mut bindings: HashMap<&str, Vec<ActionSuggestedBinding>> = HashMap::new();
for e in actions.read() { for e in actions.read() {
bindings.entry(&e.interaction_profile).or_default().extend( bindings.entry(&e.interaction_profile).or_default().extend(
e.bindings e.bindings

View File

@@ -1,7 +1,4 @@
use bevy::{ use bevy::prelude::{Deref, DerefMut, Resource};
prelude::{Deref, DerefMut},
};
use bevy::prelude::Resource;
use openxr::ExtensionSet; use openxr::ExtensionSet;
#[derive(Clone, Debug, Eq, PartialEq, Deref, DerefMut, Resource)] #[derive(Clone, Debug, Eq, PartialEq, Deref, DerefMut, Resource)]

View File

@@ -8,6 +8,7 @@ use openxr::PassthroughCapabilityFlagsFB;
use crate::layer_builder::PassthroughLayer; use crate::layer_builder::PassthroughLayer;
use crate::resources::*; use crate::resources::*;
use crate::session::OxrSession; use crate::session::OxrSession;
use crate::types::Result as OxrResult;
pub struct OxrPassthroughPlugin; pub struct OxrPassthroughPlugin;
@@ -72,7 +73,7 @@ pub fn create_passthrough(
session: &OxrSession, session: &OxrSession,
flags: openxr::PassthroughFlagsFB, flags: openxr::PassthroughFlagsFB,
purpose: openxr::PassthroughLayerPurposeFB, purpose: openxr::PassthroughLayerPurposeFB,
) -> crate::types::Result<(OxrPassthrough, OxrPassthroughLayer)> { ) -> OxrResult<(OxrPassthrough, OxrPassthroughLayer)> {
let passthrough = session.create_passthrough(flags)?; let passthrough = session.create_passthrough(flags)?;
let passthrough_layer = session.create_passthrough_layer(&passthrough, purpose)?; let passthrough_layer = session.create_passthrough_layer(&passthrough, purpose)?;
@@ -81,7 +82,10 @@ pub fn create_passthrough(
} }
#[inline] #[inline]
pub fn supports_passthrough(instance: &OxrInstance, system: OxrSystemId) -> crate::types::Result<bool> { pub fn supports_passthrough(
instance: &OxrInstance,
system: OxrSystemId,
) -> OxrResult<bool> {
if instance.exts().fb_passthrough.is_none() { if instance.exts().fb_passthrough.is_none() {
return Ok(false); return Ok(false);
} }

View File

@@ -3,7 +3,6 @@ use std::ffi::{c_void, CString};
use ash::vk::Handle; use ash::vk::Handle;
use bevy::log::{debug, error}; use bevy::log::{debug, error};
use bevy::math::UVec2; use bevy::math::UVec2;
use bevy::render::render_resource::TextureFormat;
use openxr::{sys, Version}; use openxr::{sys, Version};
use wgpu_hal::api::Vulkan; use wgpu_hal::api::Vulkan;
use wgpu_hal::Api; use wgpu_hal::Api;
@@ -197,8 +196,7 @@ unsafe impl GraphicsExt for openxr::Vulkan {
"Couldn't parse Android's ", "Couldn't parse Android's ",
"ro.build.version.sdk system property ({}): {}", "ro.build.version.sdk system property ({}): {}",
), ),
val, val, err,
err,
); );
0 0
} }
@@ -652,6 +650,7 @@ fn wgpu_to_vulkan(format: wgpu::TextureFormat) -> Option<ash::vk::Format> {
Tf::R32Uint => F::R32_UINT, Tf::R32Uint => F::R32_UINT,
Tf::R32Sint => F::R32_SINT, Tf::R32Sint => F::R32_SINT,
Tf::R32Float => F::R32_SFLOAT, Tf::R32Float => F::R32_SFLOAT,
Tf::R64Uint => F::R64_UINT,
Tf::Rg16Uint => F::R16G16_UINT, Tf::Rg16Uint => F::R16G16_UINT,
Tf::Rg16Sint => F::R16G16_SINT, Tf::Rg16Sint => F::R16G16_SINT,
Tf::Rg16Float => F::R16G16_SFLOAT, Tf::Rg16Float => F::R16G16_SFLOAT,
@@ -756,8 +755,5 @@ fn wgpu_to_vulkan(format: wgpu::TextureFormat) -> Option<ash::vk::Format> {
AstcBlock::B12x12 => F::ASTC_12X12_SFLOAT_BLOCK_EXT, AstcBlock::B12x12 => F::ASTC_12X12_SFLOAT_BLOCK_EXT,
}, },
}, },
TextureFormat::R64Uint => {
panic!()
}
}) })
} }

View File

@@ -13,6 +13,7 @@ use bevy::render::settings::RenderCreation;
use bevy::render::MainWorld; use bevy::render::MainWorld;
use bevy::render::Render; use bevy::render::Render;
use bevy::render::RenderApp; use bevy::render::RenderApp;
use bevy::render::RenderDebugFlags;
use bevy::render::RenderPlugin; use bevy::render::RenderPlugin;
use bevy::winit::UpdateMode; use bevy::winit::UpdateMode;
use bevy::winit::WinitSettings; use bevy::winit::WinitSettings;
@@ -24,11 +25,12 @@ use crate::graphics::*;
use crate::resources::*; use crate::resources::*;
use crate::session::OxrSession; use crate::session::OxrSession;
use crate::session::OxrSessionCreateNextChain; use crate::session::OxrSessionCreateNextChain;
use crate::types::Result as OxrResult;
use crate::types::*; use crate::types::*;
use super::exts::OxrEnabledExtensions; use super::exts::OxrEnabledExtensions;
use super::poll_events::OxrEventIn;
use super::poll_events::OxrEventHandlerExt; use super::poll_events::OxrEventHandlerExt;
use super::poll_events::OxrEventIn;
pub fn session_started(started: Option<Res<OxrSessionStarted>>) -> bool { pub fn session_started(started: Option<Res<OxrSessionStarted>>) -> bool {
started.is_some_and(|started| started.0) started.is_some_and(|started| started.0)
@@ -62,6 +64,7 @@ pub struct OxrInitPlugin {
pub resolutions: Option<Vec<UVec2>>, pub resolutions: Option<Vec<UVec2>>,
/// Passed into the render plugin when added to the app. /// Passed into the render plugin when added to the app.
pub synchronous_pipeline_compilation: bool, pub synchronous_pipeline_compilation: bool,
pub render_debug_flags: RenderDebugFlags,
} }
impl Default for OxrInitPlugin { impl Default for OxrInitPlugin {
fn default() -> Self { fn default() -> Self {
@@ -73,11 +76,12 @@ impl Default for OxrInitPlugin {
exts.enable_hand_tracking(); exts.enable_hand_tracking();
exts exts
}, },
blend_modes: default(), blend_modes: Some(vec![openxr::EnvironmentBlendMode::OPAQUE]),
backends: default(), backends: default(),
formats: Some(vec![wgpu::TextureFormat::Rgba8UnormSrgb]), formats: Some(vec![wgpu::TextureFormat::Rgba8UnormSrgb]),
resolutions: default(), resolutions: default(),
synchronous_pipeline_compilation: false, synchronous_pipeline_compilation: false,
render_debug_flags: default(),
} }
} }
} }
@@ -104,7 +108,7 @@ impl Plugin for OxrInitPlugin {
RenderInstance(Arc::new(WgpuWrapper::new(wgpu_instance))), RenderInstance(Arc::new(WgpuWrapper::new(wgpu_instance))),
), ),
synchronous_pipeline_compilation: self.synchronous_pipeline_compilation, synchronous_pipeline_compilation: self.synchronous_pipeline_compilation,
debug_flags: Default::default(), debug_flags: self.render_debug_flags,
}, },
ExtractResourcePlugin::<OxrSessionStarted>::default(), ExtractResourcePlugin::<OxrSessionStarted>::default(),
)) ))
@@ -207,7 +211,7 @@ fn detect_session_destroyed(
impl OxrInitPlugin { impl OxrInitPlugin {
fn init_xr( fn init_xr(
&self, &self,
) -> crate::types::Result<( ) -> OxrResult<(
OxrInstance, OxrInstance,
OxrSystemId, OxrSystemId,
WgpuGraphics, WgpuGraphics,
@@ -351,7 +355,7 @@ fn init_xr_session(
resolutions, resolutions,
graphics_info, graphics_info,
}: SessionConfigInfo, }: SessionConfigInfo,
) -> crate::types::Result<( ) -> OxrResult<(
OxrSession, OxrSession,
OxrFrameWaiter, OxrFrameWaiter,
OxrFrameStream, OxrFrameStream,
@@ -457,7 +461,7 @@ fn init_xr_session(
} else { } else {
available_blend_modes.first().copied() available_blend_modes.first().copied()
} }
.ok_or(OxrError::NoAvailableBackend)?; .ok_or(OxrError::NoAvailableBlendMode)?;
let graphics_info = OxrGraphicsInfo { let graphics_info = OxrGraphicsInfo {
blend_mode, blend_mode,

View File

@@ -5,6 +5,7 @@ use crate::error::OxrError;
use crate::graphics::*; use crate::graphics::*;
use crate::layer_builder::{CompositionLayer, LayerProvider}; use crate::layer_builder::{CompositionLayer, LayerProvider};
use crate::session::{OxrSession, OxrSessionCreateNextChain}; use crate::session::{OxrSession, OxrSessionCreateNextChain};
use crate::types::Result as OxrResult;
use crate::types::*; use crate::types::*;
/// Wrapper around an [`Entry`](openxr::Entry) with some methods overridden to use bevy types. /// Wrapper around an [`Entry`](openxr::Entry) with some methods overridden to use bevy types.
@@ -15,7 +16,7 @@ pub struct OxrEntry(pub openxr::Entry);
impl OxrEntry { impl OxrEntry {
/// Enumerate available extensions for this OpenXR runtime. /// Enumerate available extensions for this OpenXR runtime.
pub fn enumerate_extensions(&self) -> crate::types::Result<OxrExtensions> { pub fn enumerate_extensions(&self) -> OxrResult<OxrExtensions> {
Ok(self.0.enumerate_extensions().map(Into::into)?) Ok(self.0.enumerate_extensions().map(Into::into)?)
} }
@@ -28,7 +29,7 @@ impl OxrEntry {
exts: OxrExtensions, exts: OxrExtensions,
layers: &[&str], layers: &[&str],
backend: GraphicsBackend, backend: GraphicsBackend,
) -> crate::types::Result<OxrInstance> { ) -> OxrResult<OxrInstance> {
let available_exts = self.enumerate_extensions()?; let available_exts = self.enumerate_extensions()?;
if !backend.is_available(&available_exts) { if !backend.is_available(&available_exts) {
@@ -53,7 +54,7 @@ impl OxrEntry {
} }
/// Returns a list of all of the backends the OpenXR runtime supports. /// Returns a list of all of the backends the OpenXR runtime supports.
pub fn available_backends(&self) -> crate::types::Result<Vec<GraphicsBackend>> { pub fn available_backends(&self) -> OxrResult<Vec<GraphicsBackend>> {
Ok(GraphicsBackend::available_backends( Ok(GraphicsBackend::available_backends(
&self.enumerate_extensions()?, &self.enumerate_extensions()?,
)) ))
@@ -105,7 +106,7 @@ impl OxrInstance {
pub fn init_graphics( pub fn init_graphics(
&self, &self,
system_id: openxr::SystemId, system_id: openxr::SystemId,
) -> crate::types::Result<(WgpuGraphics, SessionCreateInfo)> { ) -> OxrResult<(WgpuGraphics, SessionCreateInfo)> {
graphics_match!( graphics_match!(
self.1; self.1;
_ => { _ => {
@@ -128,9 +129,9 @@ impl OxrInstance {
system_id: openxr::SystemId, system_id: openxr::SystemId,
info: SessionCreateInfo, info: SessionCreateInfo,
chain: &mut OxrSessionCreateNextChain, chain: &mut OxrSessionCreateNextChain,
) -> crate::types::Result<(OxrSession, OxrFrameWaiter, OxrFrameStream)> { ) -> OxrResult<(OxrSession, OxrFrameWaiter, OxrFrameStream)> {
if !info.0.using_graphics_of_val(&self.1) { if !info.0.using_graphics_of_val(&self.1) {
return crate::types::Result::Err(OxrError::GraphicsBackendMismatch { return OxrResult::Err(OxrError::GraphicsBackendMismatch {
item: std::any::type_name::<SessionCreateInfo>(), item: std::any::type_name::<SessionCreateInfo>(),
backend: info.0.graphics_name(), backend: info.0.graphics_name(),
expected_backend: self.1.graphics_name(), expected_backend: self.1.graphics_name(),
@@ -180,7 +181,7 @@ impl OxrFrameStream {
display_time: openxr::Time, display_time: openxr::Time,
environment_blend_mode: openxr::EnvironmentBlendMode, environment_blend_mode: openxr::EnvironmentBlendMode,
layers: &[&dyn CompositionLayer], layers: &[&dyn CompositionLayer],
) -> crate::types::Result<()> { ) -> OxrResult<()> {
graphics_match!( graphics_match!(
&mut self.0; &mut self.0;
stream => { stream => {
@@ -233,7 +234,7 @@ impl OxrSwapchain {
/// Determine the index of the next image to render to in the swapchain image array. /// Determine the index of the next image to render to in the swapchain image array.
/// ///
/// Calls [`acquire_image`](openxr::Swapchain::acquire_image) internally. /// Calls [`acquire_image`](openxr::Swapchain::acquire_image) internally.
pub fn acquire_image(&mut self) -> crate::types::Result<u32> { pub fn acquire_image(&mut self) -> OxrResult<u32> {
graphics_match!( graphics_match!(
&mut self.0; &mut self.0;
swap => Ok(swap.acquire_image()?) swap => Ok(swap.acquire_image()?)
@@ -243,7 +244,7 @@ impl OxrSwapchain {
/// Wait for the compositor to finish reading from the oldest unwaited acquired image. /// Wait for the compositor to finish reading from the oldest unwaited acquired image.
/// ///
/// Calls [`wait_image`](openxr::Swapchain::wait_image) internally. /// Calls [`wait_image`](openxr::Swapchain::wait_image) internally.
pub fn wait_image(&mut self, timeout: openxr::Duration) -> crate::types::Result<()> { pub fn wait_image(&mut self, timeout: openxr::Duration) -> OxrResult<()> {
graphics_match!( graphics_match!(
&mut self.0; &mut self.0;
swap => Ok(swap.wait_image(timeout)?) swap => Ok(swap.wait_image(timeout)?)
@@ -253,7 +254,7 @@ impl OxrSwapchain {
/// Release the oldest acquired image. /// Release the oldest acquired image.
/// ///
/// Calls [`release_image`](openxr::Swapchain::release_image) internally. /// Calls [`release_image`](openxr::Swapchain::release_image) internally.
pub fn release_image(&mut self) -> crate::types::Result<()> { pub fn release_image(&mut self) -> OxrResult<()> {
graphics_match!( graphics_match!(
&mut self.0; &mut self.0;
swap => Ok(swap.release_image()?) swap => Ok(swap.release_image()?)
@@ -268,7 +269,7 @@ impl OxrSwapchain {
device: &wgpu::Device, device: &wgpu::Device,
format: wgpu::TextureFormat, format: wgpu::TextureFormat,
resolution: UVec2, resolution: UVec2,
) -> crate::types::Result<OxrSwapchainImages> { ) -> OxrResult<OxrSwapchainImages> {
graphics_match!( graphics_match!(
&self.0; &self.0;
swap => { swap => {

View File

@@ -1,6 +1,6 @@
use std::{mem::MaybeUninit, ptr, sync::Mutex}; use std::{mem::MaybeUninit, ptr, sync::Mutex};
use bevy::{prelude::*}; use bevy::{platform::collections::hash_set::HashSet, prelude::*};
use bevy_mod_xr::{ use bevy_mod_xr::{
session::{XrFirst, XrHandleEvents}, session::{XrFirst, XrHandleEvents},
spaces::{ spaces::{
@@ -64,7 +64,7 @@ fn destroy_space_event(instance: Res<OxrInstance>, mut events: EventReader<XrDes
} }
} }
pub static OXR_DO_NOT_CALL_DESTOY_SPACE_FOR_SPACES: Mutex<Option<bevy::platform::collections::hash_set::HashSet<u64>>> = Mutex::new(None); pub static OXR_DO_NOT_CALL_DESTOY_SPACE_FOR_SPACES: Mutex<Option<HashSet<u64>>> = Mutex::new(None);
pub static OXR_ORIGINAL_DESTOY_SPACE: Mutex<Option<openxr::sys::pfn::DestroySpace>> = pub static OXR_ORIGINAL_DESTOY_SPACE: Mutex<Option<openxr::sys::pfn::DestroySpace>> =
Mutex::new(None); Mutex::new(None);
@@ -72,7 +72,7 @@ fn patch_destroy_space(instance: ResMut<OxrInstance>) {
OXR_DO_NOT_CALL_DESTOY_SPACE_FOR_SPACES OXR_DO_NOT_CALL_DESTOY_SPACE_FOR_SPACES
.lock() .lock()
.unwrap() .unwrap()
.replace(bevy::platform::collections::hash_set::HashSet::new()); .replace(HashSet::new());
let raw_instance_ptr = instance.fp() as *const _ as *mut openxr::raw::Instance; let raw_instance_ptr = instance.fp() as *const _ as *mut openxr::raw::Instance;
unsafe { unsafe {
OXR_ORIGINAL_DESTOY_SPACE OXR_ORIGINAL_DESTOY_SPACE

View File

@@ -10,7 +10,7 @@ keywords = ["gamedev", "bevy", "Xr", "Vr"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
bevy.workspace = true bevy = { workspace = true, features = ["bevy_log"] }
[lints.clippy] [lints.clippy]
too_many_arguments = "allow" too_many_arguments = "allow"

View File

@@ -2,7 +2,7 @@ use bevy::{
ecs::{component::Component, entity::Entity}, ecs::{component::Component, entity::Entity},
log::warn, log::warn,
math::bool, math::bool,
prelude::{Bundle, Commands, Deref, DerefMut, Resource, Transform, Visibility, World}, prelude::{Bundle, Command, Commands, Deref, DerefMut, Resource, Transform, Visibility, World},
}; };
use crate::{session::XrTracker, spaces::XrSpaceLocationFlags}; use crate::{session::XrTracker, spaces::XrSpaceLocationFlags};
pub const HAND_JOINT_COUNT: usize = 26; pub const HAND_JOINT_COUNT: usize = 26;
@@ -180,8 +180,8 @@ pub struct SpawnHandTracker<B: Bundle> {
pub side: HandSide, pub side: HandSide,
} }
impl<B: Bundle> bevy::prelude::Command for SpawnHandTracker<B> { impl<B: Bundle> Command for SpawnHandTracker<B> {
fn apply(self, world: &mut bevy::prelude::World) { fn apply(self, world: &mut World) {
let Some(executor) = world.remove_resource::<SpawnHandTrackerCommandExecutor>() else { let Some(executor) = world.remove_resource::<SpawnHandTrackerCommandExecutor>() else {
warn!("no SpawnHandTracker executor defined, skipping handtracker creation"); warn!("no SpawnHandTracker executor defined, skipping handtracker creation");
return; return;