Skip to content

Commit

Permalink
perfect spacemouse support
Browse files Browse the repository at this point in the history
  • Loading branch information
gilescope committed May 16, 2022
1 parent 65efb28 commit 3899e18
Show file tree
Hide file tree
Showing 6 changed files with 137 additions and 63 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ resolver = "2"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[features]
default = ["spacemouse"]
# 3d mouse support.
default = ["normalmouse"]
# 3d mouse support (it's best not to have both features enabled at once).
spacemouse = ["bevy_spacemouse"]
normalmouse = ["bevy_flycam"]

[dependencies]
sp-core = "*"
Expand All @@ -24,7 +25,7 @@ futures = "0.3.13"

winit = { version = "*", features = ["x11"] }
#sp-keyring = "5.0.0"
bevy_flycam = "0.7"
bevy_flycam = {version ="0.7", optional = true }
#bevy_text_mesh = "0.2"
bevy_mod_picking = "0.6"
hex = "*"
Expand All @@ -38,7 +39,7 @@ fastrand = "*"
bevy-inspector-egui = "0.10"
serde_bytes = "0.11"
#rayon = "*"
bevy_spacemouse = { path= "/home/gilescope/git/bevy-spacemouse-example", optional = true }
bevy_spacemouse = { git= "https://github.com/gilescope/bevy_spacemouse.git", rev="5a5879132c191a66c7486eb232d303b33ebad3bd", optional = true }
serde = "*"
bevy_egui = "*"
egui = "*"
Expand Down
19 changes: 15 additions & 4 deletions shell.nix
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@

