refactor: remove once_cell dependency

This commit is contained in:
Nova
2025-02-24 14:56:37 -08:00
parent 12a99cf9dd
commit 5362563e44
16 changed files with 144 additions and 150 deletions

11
Cargo.lock generated
View File

@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 4
[[package]] [[package]]
name = "addr2line" name = "addr2line"
@@ -1520,7 +1520,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"windows-targets 0.48.5", "windows-targets 0.52.6",
] ]
[[package]] [[package]]
@@ -2645,7 +2645,7 @@ checksum = "2f2b15926089e5526bb2dd738a2eb0e59034356e06eb71e1cd912358c0e62c4d"
[[package]] [[package]]
name = "stardust-xr" name = "stardust-xr"
version = "0.45.0" version = "0.45.0"
source = "git+https://github.com/StardustXR/core.git?branch=dev#6ea2a27df24e5fcf31fe2f7726989f0a1aecbd6c" source = "git+https://github.com/StardustXR/core.git?branch=dev#0e746ca4d0a04f668fc1958e38b9d799eb5e3370"
dependencies = [ dependencies = [
"cluFlock", "cluFlock",
"color-eyre", "color-eyre",
@@ -2666,7 +2666,7 @@ dependencies = [
[[package]] [[package]]
name = "stardust-xr-schemas" name = "stardust-xr-schemas"
version = "1.5.3" version = "1.5.3"
source = "git+https://github.com/StardustXR/core.git?branch=dev#6ea2a27df24e5fcf31fe2f7726989f0a1aecbd6c" source = "git+https://github.com/StardustXR/core.git?branch=dev#0e746ca4d0a04f668fc1958e38b9d799eb5e3370"
dependencies = [ dependencies = [
"flatbuffers", "flatbuffers",
"flexbuffers", "flexbuffers",
@@ -2698,7 +2698,6 @@ dependencies = [
"mint", "mint",
"nanoid", "nanoid",
"nix 0.29.0", "nix 0.29.0",
"once_cell",
"parking_lot 0.12.3", "parking_lot 0.12.3",
"portable-atomic", "portable-atomic",
"prisma", "prisma",
@@ -3388,7 +3387,7 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
dependencies = [ dependencies = [
"windows-sys 0.48.0", "windows-sys 0.59.0",
] ]
[[package]] [[package]]

View File

@@ -55,7 +55,6 @@ lto = "thin"
[dependencies] [dependencies]
# small utility thingys # small utility thingys
once_cell = "1.19.0"
nanoid = "0.4.0" nanoid = "0.4.0"
lazy_static = "1.5.0" lazy_static = "1.5.0"
rand = "0.8.5" rand = "0.8.5"

View File

@@ -14,11 +14,16 @@ use crate::{
use color_eyre::eyre::{Result, eyre}; use color_eyre::eyre::{Result, eyre};
use global_counter::primitive::exact::CounterU32; use global_counter::primitive::exact::CounterU32;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use stardust_xr::messenger::{self, MessageSenderHandle}; use stardust_xr::messenger::{self, MessageSenderHandle};
use std::{fmt::Debug, fs, iter::FromIterator, path::PathBuf, sync::Arc}; use std::{
fmt::Debug,
fs,
iter::FromIterator,
path::PathBuf,
sync::{Arc, OnceLock},
};
use tokio::{net::UnixStream, task::JoinHandle}; use tokio::{net::UnixStream, task::JoinHandle};
use tracing::info; use tracing::info;
@@ -29,16 +34,16 @@ lazy_static! {
// env: None, // env: None,
exe: None, exe: None,
dispatch_join_handle: OnceCell::new(), dispatch_join_handle: OnceLock::new(),
flush_join_handle: OnceCell::new(), flush_join_handle: OnceLock::new(),
disconnect_status: OnceCell::new(), disconnect_status: OnceLock::new(),
message_sender_handle: None, message_sender_handle: None,
id_counter: CounterU32::new(0), id_counter: CounterU32::new(0),
scenegraph: Default::default(), scenegraph: Default::default(),
root: OnceCell::new(), root: OnceLock::new(),
base_resource_prefixes: Default::default(), base_resource_prefixes: Default::default(),
state: OnceCell::default(), state: OnceLock::default(),
}); });
} }
@@ -59,16 +64,16 @@ pub struct Client {
pub pid: Option<i32>, pub pid: Option<i32>,
// env: Option<FxHashMap<String, String>>, // env: Option<FxHashMap<String, String>>,
exe: Option<PathBuf>, exe: Option<PathBuf>,
dispatch_join_handle: OnceCell<JoinHandle<Result<()>>>, dispatch_join_handle: OnceLock<JoinHandle<Result<()>>>,
flush_join_handle: OnceCell<JoinHandle<Result<()>>>, flush_join_handle: OnceLock<JoinHandle<Result<()>>>,
disconnect_status: OnceCell<Result<()>>, disconnect_status: OnceLock<Result<()>>,
id_counter: CounterU32, id_counter: CounterU32,
pub message_sender_handle: Option<MessageSenderHandle>, pub message_sender_handle: Option<MessageSenderHandle>,
pub scenegraph: Arc<Scenegraph>, pub scenegraph: Arc<Scenegraph>,
pub root: OnceCell<Arc<Root>>, pub root: OnceLock<Arc<Root>>,
pub base_resource_prefixes: Mutex<Vec<PathBuf>>, pub base_resource_prefixes: Mutex<Vec<PathBuf>>,
pub state: OnceCell<ClientState>, pub state: OnceLock<ClientState>,
} }
impl Client { impl Client {
pub fn from_connection(connection: UnixStream) -> Result<Arc<Self>> { pub fn from_connection(connection: UnixStream) -> Result<Arc<Self>> {
@@ -95,16 +100,16 @@ impl Client {
// env, // env,
exe: exe.clone(), exe: exe.clone(),
dispatch_join_handle: OnceCell::new(), dispatch_join_handle: OnceLock::new(),
flush_join_handle: OnceCell::new(), flush_join_handle: OnceLock::new(),
disconnect_status: OnceCell::new(), disconnect_status: OnceLock::new(),
id_counter: CounterU32::new(256), id_counter: CounterU32::new(256),
message_sender_handle: Some(messenger_tx.handle()), message_sender_handle: Some(messenger_tx.handle()),
scenegraph: scenegraph.clone(), scenegraph: scenegraph.clone(),
root: OnceCell::new(), root: OnceLock::new(),
base_resource_prefixes: Default::default(), base_resource_prefixes: Default::default(),
state: OnceCell::default(), state: OnceLock::default(),
}); });
let _ = client.scenegraph.client.set(Arc::downgrade(&client)); let _ = client.scenegraph.client.set(Arc::downgrade(&client));
let _ = client.root.set(Root::create(&client, state.root)?); let _ = client.root.set(Root::create(&client, state.root)?);
@@ -128,7 +133,7 @@ impl Client {
.map(|exe| exe.to_string()) .map(|exe| exe.to_string())
}) })
.unwrap_or_else(|| "??".to_string()); .unwrap_or_else(|| "??".to_string());
let _ = client.dispatch_join_handle.get_or_try_init(|| { let _ = client.dispatch_join_handle.get_or_init(|| {
task::new( task::new(
|| { || {
format!( format!(
@@ -147,8 +152,9 @@ impl Client {
} }
}, },
) )
.unwrap()
}); });
let _ = client.flush_join_handle.get_or_try_init(|| { let _ = client.flush_join_handle.get_or_init(|| {
task::new( task::new(
|| format!("client flush pid={} exe={}", &pid_printable, &exe_printable,), || format!("client flush pid={} exe={}", &pid_printable, &exe_printable,),
{ {
@@ -162,6 +168,7 @@ impl Client {
} }
}, },
) )
.unwrap()
}); });
Ok(client) Ok(client)

