feat: save/restore state

This commit is contained in:
Nova
2024-02-20 23:12:23 -05:00
parent a85a9f56a6
commit c582c85a1a
10 changed files with 119 additions and 46 deletions

20
Cargo.lock generated
View File

@@ -846,6 +846,7 @@ dependencies = [
"manifest-dir-macros", "manifest-dir-macros",
"mint", "mint",
"protostar", "protostar",
"serde",
"stardust-xr-fusion", "stardust-xr-fusion",
"stardust-xr-molecules", "stardust-xr-molecules",
"tokio", "tokio",
@@ -1828,18 +1829,18 @@ checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.196" version = "1.0.197"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "870026e60fa08c69f064aa766c10f10b1d62db9ccd4d0abb206472bee0ce3b32" checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.196" version = "1.0.197"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33c85360c95e7d137454dc81d9a4ed2b8efd8fbe19cee57357b32b9771fccb67" checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -1974,6 +1975,7 @@ dependencies = [
"manifest-dir-macros", "manifest-dir-macros",
"mint", "mint",
"protostar", "protostar",
"serde",
"stardust-xr-fusion", "stardust-xr-fusion",
"stardust-xr-molecules", "stardust-xr-molecules",
"tokio", "tokio",
@@ -2016,7 +2018,7 @@ checksum = "2f2b15926089e5526bb2dd738a2eb0e59034356e06eb71e1cd912358c0e62c4d"
[[package]] [[package]]
name = "stardust-xr" name = "stardust-xr"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/StardustXR/core.git#6904244bda0346a9689358d5cd1b241108423656" source = "git+https://github.com/StardustXR/core.git#66f759f44e34caa12d1b76a8f058352b8cdeabe4"
dependencies = [ dependencies = [
"cluFlock", "cluFlock",
"color-rs", "color-rs",
@@ -2036,7 +2038,7 @@ dependencies = [
[[package]] [[package]]
name = "stardust-xr-fusion" name = "stardust-xr-fusion"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/StardustXR/core.git#6904244bda0346a9689358d5cd1b241108423656" source = "git+https://github.com/StardustXR/core.git#66f759f44e34caa12d1b76a8f058352b8cdeabe4"
dependencies = [ dependencies = [
"color-eyre", "color-eyre",
"color-rs", "color-rs",
@@ -2056,7 +2058,7 @@ dependencies = [
[[package]] [[package]]
name = "stardust-xr-fusion-codegen" name = "stardust-xr-fusion-codegen"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/StardustXR/core.git#6904244bda0346a9689358d5cd1b241108423656" source = "git+https://github.com/StardustXR/core.git#66f759f44e34caa12d1b76a8f058352b8cdeabe4"
dependencies = [ dependencies = [
"convert_case", "convert_case",
"mint", "mint",
@@ -2069,7 +2071,7 @@ dependencies = [
[[package]] [[package]]
name = "stardust-xr-molecules" name = "stardust-xr-molecules"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/StardustXR/molecules.git#c861e5665536e45262510048f90afd4eab694132" source = "git+https://github.com/StardustXR/molecules.git#dffa22c302e730776876940f4dac39a526d601bc"
dependencies = [ dependencies = [
"color-rs", "color-rs",
"glam 0.25.0", "glam 0.25.0",
@@ -2087,7 +2089,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#6904244bda0346a9689358d5cd1b241108423656" source = "git+https://github.com/StardustXR/core.git#66f759f44e34caa12d1b76a8f058352b8cdeabe4"
dependencies = [ dependencies = [
"flatbuffers", "flatbuffers",
"flexbuffers", "flexbuffers",

View File

@@ -3,6 +3,7 @@ members = ["app_grid", "hexagon_launcher", "protostar", "single", "sirius"]
[workspace.dependencies] [workspace.dependencies]
tokio = { version = "1.32.0", features = ["rt", "tokio-macros", "sync"] } tokio = { version = "1.32.0", features = ["rt", "tokio-macros", "sync"] }
serde = "1.0.197"
[workspace.dependencies.stardust-xr-fusion] [workspace.dependencies.stardust-xr-fusion]
git = "https://github.com/StardustXR/core.git" git = "https://github.com/StardustXR/core.git"

View File

@@ -46,6 +46,7 @@ async fn main() -> Result<()> {
} }
struct AppGrid { struct AppGrid {
root: Spatial,
apps: Vec<App>, apps: Vec<App>,
//style: TextStyle, //style: TextStyle,
} }
@@ -70,7 +71,10 @@ impl AppGrid {
.ok() .ok()
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
AppGrid { apps } AppGrid {
root: client.get_root().alias(),
apps,
}
} }
} }
impl RootHandler for AppGrid { impl RootHandler for AppGrid {
@@ -80,7 +84,7 @@ impl RootHandler for AppGrid {
} }
} }
fn save_state(&mut self) -> ClientState { fn save_state(&mut self) -> ClientState {
ClientState::default() ClientState::from_root(&self.root)
} }
} }

View File

@@ -14,5 +14,6 @@ mint = "0.5.9"
tween = "2.0.1" tween = "2.0.1"
tracing-subscriber = "0.3.17" tracing-subscriber = "0.3.17"
tokio = { workspace = true } tokio = { workspace = true }
serde = { workspace = true }
stardust-xr-fusion = { workspace = true } stardust-xr-fusion = { workspace = true }
stardust-xr-molecules = { workspace = true } stardust-xr-molecules = { workspace = true }

View File

@@ -20,7 +20,7 @@ use stardust_xr_molecules::{Grabbable, GrabbableSettings};
use std::f32::consts::PI; use std::f32::consts::PI;
use tween::{QuartInOut, Tweener}; use tween::{QuartInOut, Tweener};
use crate::{ACTIVATION_DISTANCE, APP_SIZE, DEFAULT_HEX_COLOR}; use crate::{State, ACTIVATION_DISTANCE, APP_SIZE, DEFAULT_HEX_COLOR};
// Model handling // Model handling
fn model_from_icon(parent: &Spatial, icon: &Icon) -> Result<Model> { fn model_from_icon(parent: &Spatial, icon: &Icon) -> Result<Model> {
@@ -65,13 +65,13 @@ pub struct App {
grabbable_shrink: Option<Tweener<f32, f64, QuartInOut>>, grabbable_shrink: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_grow: Option<Tweener<f32, f64, QuartInOut>>, grabbable_grow: Option<Tweener<f32, f64, QuartInOut>>,
grabbable_move: Option<Tweener<f32, f64, QuartInOut>>, grabbable_move: Option<Tweener<f32, f64, QuartInOut>>,
currently_shown: bool,
} }
impl App { impl App {
pub fn create_from_desktop_file( pub fn create_from_desktop_file(
parent: &Spatial, parent: &Spatial,
position: impl Into<Vector3<f32>>, position: impl Into<Vector3<f32>>,
desktop_file: DesktopFile, desktop_file: DesktopFile,
state: &State,
) -> Result<Self> { ) -> Result<Self> {
let position = position.into(); let position = position.into();
let field = BoxField::create(parent, Transform::identity(), [APP_SIZE; 3])?; let field = BoxField::create(parent, Transform::identity(), [APP_SIZE; 3])?;
@@ -87,6 +87,9 @@ impl App {
..Default::default() ..Default::default()
}, },
)?; )?;
if !state.unfurled {
grabbable.set_enabled(false)?;
}
grabbable.content_parent().set_spatial_parent(parent)?; grabbable.content_parent().set_spatial_parent(parent)?;
field.set_spatial_parent(grabbable.content_parent())?; field.set_spatial_parent(grabbable.content_parent())?;
let icon = icon let icon = icon
@@ -101,6 +104,9 @@ impl App {
&ResourceID::new_namespaced("protostar", "hexagon/hexagon"), &ResourceID::new_namespaced("protostar", "hexagon/hexagon"),
)?) )?)
})?; })?;
if !state.unfurled {
icon.set_enabled(false)?;
}
let label_style = TextStyle { let label_style = TextStyle {
character_height: APP_SIZE * 2.0, character_height: APP_SIZE * 2.0,
@@ -127,6 +133,12 @@ impl App {
) )
.ok() .ok()
}); });
if !state.unfurled {
if let Some(label) = label.as_ref() {
label.set_enabled(false)?;
}
}
Ok(App { Ok(App {
parent: parent.alias(), parent: parent.alias(),
position, position,
@@ -138,27 +150,25 @@ impl App {
grabbable_shrink: None, grabbable_shrink: None,
grabbable_grow: None, grabbable_grow: None,
grabbable_move: None, grabbable_move: None,
currently_shown: true,
}) })
} }
pub fn content_parent(&self) -> &Spatial { pub fn content_parent(&self) -> &Spatial {
self.grabbable.content_parent() self.grabbable.content_parent()
} }
pub fn toggle(&mut self) { pub fn apply_state(&mut self, state: &State) {
self.grabbable.set_enabled(!self.currently_shown).unwrap(); self.grabbable.set_enabled(state.unfurled).unwrap();
if self.currently_shown { if state.unfurled {
self.grabbable_move = Some(Tweener::quart_in_out(1.0, 0.0001, 0.25)); //TODO make the scale a parameter
} else {
self.icon.set_enabled(true).unwrap(); self.icon.set_enabled(true).unwrap();
if let Some(label) = self.label.as_ref() { if let Some(label) = self.label.as_ref() {
label.set_enabled(true).unwrap() label.set_enabled(true).unwrap()
} }
self.grabbable_move = Some(Tweener::quart_in_out(0.0001, 1.0, 0.25)); self.grabbable_move = Some(Tweener::quart_in_out(0.0001, 1.0, 0.25));
} else {
self.grabbable_move = Some(Tweener::quart_in_out(1.0, 0.0001, 0.25)); //TODO make the scale a parameter
} }
self.currently_shown = !self.currently_shown;
} }
pub fn frame(&mut self, info: FrameInfo) { pub fn frame(&mut self, info: FrameInfo, state: &State) {
let _ = self.grabbable.update(&info); let _ = self.grabbable.update(&info);
if let Some(grabbable_move) = &mut self.grabbable_move { if let Some(grabbable_move) = &mut self.grabbable_move {
@@ -193,7 +203,7 @@ impl App {
.content_parent() .content_parent()
.set_spatial_parent(&self.parent) .set_spatial_parent(&self.parent)
.unwrap(); .unwrap();
if self.currently_shown { if state.unfurled {
self.grabbable_grow = Some(Tweener::quart_in_out(0.0001, 1.0, 0.25)); self.grabbable_grow = Some(Tweener::quart_in_out(0.0001, 1.0, 0.25));
self.grabbable.cancel_angular_velocity(); self.grabbable.cancel_angular_velocity();
self.grabbable.cancel_linear_velocity(); self.grabbable.cancel_linear_velocity();

View File

@@ -8,16 +8,17 @@ use glam::Quat;
use hex::{HEX_CENTER, HEX_DIRECTION_VECTORS}; use hex::{HEX_CENTER, HEX_DIRECTION_VECTORS};
use manifest_dir_macros::directory_relative_path; use manifest_dir_macros::directory_relative_path;
use protostar::xdg::{get_desktop_files, parse_desktop_file, DesktopFile}; use protostar::xdg::{get_desktop_files, parse_desktop_file, DesktopFile};
use serde::{Deserialize, Serialize};
use stardust_xr_fusion::{ use stardust_xr_fusion::{
client::{Client, ClientState, FrameInfo, RootHandler}, client::{Client, ClientState, FrameInfo, RootHandler},
core::values::ResourceID, core::{schemas::flex::flexbuffers, values::ResourceID},
drawable::{MaterialParameter, Model, ModelPartAspect}, drawable::{MaterialParameter, Model, ModelPartAspect},
fields::BoxField, fields::BoxField,
node::NodeError, node::{NodeError, NodeType},
spatial::{SpatialAspect, Transform}, spatial::{Spatial, SpatialAspect, Transform},
}; };
use stardust_xr_molecules::{touch_plane::TouchPlane, Grabbable, GrabbableSettings, PointerMode}; use stardust_xr_molecules::{touch_plane::TouchPlane, Grabbable, GrabbableSettings, PointerMode};
use std::f32::consts::PI; use std::{f32::consts::PI, time::Duration};
const APP_SIZE: f32 = 0.06; const APP_SIZE: f32 = 0.06;
const PADDING: f32 = 0.005; const PADDING: f32 = 0.005;
@@ -38,7 +39,7 @@ async fn main() -> Result<()> {
let (client, event_loop) = Client::connect_with_async_loop().await?; let (client, event_loop) = Client::connect_with_async_loop().await?;
client.set_base_prefixes(&[directory_relative_path!("res")]); client.set_base_prefixes(&[directory_relative_path!("res")]);
let _root = client.wrap_root(AppHexGrid::new(&client))?; let _root = client.wrap_root(AppHexGrid::new(&client).await)?;
tokio::select! { tokio::select! {
_ = tokio::signal::ctrl_c() => (), _ = tokio::signal::ctrl_c() => (),
@@ -47,13 +48,27 @@ async fn main() -> Result<()> {
Ok(()) Ok(())
} }
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct State {
unfurled: bool,
}
struct AppHexGrid { struct AppHexGrid {
movable_root: Spatial,
apps: Vec<App>, apps: Vec<App>,
button: Button, button: Button,
state: State,
} }
impl AppHexGrid { impl AppHexGrid {
fn new(client: &Client) -> Self { async fn new(client: &Client) -> Self {
let button = Button::new(client).unwrap(); let state = flexbuffers::from_slice(&client.state().data).unwrap_or_default();
let movable_root =
Spatial::create(client.get_root(), Transform::identity(), false).unwrap();
let button = Button::new(client, &client.state()).unwrap();
tokio::time::sleep(Duration::from_millis(10)).await; // give it a bit of time to send the messages properly
let mut desktop_files: Vec<DesktopFile> = get_desktop_files() let mut desktop_files: Vec<DesktopFile> = get_desktop_files()
.filter_map(|d| parse_desktop_file(d).ok()) .filter_map(|d| parse_desktop_file(d).ok())
.filter(|d| !d.no_display) .filter(|d| !d.no_display)
@@ -78,6 +93,7 @@ impl AppHexGrid {
button.grabbable.content_parent(), button.grabbable.content_parent(),
hex.get_coords(), hex.get_coords(),
desktop_files.pop().unwrap(), desktop_files.pop().unwrap(),
&state,
) )
.unwrap(), .unwrap(),
); );
@@ -86,7 +102,12 @@ impl AppHexGrid {
} }
radius += 1; radius += 1;
} }
AppHexGrid { apps, button } AppHexGrid {
movable_root,
apps,
button,
state,
}
} }
} }
impl RootHandler for AppHexGrid { impl RootHandler for AppHexGrid {
@@ -99,8 +120,9 @@ impl RootHandler for AppHexGrid {
.unwrap() .unwrap()
.set_material_parameter("color", MaterialParameter::Color(BTN_SELECTED_COLOR)) .set_material_parameter("color", MaterialParameter::Color(BTN_SELECTED_COLOR))
.unwrap(); .unwrap();
self.state.unfurled = !self.state.unfurled;
for app in &mut self.apps { for app in &mut self.apps {
app.toggle(); app.apply_state(&self.state);
} }
} else if self.button.touch_plane.touch_stopped() { } else if self.button.touch_plane.touch_stopped() {
self.button self.button
@@ -111,12 +133,27 @@ impl RootHandler for AppHexGrid {
.unwrap(); .unwrap();
} }
for app in &mut self.apps { for app in &mut self.apps {
app.frame(info); app.frame(info, &self.state);
} }
} }
fn save_state(&mut self) -> ClientState { fn save_state(&mut self) -> ClientState {
ClientState::default() self.movable_root
.set_relative_transform(
self.button.grabbable.content_parent(),
Transform::from_translation([0.0; 3]),
)
.unwrap();
ClientState {
data: flexbuffers::to_vec(&self.state).unwrap(),
root: self.movable_root.alias(),
spatial_anchors: [(
"content_parent".to_string(),
self.button.grabbable.content_parent().alias(),
)]
.into_iter()
.collect(),
}
} }
} }
@@ -126,7 +163,7 @@ struct Button {
model: Model, model: Model,
} }
impl Button { impl Button {
fn new(client: &Client) -> Result<Self, NodeError> { fn new(client: &Client, state: &ClientState) -> Result<Self, NodeError> {
let field = BoxField::create(client.get_root(), Transform::identity(), [APP_SIZE; 3])?; let field = BoxField::create(client.get_root(), Transform::identity(), [APP_SIZE; 3])?;
let grabbable = Grabbable::create( let grabbable = Grabbable::create(
client.get_root(), client.get_root(),
@@ -161,6 +198,11 @@ impl Button {
model model
.model_part("Hex")? .model_part("Hex")?
.set_material_parameter("color", MaterialParameter::Color(BTN_COLOR))?; .set_material_parameter("color", MaterialParameter::Color(BTN_COLOR))?;
if let Some(content_parent) = state.spatial_anchors.get("content_parent") {
grabbable
.content_parent()
.set_relative_transform(content_parent, Transform::identity())?;
}
Ok(Button { Ok(Button {
touch_plane, touch_plane,
grabbable, grabbable,

View File

@@ -55,10 +55,7 @@ impl Application {
.ok_or(NodeError::DoesNotExist)?; .ok_or(NodeError::DoesNotExist)?;
tokio::task::spawn(async move { tokio::task::spawn(async move {
let Ok(startup_token) = client let Ok(startup_token) = client
.state_token(&ClientState { .state_token(&ClientState::from_root(&launch_space))
root: Some(launch_space.alias()),
..Default::default()
})
.await .await
else { else {
return; return;

View File

@@ -243,6 +243,6 @@ impl RootHandler for Single {
} }
fn save_state(&mut self) -> ClientState { fn save_state(&mut self) -> ClientState {
ClientState::default() ClientState::from_root(self.content_parent())
} }
} }

View File

@@ -15,5 +15,6 @@ tween = "2.0.1"
tracing-subscriber = "0.3.17" tracing-subscriber = "0.3.17"
walkdir = "2.4.0" walkdir = "2.4.0"
tokio = { workspace = true } tokio = { workspace = true }
serde = { workspace = true }
stardust-xr-fusion = { workspace = true } stardust-xr-fusion = { workspace = true }
stardust-xr-molecules = { workspace = true } stardust-xr-molecules = { workspace = true }

View File

@@ -8,9 +8,10 @@ use protostar::{
application::Application, application::Application,
xdg::{parse_desktop_file, DesktopFile, Icon, IconType}, xdg::{parse_desktop_file, DesktopFile, Icon, IconType},
}; };
use serde::{Deserialize, Serialize};
use stardust_xr_fusion::{ use stardust_xr_fusion::{
client::{Client, ClientState, FrameInfo, RootHandler}, client::{Client, ClientState, FrameInfo, RootHandler},
core::values::ResourceID, core::{schemas::flex::flexbuffers, values::ResourceID},
drawable::{ drawable::{
MaterialParameter, Model, ModelPartAspect, Text, TextBounds, TextFit, TextStyle, XAlign, MaterialParameter, Model, ModelPartAspect, Text, TextBounds, TextFit, TextStyle, XAlign,
YAlign, YAlign,
@@ -59,11 +60,16 @@ async fn main() -> Result<()> {
Ok(()) Ok(())
} }
#[derive(Debug, Serialize, Deserialize)]
struct State {
visible: bool,
}
struct Sirius { struct Sirius {
touch_plane: TouchPlane, touch_plane: TouchPlane,
model: Model, model: Model,
clients: Vec<App>, clients: Vec<App>,
visibility: bool, state: State,
grabbable: Grabbable, grabbable: Grabbable,
} }
impl Sirius { impl Sirius {
@@ -113,13 +119,13 @@ impl Sirius {
&ResourceID::new_namespaced("protostar", "button"), &ResourceID::new_namespaced("protostar", "button"),
)?; )?;
field.set_spatial_parent(grabbable.content_parent())?; field.set_spatial_parent(grabbable.content_parent())?;
let visibility = false; let state = State { visible: false };
Ok(Sirius { Ok(Sirius {
touch_plane, touch_plane,
model, model,
clients, clients,
visibility, state,
grabbable, grabbable,
}) })
} }
@@ -141,8 +147,8 @@ impl RootHandler for Sirius {
self.touch_plane.update(); self.touch_plane.update();
if self.touch_plane.touch_started() { if self.touch_plane.touch_started() {
println!("Touch started"); println!("Touch started");
self.visibility = !self.visibility; self.state.visible = !self.state.visible;
match self.visibility { match self.state.visible {
true => { true => {
for (pos, star) in self.clients.iter().enumerate() { for (pos, star) in self.clients.iter().enumerate() {
let mut starpos = (pos as f32 + 1.0) / 10.0; let mut starpos = (pos as f32 + 1.0) / 10.0;
@@ -210,7 +216,16 @@ impl RootHandler for Sirius {
} }
fn save_state(&mut self) -> ClientState { fn save_state(&mut self) -> ClientState {
ClientState::default() ClientState {
data: flexbuffers::to_vec(&self.state).unwrap(),
root: self.grabbable.content_parent().alias(),
spatial_anchors: [(
"content_parent".to_string(),
self.grabbable.content_parent().alias(),
)]
.into_iter()
.collect(),
}
} }
} }