{ pkgs ? import <nixpkgs> {} }:
with pkgs; mkShell {
# { pkgs ? import <nixpkgs> {} }:
let
mozillaOverlay =
import (builtins.fetchGit {
url = "https://github.com/mozilla/nixpkgs-mozilla.git";
rev = "e1f7540fc0a8b989fb8cf701dc4fd7fc76bcf168";
});
nixpkgs = import <nixpkgs> { overlays = [ mozillaOverlay ]; };
rust-nightly = with nixpkgs; ((rustChannelOf { date = "2022-05-14"; channel = "nightly"; }).rust.override {
});
in
with nixpkgs; mkShell {
nativeBuildInputs = [
pkgconfig
clang lld # To use lld linker
];
buildInputs = [
udev alsaLib vulkan-loader
libspnav udev alsaLib vulkan-loader
xlibsWrapper xorg.libXcursor xorg.libXrandr xorg.libXi # To use x11 feature
libxkbcommon wayland # To use wayland feature
libspnav
rust-nightly
];
shellHook = ''export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${pkgs.lib.makeLibraryPath [
udev alsaLib vulkan-loader
Expand Down
22 changes: 19 additions & 3 deletions src/datasource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ pub async fn watch_blocks(
tx: ABlocks,
url: String,
relay_id: String,
as_of: Option<&str>
) -> Result<(), Box<dyn std::error::Error>> {
// use core::slice::SlicePattern;
// use scale_info::form::PortableForm;
Expand Down Expand Up @@ -908,7 +909,7 @@ pub struct PolkaBlock {
pub events: Vec<DataEvent>,
}
use core::slice::SlicePattern;
pub async fn watch_events(tx: ABlocks, url: &str) -> Result<(), Box<dyn std::error::Error>> {
pub async fn watch_events(tx: ABlocks, url: &str, as_of: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
let api = ClientBuilder::new()
.set_url(url)
.build()
Expand All @@ -925,9 +926,19 @@ pub async fn watch_events(tx: ABlocks, url: &str) -> Result<(), Box<dyn std::err
let mut data_events = vec![];
for ev_raw in events.iter_raw() {
let mut details = Details::default();
let mut link = vec![];
let mut link = vec![];

if let Ok(ev) = &ev_raw {
details.pallet = ev.pallet.clone();
details.variant = ev.variant.clone();

if details.pallet == "XcmPallet" && details.variant == "Attempted" {
use crate::polkadot::runtime_types::xcm::v2::traits::Error;
use crate::polkadot::runtime_types::xcm::v2::traits::Outcome;//TODO version
let result = <Outcome as Decode>::decode(&mut ev.data.as_slice());
details.flattern = format!("{:#?}", result);
}

let ev = <polkadot::Event as Decode>::decode(&mut ev.data.as_slice());
if let Ok(event) = ev {
// println!("{:#?}", ev);
Expand All @@ -940,7 +951,12 @@ pub async fn watch_events(tx: ABlocks, url: &str) -> Result<(), Box<dyn std::err
println!("got here rnrtnrtrtnrt");
println!("{:#?}", event);

let received_hash = format!("{}-{}",blockhash, hex::encode(msg));
// Hypothesis: there's no sent_at because it would be the sent at of the individual chain.
// https://substrate.stackexchange.com/questions/2627/how-can-i-see-what-xcm-message-the-moonbeam-river-parachain-has-sent
// TL/DR: we have to wait before we can match up things going upwards...

// blockhash of the recieving block would be incorrect.
let received_hash = format!("{}",hex::encode(msg));
println!("recieved UMP hash {}", &received_hash);
link.push(received_hash);
// // msg is a msg id! not decodable - match against hash of original
Expand Down
100 changes: 70 additions & 30 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use bevy::ecs as bevy_ecs;
use bevy::prelude::*;
use bevy::winit::WinitSettings;
use bevy_ecs::prelude::Component;
use bevy_flycam::FlyCam;
use bevy_flycam::MovementSettings;
use bevy_flycam::NoCameraPlayerPlugin;
#[cfg(feature = "normalmouse")]
use bevy_flycam::{FlyCam, MovementSettings, NoCameraPlayerPlugin};

use bevy_inspector_egui::{plugin::InspectorWindows, Inspectable, InspectorPlugin};
use bevy_mod_picking::*;
//use bevy_egui::render_systems::ExtractedWindowSizes;
Expand All @@ -25,15 +25,33 @@ mod style;
use crate::details::Details;
use bevy_inspector_egui::RegisterInspectable;
#[cfg(feature = "spacemouse")]
use bevy_spacemouse::{SpaceMouseControllable, SpaceMousePlugin};
use bevy_spacemouse::{SpaceMouseRelativeControllable, SpaceMousePlugin};
use sp_core::H256;
use std::convert::AsRef;


// #[subxt::subxt(runtime_metadata_path = "wss://kusama-rpc.polkadot.io:443")]
// pub mod polkadot {}
#[subxt::subxt(runtime_metadata_path = "polkadot_metadata.scale")]
pub mod polkadot {}

#[cfg(feature = "spacemouse")]
pub struct MovementSettings {
pub sensitivity: f32,
pub speed: f32,
}

#[cfg(feature = "spacemouse")]
impl Default for MovementSettings {
fn default() -> Self {
Self {
sensitivity: 0.00012,
speed: 12.,
}
}
}


static RELAY_BLOCKS: AtomicU32 = AtomicU32::new(0);
static RELAY_BLOCKS2: AtomicU32 = AtomicU32::new(0);

Expand Down Expand Up @@ -63,6 +81,13 @@ mod details;
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let selected_env = Env::Prod; //if std::env::args().next().is_some() { Env::Test } else {Env::Prod};


let mut as_of = None;

if let Env::Local = selected_env {
as_of = Some("0"); // If local show from the first block...
}

let relays = networks::get_network(&selected_env);
let is_self_sovereign = selected_env.is_self_sovereign();
let relays = relays
Expand All @@ -79,14 +104,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let clone_chains_for_lanes = relays.clone();
let mut app = App::new();
app.insert_resource(Msaa { samples: 4 })
.add_plugins(DefaultPlugins)
.add_plugins(DefaultPlugins);
// .insert_resource(WinitSettings::desktop_app()) - this messes up the 3d space mouse?
.insert_resource(MovementSettings {

app.insert_resource(MovementSettings {
sensitivity: 0.00020, // default: 0.00012
speed: 12.0, // default: 12.0
})
.insert_resource(movement::MouseCapture::default())
.add_plugin(NoCameraPlayerPlugin);
});

#[cfg(feature = "normalmouse")]
app.add_plugin(NoCameraPlayerPlugin);
app.insert_resource(movement::MouseCapture::default());

#[cfg(feature = "spacemouse")]
app.add_plugin(SpaceMousePlugin);
Expand All @@ -100,16 +128,24 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// .add_plugin(LogDiagnosticsPlugin::default())
// .add_plugin(WorldInspectorPlugin::new())
.add_plugin(PolylinePlugin)
.add_system(movement::scroll)
// .add_system(movement::scroll)
.add_startup_system(
move |commands: Commands,
meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>| {
materials: ResMut<Assets<StandardMaterial>>
| {
let clone_chains_for_lanes = clone_chains_for_lanes.clone();
setup(commands, meshes, materials, clone_chains_for_lanes);
},
)
.add_system(movement::player_move_arrows)
);
#[cfg(feature = "spacemouse")]
app.add_startup_system(
move |mut scale: ResMut<bevy_spacemouse::Scale>| {
scale.rotate_scale = 0.00015;
scale.translate_scale = 0.004;
},
);
app.add_system(movement::player_move_arrows)
.add_system(rain)
.add_system(right_click_system)
.add_startup_system(details::configure_visuals)
Expand Down Expand Up @@ -164,8 +200,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
while reconnects < 20 {
println!("Connecting to {}", &url);
let _ = async_std::task::block_on(datasource::watch_events(
lock_clone.clone(),
lock_clone.clone(),
&url,
as_of
));
println!("Problem with {} events (retrys left {})", &url, reconnects);
std::thread::sleep(std::time::Duration::from_secs(20));
Expand All @@ -185,6 +222,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
lock_clone.clone(),
url_clone.clone(),
relay_id.to_string(),
as_of
));
println!(
"Problem with {} blocks (retries left {})",
Expand Down Expand Up @@ -684,11 +722,7 @@ fn add_blocks<'a>(
println!("creating rainbow!");

let mut vertices = vec![
Vec3::new(
source_global.translation.x,
source_global.translation.y,
source_global.translation.z,
),
source_global.translation,
Vec3::new(px, target_y * build_direction, pz),
];
rainbow(&mut vertices, 50);
Expand Down Expand Up @@ -950,7 +984,7 @@ pub struct UpdateTimer {

pub fn print_events(
mut events: EventReader<PickingEvent>,
mut query2: Query<Entity>,
mut query2: Query<(Entity, &Details)>,
mut inspector: ResMut<Inspector>,
// mut inspector_windows: Res<InspectorWindows>,
) {
Expand All @@ -968,14 +1002,14 @@ pub fn print_events(
// commands.entity(entity).despawn();
// });

let entity = query2.get_mut(*entity).unwrap();
let (entity, details) = query2.get_mut(*entity).unwrap();

if inspector.active == Some(entity) {
print!("deselected current selection");
inspector.active = None;
} else {
inspector.active = Some(entity);
}
// if inspector.active == Some(details) {
// print!("deselected current selection");
// inspector.active = None;
// } else {
inspector.active = Some(details.clone());
// }

// info!("{}", details.hover.as_str());
// decode_ex!(events, crate::polkadot::ump::events::UpwardMessagesReceived, value, details);
Expand Down Expand Up @@ -1087,12 +1121,15 @@ fn setup(
},
..default()
});
#[cfg(feature = "normalmouse")]
entity_comands
.insert(FlyCam)
.insert(FlyCam);
entity_comands
.insert(Viewport)
.insert_bundle(PickingCameraBundle { ..default() });

#[cfg(feature = "spacemouse")]
entity_comands.insert(SpaceMouseControllable);
entity_comands.insert(SpaceMouseRelativeControllable);

use std::time::Duration;
commands.insert_resource(UpdateTimer {
Expand All @@ -1119,9 +1156,12 @@ fn setup(
#[derive(Inspectable, Default)]
pub struct Inspector {
#[inspectable(deletable = false)]
active: Option<Entity>,
active: Option<Details>,
}

#[derive(Component)]
pub struct Viewport;

// #[cfg(target_arch = "wasm32")]
// pub mod html_body {
// use web_sys::HtmlElement;
Expand Down
49 changes: 27 additions & 22 deletions src/movement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ use bevy::prelude::*;
use bevy::render::camera::CameraProjection;
use bevy::transform::components::Transform;
use bevy::window::Windows;
use bevy_flycam::FlyCam;
use bevy_flycam::MovementSettings;
use crate::Viewport;

#[cfg(feature = "normalmouse")]
use bevy_flycam::{FlyCam,MovementSettings};
#[cfg(feature = "spacemouse")]
use crate::MovementSettings;


pub struct MouseCapture(pub bool);

Expand All @@ -25,7 +30,7 @@ pub fn player_move_arrows(
time: Res<Time>,
windows: Res<Windows>,
mut settings: ResMut<MovementSettings>,
mut query: Query<&mut Transform, With<FlyCam>>,
mut query: Query<&mut Transform, With<Viewport>>,
mut toggle_mouse_capture: ResMut<MouseCapture>,
) {
let window = windows.get_primary().unwrap();
Expand Down Expand Up @@ -68,25 +73,25 @@ pub fn player_move_arrows(
}
}

/// the mouse-scroll changes the field-of-view of the camera
pub fn scroll(
mut mouse_wheel_events: EventReader<MouseWheel>,
windows: Res<Windows>,
mut query: Query<(&FlyCam, &mut Camera, &mut PerspectiveProjection)>,
) {
// for event in mouse_wheel_events.iter() {
// for (_camera, mut camera, mut project) in query.iter_mut() {
// project.fov = (project.fov - event.y * 0.01).abs();
// let prim = windows.get_primary().unwrap();
// the mouse-scroll changes the field-of-view of the camera
// pub fn scroll(
// mut mouse_wheel_events: EventReader<MouseWheel>,
// windows: Res<Windows>,
// mut query: Query<(&FlyCam, &mut Camera, &mut PerspectiveProjection)>,
// ) {
// // for event in mouse_wheel_events.iter() {
// // for (_camera, mut camera, mut project) in query.iter_mut() {
// // project.fov = (project.fov - event.y * 0.01).abs();
// // let prim = windows.get_primary().unwrap();

// //Calculate projection with new fov
// project.update(prim.width(), prim.height());
// // //Calculate projection with new fov
// // project.update(prim.width(), prim.height());

// //Update camera with the new fov
// camera.projection_matrix = project.get_projection_matrix();
// camera.depth_calculation = project.depth_calculation();
// // //Update camera with the new fov
// // camera.projection_matrix = project.get_projection_matrix();
// // camera.depth_calculation = project.depth_calculation();

// // println!("FOV: {:?}", project.fov);
// }
// }
}
// // // println!("FOV: {:?}", project.fov);
// // }
// // }
// }

0 comments on commit 3899e18

Please sign in to comment.