View File

@@ -1,14 +1,13 @@
use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::any::Any; use std::{any::Any, sync::LazyLock};
use tokio::sync::mpsc::{self, unbounded_channel}; use tokio::sync::mpsc::{self, unbounded_channel};
type Anything = Box<dyn Any + Send + Sync>; type Anything = Box<dyn Any + Send + Sync>;
static MAIN_DESTROY_QUEUE: Lazy<( static MAIN_DESTROY_QUEUE: LazyLock<(
mpsc::UnboundedSender<Anything>, mpsc::UnboundedSender<Anything>,
Mutex<mpsc::UnboundedReceiver<Anything>>, Mutex<mpsc::UnboundedReceiver<Anything>>,
)> = Lazy::new(|| { )> = LazyLock::new(|| {
let (tx, rx) = unbounded_channel(); let (tx, rx) = unbounded_channel();
(tx, Mutex::new(rx)) (tx, Mutex::new(rx))
}); });

View File

@@ -2,7 +2,6 @@ use crate::core::error::Result;
use crate::nodes::Node; use crate::nodes::Node;
use crate::nodes::alias::get_original; use crate::nodes::alias::get_original;
use crate::{core::client::Client, nodes::Message}; use crate::{core::client::Client, nodes::Message};
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use serde::Serialize; use serde::Serialize;
@@ -11,13 +10,13 @@ use stardust_xr::scenegraph::ScenegraphError;
use stardust_xr::schemas::flex::serialize; use stardust_xr::schemas::flex::serialize;
use std::future::Future; use std::future::Future;
use std::os::fd::OwnedFd; use std::os::fd::OwnedFd;
use std::sync::{Arc, Weak}; use std::sync::{Arc, OnceLock, Weak};
use tokio::sync::oneshot; use tokio::sync::oneshot;
use tracing::{debug, debug_span}; use tracing::{debug, debug_span};
#[derive(Default)] #[derive(Default)]
pub struct Scenegraph { pub struct Scenegraph {
pub(super) client: OnceCell<Weak<Client>>, pub(super) client: OnceLock<Weak<Client>>,
nodes: Mutex<FxHashMap<u64, Arc<Node>>>, nodes: Mutex<FxHashMap<u64, Arc<Node>>>,
} }

View File

@@ -15,12 +15,11 @@ use core::client::Client;
use core::task; use core::task;
use directories::ProjectDirs; use directories::ProjectDirs;
use objects::ServerObjects; use objects::ServerObjects;
use once_cell::sync::OnceCell;
use session::{launch_start, save_session}; use session::{launch_start, save_session};
use stardust_xr::schemas::dbus::object_registry::ObjectRegistry; use stardust_xr::schemas::dbus::object_registry::ObjectRegistry;
use stardust_xr::server; use stardust_xr::server;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::{Arc, OnceLock};
use std::time::Duration; use std::time::Duration;
use stereokit_rust::material::Material; use stereokit_rust::material::Material;
use stereokit_rust::shader::Shader; use stereokit_rust::shader::Shader;
@@ -70,7 +69,7 @@ struct CliArgs {
restore: Option<String>, restore: Option<String>,
} }
static STARDUST_INSTANCE: OnceCell<String> = OnceCell::new(); static STARDUST_INSTANCE: OnceLock<String> = OnceLock::new();
// #[tokio::main] // #[tokio::main]
#[tokio::main(flavor = "current_thread")] #[tokio::main(flavor = "current_thread")]

View File

@@ -7,12 +7,11 @@ use crate::core::resource::get_resource_file;
use crate::nodes::spatial::{SPATIAL_ASPECT_ALIAS_INFO, Spatial, Transform}; use crate::nodes::spatial::{SPATIAL_ASPECT_ALIAS_INFO, Spatial, Transform};
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use glam::{Vec4Swizzles, vec3}; use glam::{Vec4Swizzles, vec3};
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use stardust_xr::values::ResourceID; use stardust_xr::values::ResourceID;
use std::ops::DerefMut; use std::ops::DerefMut;
use std::sync::Arc; use std::sync::{Arc, OnceLock};
use std::{ffi::OsStr, path::PathBuf}; use std::{ffi::OsStr, path::PathBuf};
use stereokit_rust::sound::{Sound as SkSound, SoundInst}; use stereokit_rust::sound::{Sound as SkSound, SoundInst};
@@ -24,7 +23,7 @@ pub struct Sound {
volume: f32, volume: f32,
pending_audio_path: PathBuf, pending_audio_path: PathBuf,
sk_sound: OnceCell<SkSound>, sk_sound: OnceLock<SkSound>,
instance: Mutex<Option<SoundInst>>, instance: Mutex<Option<SoundInst>>,
stop: Mutex<Option<()>>, stop: Mutex<Option<()>>,
play: Mutex<Option<()>>, play: Mutex<Option<()>>,
@@ -41,7 +40,7 @@ impl Sound {
space: node.get_aspect::<Spatial>().unwrap().clone(), space: node.get_aspect::<Spatial>().unwrap().clone(),
volume: 1.0, volume: 1.0,
pending_audio_path, pending_audio_path,
sk_sound: OnceCell::new(), sk_sound: OnceLock::new(),
instance: Mutex::new(None), instance: Mutex::new(None),
stop: Mutex::new(None), stop: Mutex::new(None),
play: Mutex::new(None), play: Mutex::new(None),

View File

@@ -9,13 +9,12 @@ use crate::nodes::alias::{Alias, AliasList};
use crate::nodes::spatial::Spatial; use crate::nodes::spatial::Spatial;
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use glam::{Mat4, Vec2, Vec3}; use glam::{Mat4, Vec2, Vec3};
use once_cell::sync::{Lazy, OnceCell};
use parking_lot::Mutex; use parking_lot::Mutex;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use stardust_xr::values::ResourceID; use stardust_xr::values::ResourceID;
use std::ffi::OsStr; use std::ffi::OsStr;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::sync::{Arc, Weak}; use std::sync::{Arc, LazyLock, OnceLock, Weak};
use stereokit_rust::material::Transparency; use stereokit_rust::material::Transparency;
use stereokit_rust::maths::Bounds; use stereokit_rust::maths::Bounds;
use stereokit_rust::sk::MainThreadToken; use stereokit_rust::sk::MainThreadToken;
@@ -98,9 +97,9 @@ impl MaterialRegistry {
} }
} }
static MATERIAL_REGISTRY: Lazy<MaterialRegistry> = Lazy::new(MaterialRegistry::default); static MATERIAL_REGISTRY: LazyLock<MaterialRegistry> = LazyLock::new(MaterialRegistry::default);
static MODEL_REGISTRY: Registry<Model> = Registry::new(); static MODEL_REGISTRY: Registry<Model> = Registry::new();
static HOLDOUT_MATERIAL: OnceCell<Arc<MaterialWrapper>> = OnceCell::new(); static HOLDOUT_MATERIAL: OnceLock<Arc<MaterialWrapper>> = OnceLock::new();
impl MaterialParameter { impl MaterialParameter {
fn apply_to_material(&self, client: &Client, material: &Material, parameter_name: &str) { fn apply_to_material(&self, client: &Client, material: &Material, parameter_name: &str) {
@@ -333,7 +332,7 @@ impl ModelPartAspect for ModelPart {
pub struct Model { pub struct Model {
space: Arc<Spatial>, space: Arc<Spatial>,
_resource_id: ResourceID, _resource_id: ResourceID,
sk_model: OnceCell<SKModel>, sk_model: OnceLock<SKModel>,
parts: Mutex<Vec<Arc<ModelPart>>>, parts: Mutex<Vec<Arc<ModelPart>>>,
} }
impl Model { impl Model {
@@ -348,7 +347,7 @@ impl Model {
let model = Arc::new(Model { let model = Arc::new(Model {
space: node.get_aspect::<Spatial>().unwrap().clone(), space: node.get_aspect::<Spatial>().unwrap().clone(),
_resource_id: resource_id, _resource_id: resource_id,
sk_model: OnceCell::new(), sk_model: OnceLock::new(),
parts: Mutex::new(Vec::default()), parts: Mutex::new(Vec::default()),
}); });
MODEL_REGISTRY.add_raw(&model); MODEL_REGISTRY.add_raw(&model);

View File

@@ -7,9 +7,12 @@ use crate::{
}; };
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use glam::{Mat4, Vec2, vec3}; use glam::{Mat4, Vec2, vec3};
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::{ffi::OsStr, path::PathBuf, sync::Arc}; use std::{
ffi::OsStr,
path::PathBuf,
sync::{Arc, OnceLock},
};
use stereokit_rust::{ use stereokit_rust::{
font::Font, font::Font,
sk::MainThreadToken, sk::MainThreadToken,
@@ -38,7 +41,7 @@ fn convert_align(x_align: super::XAlign, y_align: super::YAlign) -> TextAlign {
pub struct Text { pub struct Text {
space: Arc<Spatial>, space: Arc<Spatial>,
font_path: Option<PathBuf>, font_path: Option<PathBuf>,
style: OnceCell<SkTextStyle>, style: OnceLock<SkTextStyle>,
text: Mutex<String>, text: Mutex<String>,
data: Mutex<TextStyle>, data: Mutex<TextStyle>,
@@ -51,7 +54,7 @@ impl Text {
font_path: style.font.as_ref().and_then(|res| { font_path: style.font.as_ref().and_then(|res| {
get_resource_file(res, &client, &[OsStr::new("ttf"), OsStr::new("otf")]) get_resource_file(res, &client, &[OsStr::new("ttf"), OsStr::new("otf")])
}), }),
style: OnceCell::new(), style: OnceLock::new(),
text: Mutex::new(text), text: Mutex::new(text),
data: Mutex::new(style), data: Mutex::new(style),
@@ -62,73 +65,71 @@ impl Text {
} }
fn draw(&self, token: &MainThreadToken) { fn draw(&self, token: &MainThreadToken) {
let style = self.style.get_or_try_init(|| -> Result<SkTextStyle> { let style = self.style.get_or_init(|| {
let font = self let font = self
.font_path .font_path
.as_deref() .as_deref()
.and_then(|path| Font::from_file(path).ok()) .and_then(|path| Font::from_file(path).ok())
.unwrap_or_default(); .unwrap_or_default();
Ok(SkTextStyle::from_font(font, 1.0, Color32::WHITE)) SkTextStyle::from_font(font, 1.0, Color32::WHITE)
}); });
if let Ok(style) = style { let text = self.text.lock();
let text = self.text.lock(); let data = self.data.lock();
let data = self.data.lock(); let transform = self.space.global_transform()
let transform = self.space.global_transform() * Mat4::from_scale(vec3(
* Mat4::from_scale(vec3( data.character_height,
data.character_height, data.character_height,
data.character_height, data.character_height,
data.character_height, ));
)); if let Some(bounds) = &data.bounds {
if let Some(bounds) = &data.bounds { stereokit_rust::system::Text::add_in(
stereokit_rust::system::Text::add_in( token,
token, &*text,
&*text, transform,
transform, Vec2::from(bounds.bounds) / data.character_height,
Vec2::from(bounds.bounds) / data.character_height, match bounds.fit {
match bounds.fit { super::TextFit::Wrap => TextFit::Wrap,
super::TextFit::Wrap => TextFit::Wrap, super::TextFit::Clip => TextFit::Clip,
super::TextFit::Clip => TextFit::Clip, super::TextFit::Squeeze => TextFit::Squeeze,
super::TextFit::Squeeze => TextFit::Squeeze, super::TextFit::Exact => TextFit::Exact,
super::TextFit::Exact => TextFit::Exact, super::TextFit::Overflow => TextFit::Overflow,
super::TextFit::Overflow => TextFit::Overflow, },
}, Some(*style),
Some(*style), Some(Color128::new(
Some(Color128::new( data.color.c.r,
data.color.c.r, data.color.c.g,
data.color.c.g, data.color.c.b,
data.color.c.b, data.color.a,
data.color.a, )),
)), data.bounds
data.bounds .as_ref()
.as_ref() .map(|b| convert_align(b.anchor_align_x, b.anchor_align_y)),
.map(|b| convert_align(b.anchor_align_x, b.anchor_align_y)), Some(convert_align(data.text_align_x, data.text_align_y)),
Some(convert_align(data.text_align_x, data.text_align_y)), None,
None, None,
None, None,
None, );
); } else {
} else { stereokit_rust::system::Text::add_at(
stereokit_rust::system::Text::add_at( token,
token, &*text,
&*text, transform,
transform, Some(*style),
Some(*style), Some(Color128::new(
Some(Color128::new( data.color.c.r,
data.color.c.r, data.color.c.g,
data.color.c.g, data.color.c.b,
data.color.c.b, data.color.a,
data.color.a, )),
)), data.bounds
data.bounds .as_ref()
.as_ref() .map(|b| convert_align(b.anchor_align_x, b.anchor_align_y)),
.map(|b| convert_align(b.anchor_align_x, b.anchor_align_y)), Some(convert_align(data.text_align_x, data.text_align_y)),
Some(convert_align(data.text_align_x, data.text_align_y)), None,
None, None,
None, None,
None, );
);
}
} }
} }
} }

View File

@@ -12,15 +12,14 @@ use crate::nodes::spatial::SPATIAL_REF_ASPECT_ALIAS_INFO;
use crate::nodes::spatial::Transform; use crate::nodes::spatial::Transform;
use color_eyre::eyre::OptionExt; use color_eyre::eyre::OptionExt;
use glam::{Vec3, Vec3A, Vec3Swizzles, vec2, vec3, vec3a}; use glam::{Vec3, Vec3A, Vec3Swizzles, vec2, vec3, vec3a};
use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use stardust_xr::values::Vector3; use stardust_xr::values::Vector3;
use std::sync::Arc; use std::sync::{Arc, LazyLock};
// TODO: get SDFs working properly with non-uniform scale and so on, output distance relative to the spatial it's compared against // TODO: get SDFs working properly with non-uniform scale and so on, output distance relative to the spatial it's compared against
pub static FIELD_ALIAS_INFO: Lazy<AliasInfo> = Lazy::new(|| AliasInfo { pub static FIELD_ALIAS_INFO: LazyLock<AliasInfo> = LazyLock::new(|| AliasInfo {
server_methods: vec![ server_methods: vec![
SPATIAL_REF_GET_TRANSFORM_SERVER_OPCODE, SPATIAL_REF_GET_TRANSFORM_SERVER_OPCODE,
SPATIAL_REF_GET_LOCAL_BOUNDING_BOX_SERVER_OPCODE, SPATIAL_REF_GET_LOCAL_BOUNDING_BOX_SERVER_OPCODE,

View File

@@ -20,11 +20,11 @@ use crate::{
use glam::Mat4; use glam::Mat4;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use mint::{ColumnMatrix4, Vector2}; use mint::{ColumnMatrix4, Vector2};
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use stardust_xr::schemas::flex::{deserialize, serialize}; use stardust_xr::schemas::flex::{deserialize, serialize};
use std::sync::Arc; use std::sync::Arc;
use std::sync::OnceLock;
use stereokit_rust::{ use stereokit_rust::{
material::{Material, Transparency}, material::{Material, Transparency},
shader::Shader, shader::Shader,
@@ -33,7 +33,6 @@ use stereokit_rust::{
tex::{Tex, TexFormat, TexType}, tex::{Tex, TexFormat, TexType},
util::Color128, util::Color128,
}; };
use tracing::error;
pub struct TexWrapper(pub Tex); pub struct TexWrapper(pub Tex);
unsafe impl Send for TexWrapper {} unsafe impl Send for TexWrapper {}
@@ -68,8 +67,8 @@ struct FrameInfo {
pub struct CameraItem { pub struct CameraItem {
space: Arc<Spatial>, space: Arc<Spatial>,
frame_info: Mutex<FrameInfo>, frame_info: Mutex<FrameInfo>,
sk_tex: OnceCell<TexWrapper>, sk_tex: OnceLock<TexWrapper>,
sk_mat: OnceCell<Arc<MaterialWrapper>>, sk_mat: OnceLock<Arc<MaterialWrapper>>,
applied_to: Registry<ModelPart>, applied_to: Registry<ModelPart>,
apply_to: Registry<ModelPart>, apply_to: Registry<ModelPart>,
} }
@@ -82,8 +81,8 @@ impl CameraItem {
proj_matrix, proj_matrix,
px_size, px_size,
}), }),
sk_tex: OnceCell::new(), sk_tex: OnceLock::new(),
sk_mat: OnceCell::new(), sk_mat: OnceLock::new(),
applied_to: Registry::new(), applied_to: Registry::new(),
apply_to: Registry::new(), apply_to: Registry::new(),
}); });
@@ -140,19 +139,13 @@ impl CameraItem {
TexFormat::RGBA32Linear, TexFormat::RGBA32Linear,
)) ))
}); });
let sk_mat = self let sk_mat = self.sk_mat.get_or_init(|| {
.sk_mat let shader = Shader::from_memory(UNLIT_SHADER_BYTES).unwrap();
.get_or_try_init(|| -> Result<Arc<MaterialWrapper>> { let mut mat = Material::new(&shader, None);
let shader = Shader::from_memory(UNLIT_SHADER_BYTES)?; mat.get_all_param_info().set_texture("diffuse", &sk_tex.0);
let mut mat = Material::new(&shader, None); mat.transparency(Transparency::Blend);
mat.get_all_param_info().set_texture("diffuse", &sk_tex.0); Arc::new(MaterialWrapper(mat))
mat.transparency(Transparency::Blend); });
Ok(Arc::new(MaterialWrapper(mat)))
});
let Ok(sk_mat) = sk_mat else {
error!("unable to make camera item stereokit texture");
return;
};
for model_part in self.apply_to.take_valid_contents() { for model_part in self.apply_to.take_valid_contents() {
model_part.replace_material(sk_mat.clone()) model_part.replace_material(sk_mat.clone())
} }

View File

@@ -278,8 +278,8 @@ impl Node {
let serialized = serialize(input)?; let serialized = serialize(input)?;
let result = message_sender_handle let result = message_sender_handle
.method(self.id, aspect_id, method, &serialized, fds)? .method(self.id, aspect_id, method, &serialized, fds)
.await .await?
.map_err(ServerError::RemoteMethodError)?; .map_err(ServerError::RemoteMethodError)?;
let (message, fds) = result.into_components(); let (message, fds) = result.into_components();

View File

@@ -12,12 +12,11 @@ use crate::nodes::{Node, OWNED_ASPECT_ALIAS_INFO};
use color_eyre::eyre::OptionExt; use color_eyre::eyre::OptionExt;
use glam::{Mat4, Quat, Vec3, vec3a}; use glam::{Mat4, Quat, Vec3, vec3a};
use mint::Vector3; use mint::Vector3;
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use std::fmt::Debug; use std::fmt::Debug;
use std::ptr; use std::ptr;
use std::sync::{Arc, Weak}; use std::sync::{Arc, OnceLock, Weak};
use stereokit_rust::maths::Bounds; use stereokit_rust::maths::Bounds;
stardust_xr_server_codegen::codegen_spatial_protocol!(); stardust_xr_server_codegen::codegen_spatial_protocol!();
@@ -59,7 +58,7 @@ pub struct Spatial {
transform: Mutex<Mat4>, transform: Mutex<Mat4>,
zone: Mutex<Weak<Zone>>, zone: Mutex<Weak<Zone>>,
children: Registry<Spatial>, children: Registry<Spatial>,
pub bounding_box_calc: OnceCell<fn(&Node) -> Bounds>, pub bounding_box_calc: OnceLock<fn(&Node) -> Bounds>,
} }
impl Spatial { impl Spatial {
@@ -71,7 +70,7 @@ impl Spatial {
transform: Mutex::new(transform), transform: Mutex::new(transform),
zone: Mutex::new(Weak::new()), zone: Mutex::new(Weak::new()),
children: Registry::new(), children: Registry::new(),
bounding_box_calc: OnceCell::default(), bounding_box_calc: OnceLock::default(),
}) })
} }
pub fn add_to( pub fn add_to(

View File

@@ -12,7 +12,6 @@ mod xdg_shell;
use self::{state::WaylandState, surface::CORE_SURFACES}; use self::{state::WaylandState, surface::CORE_SURFACES};
use crate::{core::task, wayland::state::ClientState}; use crate::{core::task, wayland::state::ClientState};
use color_eyre::eyre::{Result, ensure}; use color_eyre::eyre::{Result, ensure};
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use smithay::backend::allocator::dmabuf::Dmabuf; use smithay::backend::allocator::dmabuf::Dmabuf;
use smithay::backend::egl::EGLContext; use smithay::backend::egl::EGLContext;
@@ -26,6 +25,7 @@ use smithay::wayland::dmabuf;
use std::ffi::OsStr; use std::ffi::OsStr;
use std::os::fd::{IntoRawFd, OwnedFd}; use std::os::fd::{IntoRawFd, OwnedFd};
use std::os::unix::prelude::AsRawFd; use std::os::unix::prelude::AsRawFd;
use std::sync::OnceLock;
use std::{ use std::{
ffi::c_void, ffi::c_void,
os::unix::{net::UnixListener, prelude::FromRawFd}, os::unix::{net::UnixListener, prelude::FromRawFd},
@@ -39,7 +39,7 @@ use tokio::{
}; };
use tracing::{debug_span, info, instrument}; use tracing::{debug_span, info, instrument};
pub static WAYLAND_DISPLAY: OnceCell<String> = OnceCell::new(); pub static WAYLAND_DISPLAY: OnceLock<String> = OnceLock::new();
struct EGLRawHandles { struct EGLRawHandles {
display: *const c_void, display: *const c_void,
@@ -161,7 +161,7 @@ impl Wayland {
let (stream, _) = acc?; let (stream, _) = acc?;
let client_state = Arc::new(ClientState { let client_state = Arc::new(ClientState {
pid: stream.peer_cred().ok().and_then(|c| c.pid()), pid: stream.peer_cred().ok().and_then(|c| c.pid()),
id: OnceCell::new(), id: OnceLock::new(),
compositor_state: Default::default(), compositor_state: Default::default(),
seat: state.lock().seat.clone(), seat: state.lock().seat.clone(),
}); });

View File

@@ -1,6 +1,5 @@
use super::seat::SeatWrapper; use super::seat::SeatWrapper;
use crate::wayland::drm::wl_drm::WlDrm; use crate::wayland::drm::wl_drm::WlDrm;
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use smithay::{ use smithay::{
backend::{ backend::{
@@ -42,13 +41,13 @@ use smithay::{
shm::{ShmHandler, ShmState}, shm::{ShmHandler, ShmState},
}, },
}; };
use std::sync::Arc; use std::sync::{Arc, OnceLock};
use tokio::sync::mpsc::UnboundedSender; use tokio::sync::mpsc::UnboundedSender;
use tracing::{info, warn}; use tracing::{info, warn};
pub struct ClientState { pub struct ClientState {
pub pid: Option<i32>, pub pid: Option<i32>,
pub id: OnceCell<ClientId>, pub id: OnceLock<ClientId>,
pub compositor_state: CompositorClientState, pub compositor_state: CompositorClientState,
pub seat: Arc<SeatWrapper>, pub seat: Arc<SeatWrapper>,
} }

View File

@@ -9,7 +9,6 @@ use crate::{
items::camera::TexWrapper, items::camera::TexWrapper,
}, },
}; };
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use send_wrapper::SendWrapper; use send_wrapper::SendWrapper;
use smithay::{ use smithay::{
@@ -22,7 +21,11 @@ use smithay::{
output::Output, output::Output,
reexports::wayland_server::{self, Resource, protocol::wl_surface::WlSurface}, reexports::wayland_server::{self, Resource, protocol::wl_surface::WlSurface},
}; };
use std::{ffi::c_void, sync::Arc, time::Duration}; use std::{
ffi::c_void,
sync::{Arc, OnceLock},
time::Duration,
};
use stereokit_rust::{ use stereokit_rust::{
material::{Material, Transparency}, material::{Material, Transparency},
shader::Shader, shader::Shader,
@@ -44,8 +47,8 @@ impl Drop for CoreSurfaceData {
pub struct CoreSurface { pub struct CoreSurface {
pub weak_surface: wayland_server::Weak<WlSurface>, pub weak_surface: wayland_server::Weak<WlSurface>,
mapped_data: Mutex<Option<CoreSurfaceData>>, mapped_data: Mutex<Option<CoreSurfaceData>>,
sk_tex: OnceCell<Mutex<TexWrapper>>, sk_tex: OnceLock<Mutex<TexWrapper>>,
sk_mat: OnceCell<Mutex<MaterialWrapper>>, sk_mat: OnceLock<Mutex<MaterialWrapper>>,
material_offset: Mutex<Delta<u32>>, material_offset: Mutex<Delta<u32>>,
pub pending_material_applications: Registry<ModelPart>, pub pending_material_applications: Registry<ModelPart>,
} }
@@ -55,8 +58,8 @@ impl CoreSurface {
let core_surface = CORE_SURFACES.add(CoreSurface { let core_surface = CORE_SURFACES.add(CoreSurface {
weak_surface: surface.downgrade(), weak_surface: surface.downgrade(),
mapped_data: Mutex::new(None), mapped_data: Mutex::new(None),
sk_tex: OnceCell::new(), sk_tex: OnceLock::new(),
sk_mat: OnceCell::new(), sk_mat: OnceLock::new(),
material_offset: Mutex::new(Delta::new(0)), material_offset: Mutex::new(Delta::new(0)),
pending_material_applications: Registry::new(), pending_material_applications: Registry::new(),
}); });