From d3fa22e9876a21ae3eb012e567da065695393f20 Mon Sep 17 00:00:00 2001 From: The Nomad Date: Mon, 19 Oct 2026 16:07:38 -0400 Subject: [PATCH] 3D mouse calibration in Preferences (#2326) Adds a 3D mouse calibration section to Preferences (#1463). --- Cargo.lock | 4 + apps/solidcraft-web/src/space_mouse.rs | 116 +- apps/solidcraft/src/space_mouse.rs | 198 ++- apps/solidcraft/src/space_mouse/hidraw.rs | 30 +- assets/locales/cs.json | 28 + assets/locales/de.json | 28 + assets/locales/en.json | 28 + assets/locales/es.json | 28 + assets/locales/fr.json | 28 + assets/locales/gl.json | 28 + assets/locales/it.json | 28 + assets/locales/ja.json | 28 + assets/locales/ko.json | 28 + assets/locales/pt-BR.json | 28 + assets/locales/ru.json | 28 + assets/locales/tr.json | 28 + assets/locales/uk.json | 28 + assets/locales/zh.json | 28 + crates/space-mouse/Cargo.toml | 4 + crates/space-mouse/src/calibration.rs | 1357 +++++++++++++++++ crates/space-mouse/src/lib.rs | 4 + crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/prefs.rs | 79 +- crates/ui-egui/src/space_mouse.rs | 167 +- crates/ui-egui/src/space_mouse_calibration.rs | 157 ++ 26 files changed, 2461 insertions(+), 52 deletions(-) create mode 100644 crates/space-mouse/src/calibration.rs create mode 100644 crates/ui-egui/src/space_mouse_calibration.rs diff --git a/Cargo.lock b/Cargo.lock index 8a2231f10..c421d34bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4268,6 +4268,9 @@ dependencies = [ [[package]] name = "solidcraft-space-mouse" version = "0.16.2" +dependencies = [ + "serde", +] [[package]] name = "solidcraft-ui-egui" @@ -4286,6 +4289,7 @@ dependencies = [ "sha2 0.10.9", "solidcraft-engine", "solidcraft-gpu", + "solidcraft-space-mouse", "tiny-skia", "toml", "ttf-parser", diff --git a/apps/solidcraft-web/src/space_mouse.rs b/apps/solidcraft-web/src/space_mouse.rs index 07394de56..3fecfd027 100644 --- a/apps/solidcraft-web/src/space_mouse.rs +++ b/apps/solidcraft-web/src/space_mouse.rs @@ -7,7 +7,7 @@ //! navigation takes them with 3DxWare's object-mode mapping, as the Linux app does without a //! profile. -use solidcraft_ui_egui::space_mouse::{Axes, FULL_SCALE}; +use solidcraft_ui_egui::space_mouse::{Axes, Calibration, FULL_SCALE, calibrated}; /// Logitech's vendor id, which older 3Dconnexion devices carry, and those devices' product ids /// (usb.ids). Logitech's own gamepads and wheels carry the same vendor id. @@ -60,9 +60,43 @@ pub fn axes(values: &[f64]) -> Option { Some(Axes { translation: [raw(0)?, raw(1)?, raw(2)?], rotation: [raw(3)?, raw(4)?, raw(5)?] }) } +/// What a calibration of the gamepad with this id is saved under: `web` and its vendor and +/// product ids. +pub fn device_key(id: &str) -> Option { + vendor_product(id).map(|(vendor, product)| format!("web {vendor:04x}:{product:04x}")) +} + /// The 3D mouse to read among the ones listed: the first device, else the first joystick. -pub fn choose(found: impl IntoIterator) -> Option { - found.into_iter().min_by_key(|(source, _)| *source).map(|(_, axes)| axes) +pub fn choose(found: impl IntoIterator) -> Option { + found.into_iter().min_by_key(|(source, _)| *source).map(|(_, reading)| reading) +} + +/// Whether the cap is moving as the next frame will see it: through the device's calibration +/// (as of the last frame) when it has one. The idle page wakes for a short-range device's push, +/// and not for a device resting off zero; the wheel filter goes by the same. +pub fn moving(axes: Axes, calibration: Option) -> bool { + calibrated(axes, calibration).moving() +} + +/// The calibration as of the last frame, and the device it was for. +pub type Cached = (Option, Option); + +/// Whether the cap of `device` is moving, judged with the calibration kept from the last frame: +/// `None` when that was for another device, so another's calibration never judges this one. The +/// waker then lets a frame look, which brings the cache up to date. +pub fn moving_as_cached(device: &Option, axes: Axes, cached: &Cached) -> Option { + (*device == cached.0).then(|| moving(axes, cached.1)) +} + +/// Whether the idle page's timer redraws: when the cap is moving as the last frame's calibration +/// judges it, when the device read isn't the one that calibration was for (a frame then judges +/// it with its own), and once when the device the last frame read is gone, so the page shows +/// that. With no device, and none last frame, it stays quiet. +pub fn wakes(reading: Option<(Option, Axes)>, cached: &Cached) -> bool { + match reading { + Some((device, axes)) => moving_as_cached(&device, axes, cached).unwrap_or(true), + None => cached.0.is_some(), + } } #[cfg(target_arch = "wasm32")] @@ -70,29 +104,29 @@ pub use browser::SpaceMouse; #[cfg(target_arch = "wasm32")] mod browser { - use std::cell::Cell; + use std::cell::{Cell, RefCell}; use std::rc::Rc; use solidcraft_ui_egui::SolveApp; - use solidcraft_ui_egui::space_mouse::{Axes, DriverMapping, navigate_frame}; + use solidcraft_ui_egui::space_mouse::{Axes, DriverMapping, calibration, navigate_frame}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; use solidcraft_ui_egui::space_mouse::WheelGuard; - use super::{axes, choose, source}; + use super::{Cached, axes, choose, device_key, moving_as_cached, source, wakes}; /// How often the page looks for the cap starting to move while nothing else redraws. const WAKE_MS: i32 = 50; - /// The 3D mouse the browser lists, if any. - fn read() -> Option { + /// The 3D mouse the browser lists, if any: its calibration key and its axes. + fn read() -> Option<(Option, Axes)> { let pads = web_sys::window()?.navigator().get_gamepads().ok()?; choose(pads.iter().filter_map(|pad| { let pad = pad.dyn_into::().ok().filter(web_sys::Gamepad::connected)?; let source = source(&pad.id())?; let values: Vec = pad.axes().iter().map(|v| v.as_f64().unwrap_or(f64::NAN)).collect(); - Some((source, axes(&values)?)) + Some((source, (device_key(&pad.id()), axes(&values)?))) })) } @@ -100,6 +134,8 @@ mod browser { #[derive(Default)] pub struct SpaceMouse { axes: Axes, + /// The 3D mouse being read, as `SolveApp::space_mouse` keeps it. + device: Option, /// The previous frame's time and the step since it (seconds). last: Option, seconds: f64, @@ -111,6 +147,8 @@ mod browser { waking: bool, /// Navigation is on (the waker reads it). enabled: Rc>, + /// The calibration as of the last frame and its device (the waker and the wheel filter read it). + cached: Rc>, } impl SpaceMouse { @@ -131,14 +169,18 @@ mod browser { } let reading = read(); if reading.is_some() && !self.waking { - self.waking = wake(ctx, &self.enabled); + self.waking = wake(ctx, &self.enabled, &self.cached); } - // Inside the dead zone is rest: a cap resting just off zero doesn't keep redrawing. - self.axes = reading.filter(|axes| axes.moving()).unwrap_or_default(); - self.wheel.filter(self.axes.moving(), now, &mut raw.events); + // As read: calibration needs the readings at rest too, and `navigate_frame` leaves a + // cap resting inside the dead zone alone. + (self.device, self.axes) = reading.unwrap_or_default(); + let moving = moving_as_cached(&self.device, self.axes, &self.cached.borrow()).unwrap_or_else(|| self.axes.moving()); + self.wheel.filter(moving, now, &mut raw.events); } pub fn logic(&self, app: &mut SolveApp, ctx: &egui::Context) { + app.space_mouse.device.clone_from(&self.device); + *self.cached.borrow_mut() = (self.device.clone(), calibration(app)); navigate_frame(app, ctx, DriverMapping::object_mode(), self.axes, self.seconds); } } @@ -156,11 +198,11 @@ mod browser { /// The browser sends no event when a gamepad moves, so a timer looks while the app is idle and /// redraws when the cap starts moving; the frames that follow keep going on their own. - fn wake(ctx: &egui::Context, enabled: &Rc>) -> bool { + fn wake(ctx: &egui::Context, enabled: &Rc>, cached: &Rc>) -> bool { let Some(window) = web_sys::window() else { return false }; - let (ctx, enabled) = (ctx.clone(), Rc::clone(enabled)); + let (ctx, enabled, cached) = (ctx.clone(), Rc::clone(enabled), Rc::clone(cached)); let tick = Closure::::new(move || { - if enabled.get() && read().is_some_and(Axes::moving) { + if enabled.get() && wakes(read(), &cached.borrow()) { ctx.request_repaint(); } }); @@ -192,6 +234,46 @@ mod tests { } } + #[test] + fn a_calibration_is_saved_under_the_ids_whichever_browser_lists_it() { + assert_eq!(device_key("SpaceMouse Pro (Vendor: 046d Product: c62b)").as_deref(), Some("web 046d:c62b")); + assert_eq!(device_key("46d-c62b-SpaceMouse Pro").as_deref(), Some("web 046d:c62b")); + assert_eq!(device_key("Xbox Wireless Controller"), None); + } + + #[test] + fn the_idle_page_wakes_for_motion_as_calibrated_not_as_read() { + let axis = + |source, rest, full| solidcraft_ui_egui::space_mouse::AxisCalibration { source, reversed: false, rest, dead_zone: 0, full: [full; 2] }; + // A short-range device: 15 of its 50 is under the raw dead zone, but 105 of 350 calibrated. + let short = Calibration { dead_zone_share: 0.0, axes: std::array::from_fn(|r| axis(r, 0, 50)) }; + let push = Axes { translation: [15, 0, 0], rotation: [0; 3] }; + assert!(!push.moving() && moving(push, Some(short))); + // A device resting at 100 on every axis: past the raw dead zone, but at rest calibrated. + let offset = Calibration { dead_zone_share: 0.0, axes: std::array::from_fn(|r| axis(r, 100, 350)) }; + let resting = Axes { translation: [100; 3], rotation: [100; 3] }; + assert!(resting.moving() && !moving(resting, Some(offset))); + // Without a calibration, as read. + assert!(!moving(push, None) && moving(resting, None)); + // Kept from the last frame: only for the device it was for. + let (a, b) = (Some("web 256f:c63a".to_string()), Some("web 1234:5678".to_string())); + assert_eq!(moving_as_cached(&b, push, &(b.clone(), Some(short))), Some(true)); + assert_eq!(moving_as_cached(&b, push, &(a.clone(), Some(offset))), None, "A's calibration doesn't judge B"); + assert_eq!(moving_as_cached(&b, push, &(None, None)), None); + assert_eq!(moving_as_cached(&a, resting, &(a.clone(), None)), Some(true), "A was read without a calibration"); + } + + #[test] + fn the_idle_page_wakes_once_for_a_device_change_and_stays_quiet_without_one() { + let (a, b) = (Some("web 256f:c63a".to_string()), Some("web 1234:5678".to_string())); + let still = Axes::default(); + let last_frame_read_a: Cached = (a.clone(), None); + assert!(!wakes(Some((a.clone(), still)), &last_frame_read_a), "A, at rest"); + assert!(wakes(Some((b.clone(), still)), &last_frame_read_a), "A to B: a frame looks at B"); + assert!(wakes(None, &last_frame_read_a), "A to none: a frame shows it's gone"); + assert!(!wakes(None, &(None, None)), "none to none: quiet"); + } + #[test] fn gamepads_and_other_logitech_devices_are_not_3d_mice() { for id in [ @@ -280,6 +362,6 @@ mod tests { assert_eq!(choose([(Source::VirtualJoystick, other)]), Some(other)); // Two devices: the first listed. assert_eq!(choose([(Source::Device, moving), (Source::Device, other)]), Some(moving)); - assert_eq!(choose([]), None); + assert_eq!(choose::([]), None); } } diff --git a/apps/solidcraft/src/space_mouse.rs b/apps/solidcraft/src/space_mouse.rs index 96c0d1ab3..9089ceac7 100644 --- a/apps/solidcraft/src/space_mouse.rs +++ b/apps/solidcraft/src/space_mouse.rs @@ -19,7 +19,7 @@ use quick_xml::Reader; use quick_xml::events::Event; use solidcraft_space_mouse::Layout; use solidcraft_ui_egui::SolveApp; -use solidcraft_ui_egui::space_mouse::{Axes, AxisRule, DriverMapping, WheelGuard, navigate_frame}; +use solidcraft_ui_egui::space_mouse::{Axes, AxisRule, Calibration, DriverMapping, WheelGuard, calibrated, calibration, navigate_frame}; const STALE_AFTER: Duration = Duration::from_millis(150); /// Whether the 3Dconnexion driver (macOS) has the device: it then reports the cap, and reading @@ -165,8 +165,36 @@ fn load_driver_mapping() -> Option { parse_driver_mapping(&xml) } +/// Where the reading comes from, which a calibration is saved under (`Source::key`). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Source { + /// The device itself, with its vendor and product ids when known. + Hid(Option<(u16, u16)>), + /// spacenavd, which may have swapped or inverted axes on its own (`spnavcfg`). + #[cfg(target_os = "linux")] + Spacenavd, + /// The 3Dconnexion driver (macOS), which applies its own settings first. + #[cfg(target_os = "macos")] + Driver, +} + +impl Source { + fn key(self) -> String { + match self { + Self::Hid(Some((vendor, product))) => format!("hid {vendor:04x}:{product:04x}"), + Self::Hid(None) => "hid".into(), + #[cfg(target_os = "linux")] + Self::Spacenavd => "spacenavd".into(), + #[cfg(target_os = "macos")] + Self::Driver => "3dxware".into(), + } + } +} + #[derive(Clone, Copy)] struct Reading { + /// The device being read; none between devices. + device: Option, axes: Axes, /// When each of X, Y, Z, Rx, Ry and Rz last arrived. Each ages on its own: a device may send /// translation and rotation in separate reports, or spread even one group over several. @@ -179,15 +207,18 @@ struct Reading { impl Reading { fn new(now: Instant) -> Self { - Self { axes: Axes::default(), at: [now; 6], held: false } + Self { device: None, axes: Axes::default(), at: [now; 6], held: false } } - fn current(self, now: Instant) -> Axes { + /// The axes at `now`. One with nothing fresh reads as `rest`: the device's own rest when it + /// is calibrated, so a device that rests off zero calibrates to no motion rather than drifting. + fn current(self, now: Instant, rest: Axes) -> Axes { let mut axes = self.axes; if !self.held { - for (value, at) in axes.translation.iter_mut().chain(axes.rotation.iter_mut()).zip(self.at) { + let rest = rest.translation.into_iter().chain(rest.rotation); + for ((value, at), rest) in axes.translation.iter_mut().chain(axes.rotation.iter_mut()).zip(self.at).zip(rest) { if now.duration_since(at) >= STALE_AFTER { - *value = 0; + *value = rest; } } } @@ -195,6 +226,11 @@ impl Reading { } } +/// The raw axes at the device's rest, which calibrate to no motion; 0 without a calibration. +fn at_rest(calibration: Option) -> Axes { + calibration.map(|calibration| calibration.raw_rest().into()).unwrap_or_default() +} + /// The Generic Desktop "Multi-Axis Controller" usage names a 3D mouse's motion interface, whoever /// made it, and excludes ordinary mice and the keyboard interfaces of 3D mice. #[cfg(any(target_os = "windows", target_os = "macos"))] @@ -233,11 +269,22 @@ fn publish(ctx: &Context, shared: &Mutex, layout: Layout, report: &[u8] #[cfg(target_os = "linux")] fn publish_held(ctx: &Context, shared: &Mutex, axes: Axes) { if let Ok(mut reading) = shared.lock() { - *reading = Reading { axes, held: true, ..Reading::new(Instant::now()) }; + *reading = Reading { device: reading.device, axes, held: true, ..Reading::new(Instant::now()) }; ctx.request_repaint(); } } +/// A device is open: say which, so its calibration applies. +fn connected(ctx: &Context, shared: &Mutex, source: Source) { + if let Ok(mut reading) = shared.lock() { + // Nothing has arrived from it yet, so every axis starts out stale. + let now = Instant::now(); + let stale = now.checked_sub(STALE_AFTER).unwrap_or(now); + *reading = Reading { device: Some(source), at: [stale; 6], ..Reading::new(now) }; + } + ctx.request_repaint(); +} + /// The device is gone: stop reporting its last position. fn reset(ctx: &Context, shared: &Mutex) { if let Ok(mut reading) = shared.lock() { @@ -255,7 +302,7 @@ fn reader(ctx: Context, shared: Arc>) { loop { if let Err(error) = api.refresh_devices() { log::warn!("3D mouse: device scan failed: {error}"); - } else if let Some((device, layout)) = api.device_list().filter(|info| is_3d_mouse(info)).find_map(|info| { + } else if let Some((device, layout, ids)) = api.device_list().filter(|info| is_3d_mouse(info)).find_map(|info| { let device = info .open_device(&api) .inspect_err(|error| { @@ -267,8 +314,9 @@ fn reader(ctx: Context, shared: Arc>) { }) .ok()?; let layout = device_layout(&device, info.vendor_id())?; - Some((device, layout)) + Some((device, layout, (info.vendor_id(), info.product_id()))) }) { + connected(&ctx, &shared, Source::Hid(Some(ids))); let mut report = [0_u8; REPORT_BUFFER_BYTES]; loop { match device.read_timeout(&mut report, 100) { @@ -323,6 +371,7 @@ fn reader(ctx: Context, shared: Arc>) { loop { if let Some(daemon) = spacenavd::connect() { log::info!("3D mouse: reading spacenavd, which applies the spnavcfg settings"); + connected(&ctx, &shared, Source::Spacenavd); spacenavd::read(daemon, |axes| publish_held(&ctx, &shared, axes)); reset(&ctx, &shared); } else if let Some(device) = hidraw::find() { @@ -330,6 +379,7 @@ fn reader(ctx: Context, shared: Arc>) { Ok(mut file) => { denied = None; log::info!("3D mouse: reading {}", device.path.display()); + connected(&ctx, &shared, Source::Hid(device.ids)); let mut report = [0_u8; REPORT_BUFFER_BYTES]; loop { match file.read(&mut report) { @@ -365,7 +415,10 @@ fn start_driver_client(ctx: &Context, shared: &Arc>) { let started = solidcraft_3dx_client::start( "SolidCraft", move |event| match event { - Event::DeviceAdded => DRIVER_CONNECTED.store(true, Ordering::Relaxed), + Event::DeviceAdded => { + DRIVER_CONNECTED.store(true, Ordering::Relaxed); + connected(&ctx, &shared, Source::Driver); + } Event::DeviceRemoved => { DRIVER_CONNECTED.store(false, Ordering::Relaxed); reset(&ctx, &shared); @@ -398,6 +451,9 @@ pub struct SpaceMouse { /// Drops 3DxWare's emulated wheel while the cap moves (#1380). wheel: WheelGuard, started: Instant, + /// The calibration as of the last frame and the device it is for, for the wheel filter, which + /// runs before the app sees the frame. + calibration: Option<(Source, Calibration)>, } impl SpaceMouse { @@ -418,6 +474,7 @@ impl SpaceMouse { mapping_checked_at: now, wheel: WheelGuard::default(), started: now, + calibration: None, } } @@ -431,7 +488,15 @@ impl SpaceMouse { if !enabled { return; } - let moving = self.shared.lock().map(|reading| reading.current(now).moving()).unwrap_or(false); + let moving = self + .shared + .lock() + .map(|reading| { + // Only the calibration of the device being read: another's would misjudge it. + let calibration = self.calibration.filter(|(source, _)| Some(*source) == reading.device).map(|(_, calibration)| calibration); + calibrated(reading.current(now, at_rest(calibration)), calibration).moving() + }) + .unwrap_or(false); self.wheel.filter(moving, now.duration_since(self.started).as_secs_f64(), &mut raw.events); } @@ -451,11 +516,16 @@ impl SpaceMouse { } self.mapping_checked_at = now; } - let axes = match self.shared.lock() { - Ok(reading) => reading.current(now), - Err(_) => return, - }; - navigate_frame(app, ctx, self.driver_mapping, axes, seconds); + let Ok(reading) = self.shared.lock().map(|reading| *reading) else { return }; + app.space_mouse.device = reading.device.map(Source::key); + let calibration = calibration(app); + self.calibration = reading.device.zip(calibration); + // While this device is being calibrated, an axis with nothing fresh reads 0, as a HID + // device's silence means: the old calibration's rest isn't fed back into the new one. A + // calibration of another device doesn't count; it ends in `navigate_frame`. + let calibrating = app.space_mouse.calibrating.as_ref().is_some_and(|(device, _)| app.space_mouse.device.as_ref() == Some(device)); + let rest = if calibrating { Axes::default() } else { at_rest(calibration) }; + navigate_frame(app, ctx, self.driver_mapping, reading.current(now, rest), seconds); } } @@ -477,14 +547,14 @@ mod tests { let mut reading = Reading::new(now); let layout = Layout::default(); assert!(!decode_report(&[1, 1, 2], layout, &mut reading, now)); - assert_eq!(reading.current(now), Axes::default()); + assert_eq!(reading.current(now, Axes::default()), Axes::default()); assert!(decode_report(&[1, 0x9c, 0xff, 0x2c, 0x01, 0, 0], layout, &mut reading, now)); assert!(decode_report(&[2, 0, 0, 1, 0, 0xff, 0xff], layout, &mut reading, now)); - assert_eq!(reading.current(now), Axes { translation: [-100, 300, 0], rotation: [0, 1, -1] }); + assert_eq!(reading.current(now, Axes::default()), Axes { translation: [-100, 300, 0], rotation: [0, 1, -1] }); // Only rotation arrives again: translation goes stale, rotation stays current. let later = now + STALE_AFTER + Duration::from_millis(1); assert!(decode_report(&[2, 4, 0, 5, 0, 6, 0], layout, &mut reading, later)); - assert_eq!(reading.current(later), Axes { translation: [0; 3], rotation: [4, 5, 6] }); + assert_eq!(reading.current(later, Axes::default()), Axes { translation: [0; 3], rotation: [4, 5, 6] }); // A device sending all six in one report updates both at once. let combined = solidcraft_space_mouse::Descriptor::parse(&[ 0x05, 0x01, 0x09, 0x08, 0xA1, 0x01, 0x85, 0x01, 0x16, 0xA2, 0xFE, 0x26, 0x5E, 0x01, 0x75, 0x10, 0x95, 0x06, 0x19, 0x30, 0x29, 0x35, 0x81, @@ -494,7 +564,7 @@ mod tests { .expect("six axes declared"); let mut both = Reading::new(now); assert!(decode_report(&[1, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0], combined, &mut both, now)); - assert_eq!(both.current(now), Axes { translation: [1, 2, 3], rotation: [4, 5, 6] }); + assert_eq!(both.current(now, Axes::default()), Axes { translation: [1, 2, 3], rotation: [4, 5, 6] }); } #[test] @@ -513,11 +583,11 @@ mod tests { let mut reading = Reading::new(now); assert!(decode_report(&[1, 100, 0], split_x_y, &mut reading, now)); assert!(decode_report(&[2, 200, 0], split_x_y, &mut reading, now)); - assert_eq!(reading.current(now).translation, [100, 200, 0]); + assert_eq!(reading.current(now, Axes::default()).translation, [100, 200, 0]); // Then only X keeps coming: Y goes stale on its own. let later = now + STALE_AFTER + Duration::from_millis(1); assert!(decode_report(&[1, 50, 0], split_x_y, &mut reading, later)); - assert_eq!(reading.current(later).translation, [50, 0, 0]); + assert_eq!(reading.current(later, Axes::default()).translation, [50, 0, 0]); } #[test] @@ -530,8 +600,8 @@ mod tests { let mut reading = Reading::new(now); assert!(decode_report(&[1, 100, 0, 0, 0, 0, 0], layout, &mut reading, now)); // Just before the timeout X is still there; at exactly the timeout it's stale. - assert_eq!(reading.current(now + STALE_AFTER - Duration::from_millis(1)).translation, [100, 0, 0]); - assert_eq!(reading.current(now + STALE_AFTER).translation, [0; 3]); + assert_eq!(reading.current(now + STALE_AFTER - Duration::from_millis(1), Axes::default()).translation, [100, 0, 0]); + assert_eq!(reading.current(now + STALE_AFTER, Axes::default()).translation, [0; 3]); // Button reports and reports with an id the layout doesn't know keep coming, but neither // refreshes X: it goes stale on time all the same. for step in 1..=10 { @@ -539,7 +609,7 @@ mod tests { assert!(decode_report(&[3, 1], layout, &mut reading, at)); assert!(!decode_report(&[0x17, 80], layout, &mut reading, at)); } - assert_eq!(reading.current(now + STALE_AFTER).translation, [0; 3]); + assert_eq!(reading.current(now + STALE_AFTER, Axes::default()).translation, [0; 3]); } #[test] @@ -549,10 +619,10 @@ mod tests { let later = now + STALE_AFTER * 20; // spacenavd sends nothing while the values stay the same: the push lasts. let held = Reading { axes, held: true, ..Reading::new(now) }; - assert_eq!(held.current(later), axes); + assert_eq!(held.current(later, Axes::default()), axes); // A HID device repeats its report: silence means the cap, or the device, is gone. let hid = Reading { axes, ..Reading::new(now) }; - assert_eq!(hid.current(later), Axes::default()); + assert_eq!(hid.current(later, Axes::default()), Axes::default()); } #[test] @@ -624,6 +694,7 @@ mod tests { mapping_checked_at: now, wheel: WheelGuard::default(), started: now, + calibration: None, }; // A window that has run a frame with focus, as the app's always has by now. let ctx = Context::default(); @@ -651,9 +722,84 @@ mod tests { mapping_checked_at: now, wheel: WheelGuard::default(), started: now, + calibration: None, } } + const DEVICE: Source = Source::Hid(Some((0x1234, 0x5678))); + + /// A device whose raw axes all rest at 100, calibrated as such. + fn resting_at_100() -> Calibration { + Calibration { + dead_zone_share: 0.0, + axes: std::array::from_fn(|source| solidcraft_space_mouse::AxisCalibration { + source, + reversed: false, + rest: 100, + dead_zone: 0, + full: [350; 2], + }), + } + } + + #[test] + fn a_calibrated_device_resting_off_zero_leaves_the_wheel_alone() { + // Read raw, X at 100 is the cap pushed past the dead zone: the wheel is dropped. + let now = Instant::now(); + let mut resting = Reading::new(now); + resting.device = Some(DEVICE); + resting.axes = Axes { translation: [100; 3], rotation: [100; 3] }; + let wheel_kept = |calibration| { + let mut mouse = mouse(resting, now); + mouse.calibration = calibration; + let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() }; + mouse.raw_input_hook_at(true, &mut raw, now); + raw.events.len() == 1 + }; + assert!(!wheel_kept(None)); + // Calibrated, it's at rest, so the wheel is the user's. + assert!(wheel_kept(Some((DEVICE, resting_at_100())))); + // Another device's calibration, kept from the last frame, isn't used for this one. + assert!(!wheel_kept(Some((Source::Hid(Some((0x256f, 0xc63a))), resting_at_100())))); + } + + #[test] + fn a_calibrated_device_resting_off_zero_doesnt_drift_when_nothing_fresh_arrives() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default()); + app.home.open = false; + app.preferences.space_mouse_calibrations.insert(DEVICE.key(), resting_at_100()); + // A window that has run a frame with focus, as the app's always has by now. + let ctx = Context::default(); + let mut frame = ctx.run_ui(egui::RawInput::default(), |_| {}); + frame.textures_delta.clear(); + let motion = |app: &mut SolveApp, reading: Reading, now: Instant| { + let mut mouse = mouse(reading, now); + mouse.last_frame = now - Duration::from_millis(20); + app.viewport.device_motion = None; + mouse.tick_at(app, &ctx, now); + app.viewport.device_motion.is_some() + }; + // Connected, and nothing reported yet. + let shared = Mutex::new(Reading::new(Instant::now())); + connected(&Context::default(), &shared, DEVICE); + let fresh = *shared.lock().unwrap(); + let now = Instant::now(); + assert!(!motion(&mut app, fresh, now), "connected, nothing reported yet"); + // The same, while another device's calibration window was open: it ends, and this one + // doesn't move on the first frame either. + app.space_mouse.calibrating = Some(("hid 256f:c63a".into(), solidcraft_space_mouse::Wizard::default())); + assert!(!motion(&mut app, fresh, now), "connected mid-calibration of another device"); + assert!(app.space_mouse.calibrating.is_none()); + // Translation reported at rest, rotation not for a while. + let old = now - STALE_AFTER - Duration::from_millis(1); + let partly = Reading { axes: Axes { translation: [100; 3], rotation: [0; 3] }, at: [now, now, now, old, old, old], ..fresh }; + assert!(!motion(&mut app, partly, now), "translation at rest, rotation stale"); + // Pushed, then the reports stopped. + let pushed = Reading { axes: Axes { translation: [450, 100, 100], rotation: [100; 3] }, at: [old; 6], ..fresh }; + assert!(!motion(&mut app, pushed, now), "the push timed out"); + assert!(motion(&mut app, Reading { at: [now; 6], ..pushed }, now), "a fresh push moves the view"); + } + #[test] fn the_wheel_3dxware_makes_from_the_cap_is_dropped() { // The cap tilted forward: 3DxWare also sends wheel turns (#1380). They are dropped. diff --git a/apps/solidcraft/src/space_mouse/hidraw.rs b/apps/solidcraft/src/space_mouse/hidraw.rs index 46ab29432..45e8f2ba5 100644 --- a/apps/solidcraft/src/space_mouse/hidraw.rs +++ b/apps/solidcraft/src/space_mouse/hidraw.rs @@ -1,6 +1,6 @@ //! Finding a 3D mouse on Linux. The kernel exposes every HID interface as `/dev/hidrawN`, with -//! its report descriptor under `/sys/class/hidraw/hidrawN/device/`. Reading it is plain file -//! I/O, so no udev or hidapi library is needed. +//! its report descriptor and ids under `/sys/class/hidraw/hidrawN/device/`. Reading them is plain +//! file I/O, so no udev or hidapi library is needed. use std::path::{Path, PathBuf}; @@ -12,6 +12,8 @@ const DEV: &str = "/dev"; pub struct Device { pub path: PathBuf, pub layout: Layout, + /// Its vendor and product ids, when the kernel gives them. + pub ids: Option<(u16, u16)>, } /// The first hidraw interface that is a multi-axis controller with motion axes, whoever made it. @@ -25,5 +27,27 @@ fn probe(sysfs: &Path, path: PathBuf) -> Option { let descriptor = Descriptor::parse(&std::fs::read(sysfs.join("device/report_descriptor")).ok()?); // A controller that declares no motion axis (buttons only, say) isn't read. let layout = descriptor.is_multi_axis_controller().then(|| descriptor.layout()).flatten()?; - Some(Device { path, layout }) + let ids = std::fs::read_to_string(sysfs.join("device/uevent")).ok().as_deref().and_then(ids); + Some(Device { path, layout, ids }) +} + +/// The vendor and product ids in a HID device's uevent: `HID_ID=bus:vendor:product`, in hex. +fn ids(uevent: &str) -> Option<(u16, u16)> { + let id = uevent.lines().find_map(|line| line.strip_prefix("HID_ID="))?; + let mut hex = id.split(':').skip(1).map(|part| u32::from_str_radix(part, 16).ok().and_then(|v| u16::try_from(v).ok())); + Some((hex.next()??, hex.next()??)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ids_come_from_the_uevent() { + let wireless = "DRIVER=hid-generic\nHID_ID=0005:0000256F:0000C63A\nHID_NAME=SpaceMouse Wireless BT\n"; + assert_eq!(ids(wireless), Some((0x256f, 0xc63a))); + assert_eq!(ids("HID_ID=0003:0000046D\n"), None); + assert_eq!(ids("HID_ID=0003:0001046D:0000C62B\n"), None, "a vendor past 16 bits isn't a USB id"); + assert_eq!(ids("HID_NAME=keyboard\n"), None); + } } diff --git a/assets/locales/cs.json b/assets/locales/cs.json index e70007ab6..ba131237d 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -993,6 +993,7 @@ "ui.autosave_every": "Automaticky ukládat každých", "ui.axes": "Osy", "ui.axis": "Osa", + "ui.back": "Zpět", "ui.base_point": "Základní bod", "ui.blocked": "Blokováno", "ui.bodies": "Tělesa", @@ -1398,8 +1399,34 @@ "ui.smooth_wheel_zoom": "Plynulé přiblížení kolečkem", "ui.smooth_wheel_zoom_tip": "Vypnutím se každý pohyb kolečka projeví okamžitě, bez dobíhání", "ui.snap": "Přichytávání", + "ui.space_mouse_calibrate": "Kalibrovat…", + "ui.space_mouse_calibrate_tip": "Pohybujte hlavicí podle pokynů v okně, aby se SolidCraft naučil, kterým směrem a jak daleko se pohybuje každá osa této 3D myši. Uloží se pro tuto 3D myš.", + "ui.space_mouse_calibrate_title": "Kalibrace 3D myši", + "ui.space_mouse_calibrated": "Zkalibrováno", + "ui.space_mouse_calibration": "Kalibrace 3D myši", + "ui.space_mouse_calibration_done": "Hotovo. Uložte ji a použije se vždy, když bude tato 3D myš připojená.", + "ui.space_mouse_calibration_no_response": "Jedna osa se skoro nepohnula, takže ji nelze zkalibrovat. Začněte znovu a pokaždé hlavicí pohněte dál.", + "ui.space_mouse_dead_zone": "Mrtvá zóna", + "ui.space_mouse_dead_zone_tip": "Jak daleko se musí hlavice pohnout, než se pohne pohled, jako podíl jejího plného rozsahu. Zvyšte ji, pokud pohled ujíždí, i když je hlavice v klidu.", + "ui.space_mouse_forget": "Zapomenout kalibraci", "ui.space_mouse_hint": "Posun a otáčení pohledu současně; náčrty používají jen posun a přiblížení.", "ui.space_mouse_navigate": "Navigace pomocí SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "3D myš nenalezena", + "ui.space_mouse_not_calibrated": "Nezkalibrováno", + "ui.space_mouse_reading": "Hodnoty", + "ui.space_mouse_step_lift": "Zvedněte hlavici nahoru, podržte a pusťte.", + "ui.space_mouse_step_press": "Zatlačte hlavici dolů, podržte a pusťte.", + "ui.space_mouse_step_pull": "Přitáhněte hlavici k sobě, podržte a pusťte.", + "ui.space_mouse_step_push": "Odtlačte hlavici od sebe, podržte a pusťte.", + "ui.space_mouse_step_rest": "Dejte ruku z hlavice a nechte ji v klidu.", + "ui.space_mouse_step_slide_left": "Posuňte hlavici doleva, podržte a pusťte.", + "ui.space_mouse_step_slide_right": "Posuňte hlavici doprava, podržte a pusťte.", + "ui.space_mouse_step_tilt_back": "Nakloňte hlavici dozadu (přední hrana nahoru), podržte a pusťte.", + "ui.space_mouse_step_tilt_forward": "Nakloňte hlavici dopředu (přední hrana dolů), podržte a pusťte.", + "ui.space_mouse_step_tilt_left": "Nakloňte hlavici doleva (levá hrana dolů), podržte a pusťte.", + "ui.space_mouse_step_tilt_right": "Nakloňte hlavici doprava (pravá hrana dolů), podržte a pusťte.", + "ui.space_mouse_step_twist_clockwise": "Otočte hlavici po směru hodinových ručiček, podržte a pusťte.", + "ui.space_mouse_step_twist_counterclockwise": "Otočte hlavici proti směru hodinových ručiček, podržte a pusťte.", "ui.spacing": "Rozteč", "ui.spacing_2": "Rozteč 2", "ui.sphere": "Koule", @@ -1407,6 +1434,7 @@ "ui.split_body": "Rozdělit těleso", "ui.stand_up_tip": "Když se soubor STEP nebo IGES otevře s osou Z nahoru, nabídnout otočení o čtvrt otáčky kolem X", "ui.start": "Start", + "ui.start_over": "Začít znovu", "ui.start_radius": "Počáteční poloměr", "ui.supersampling": "Supersampling (SSAA)", "ui.supersampling_adaptive": "Jen když je pohled v klidu", diff --git a/assets/locales/de.json b/assets/locales/de.json index 4f2e2f2bf..8570b54c6 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -782,6 +782,7 @@ "ui.autosave_every": "Autospeichern alle", "ui.axes": "Achsen", "ui.axis": "Achse", + "ui.back": "Zurück", "ui.base_point": "Basispunkt", "ui.blocked": "Verdeckt", "ui.bodies": "Körper", @@ -1177,12 +1178,39 @@ "ui.slot": "Langloch", "ui.smooth": "Glatt", "ui.snap": "Einrasten", + "ui.space_mouse_calibrate": "Kalibrieren…", + "ui.space_mouse_calibrate_tip": "Bewegen Sie die Kappe so, wie das Fenster es verlangt. So lernt SolidCraft, in welche Richtung und wie weit jede Achse dieser 3D-Maus geht. Wird für diese 3D-Maus gespeichert.", + "ui.space_mouse_calibrate_title": "3D-Maus kalibrieren", + "ui.space_mouse_calibrated": "Kalibriert", + "ui.space_mouse_calibration": "3D-Maus-Kalibrierung", + "ui.space_mouse_calibration_done": "Fertig. Speichern Sie die Kalibrierung, damit sie immer gilt, wenn diese 3D-Maus angeschlossen ist.", + "ui.space_mouse_calibration_no_response": "Eine Achse hat sich kaum bewegt und lässt sich nicht kalibrieren. Beginnen Sie von vorn und bewegen Sie die Kappe jedes Mal weiter.", + "ui.space_mouse_dead_zone": "Totzone", + "ui.space_mouse_dead_zone_tip": "Wie weit sich die Kappe bewegen muss, bevor sich die Ansicht bewegt, als Anteil ihres vollen Wegs. Erhöhen Sie sie, wenn die Ansicht wandert, obwohl die Kappe ruht.", + "ui.space_mouse_forget": "Kalibrierung vergessen", + "ui.space_mouse_none": "Keine 3D-Maus gefunden", + "ui.space_mouse_not_calibrated": "Nicht kalibriert", + "ui.space_mouse_reading": "Werte", + "ui.space_mouse_step_lift": "Kappe nach oben ziehen, halten, dann loslassen.", + "ui.space_mouse_step_press": "Kappe nach unten drücken, halten, dann loslassen.", + "ui.space_mouse_step_pull": "Kappe zu sich heranziehen, halten, dann loslassen.", + "ui.space_mouse_step_push": "Kappe von sich wegschieben, halten, dann loslassen.", + "ui.space_mouse_step_rest": "Nehmen Sie die Hand von der Kappe und lassen Sie sie ruhen.", + "ui.space_mouse_step_slide_left": "Kappe nach links schieben, halten, dann loslassen.", + "ui.space_mouse_step_slide_right": "Kappe nach rechts schieben, halten, dann loslassen.", + "ui.space_mouse_step_tilt_back": "Kappe nach hinten kippen (Vorderkante hoch), halten, dann loslassen.", + "ui.space_mouse_step_tilt_forward": "Kappe nach vorn kippen (Vorderkante runter), halten, dann loslassen.", + "ui.space_mouse_step_tilt_left": "Kappe nach links kippen (linke Kante runter), halten, dann loslassen.", + "ui.space_mouse_step_tilt_right": "Kappe nach rechts kippen (rechte Kante runter), halten, dann loslassen.", + "ui.space_mouse_step_twist_clockwise": "Kappe im Uhrzeigersinn drehen, halten, dann loslassen.", + "ui.space_mouse_step_twist_counterclockwise": "Kappe gegen den Uhrzeigersinn drehen, halten, dann loslassen.", "ui.spacing": "Abstand", "ui.spacing_2": "Abstand 2", "ui.sphere": "Sphäre", "ui.spline": "Spline", "ui.split_body": "Körper trennen", "ui.start": "Start", + "ui.start_over": "Von vorn beginnen", "ui.start_radius": "Startradius", "ui.stretch": "Strecken", "ui.supersampling": "Supersampling (SSAA)", diff --git a/assets/locales/en.json b/assets/locales/en.json index 0e7e3226c..26538886b 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1074,6 +1074,7 @@ "ui.autosave_every": "Autosave every", "ui.axes": "Axes", "ui.axis": "Axis", + "ui.back": "Back", "ui.base_point": "Base point", "ui.blocked": "Blocked", "ui.bodies": "Bodies", @@ -1508,8 +1509,34 @@ "ui.smooth_wheel_zoom": "Smooth wheel zoom", "ui.smooth_wheel_zoom_tip": "Turn off to apply each wheel event immediately, without a smoothing tail", "ui.snap": "Snap", + "ui.space_mouse_calibrate": "Calibrate…", + "ui.space_mouse_calibrate_tip": "Move the cap as the window asks, so SolidCraft learns which way each axis of this 3D mouse goes and how far. Saved for this 3D mouse.", + "ui.space_mouse_calibrate_title": "Calibrate 3D mouse", + "ui.space_mouse_calibrated": "Calibrated", + "ui.space_mouse_calibration": "3D mouse calibration", + "ui.space_mouse_calibration_done": "Done. Save it to use it whenever this 3D mouse is connected.", + "ui.space_mouse_calibration_no_response": "One axis barely moved, so it can't be calibrated. Start over and move the cap further each time.", + "ui.space_mouse_dead_zone": "Dead zone", + "ui.space_mouse_dead_zone_tip": "How far the cap has to move before the view does, as a share of its full travel. Raise it if the view drifts while the cap is at rest.", + "ui.space_mouse_forget": "Forget calibration", "ui.space_mouse_hint": "Move and rotate the view together; sketches use pan and zoom only.", "ui.space_mouse_navigate": "Navigate with SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "No 3D mouse found", + "ui.space_mouse_not_calibrated": "Not calibrated", + "ui.space_mouse_reading": "Reading", + "ui.space_mouse_step_lift": "Lift the cap up, hold it, then let go.", + "ui.space_mouse_step_press": "Press the cap down, hold it, then let go.", + "ui.space_mouse_step_pull": "Pull the cap toward you, hold it, then let go.", + "ui.space_mouse_step_push": "Push the cap away from you, hold it, then let go.", + "ui.space_mouse_step_rest": "Take your hand off the cap and leave it still.", + "ui.space_mouse_step_slide_left": "Slide the cap left, hold it, then let go.", + "ui.space_mouse_step_slide_right": "Slide the cap right, hold it, then let go.", + "ui.space_mouse_step_tilt_back": "Tilt the cap back (front edge up), hold it, then let go.", + "ui.space_mouse_step_tilt_forward": "Tilt the cap forward (front edge down), hold it, then let go.", + "ui.space_mouse_step_tilt_left": "Tilt the cap left (left edge down), hold it, then let go.", + "ui.space_mouse_step_tilt_right": "Tilt the cap right (right edge down), hold it, then let go.", + "ui.space_mouse_step_twist_clockwise": "Twist the cap clockwise, hold it, then let go.", + "ui.space_mouse_step_twist_counterclockwise": "Twist the cap anticlockwise, hold it, then let go.", "ui.spacing": "Spacing", "ui.spacing_2": "Spacing 2", "ui.sphere": "Sphere", @@ -1517,6 +1544,7 @@ "ui.split_body": "Split Body", "ui.stand_up_tip": "After a STEP or IGES file opens with Z up, offer a quarter turn about X", "ui.start": "Start", + "ui.start_over": "Start over", "ui.start_radius": "Start Radius", "ui.stretch": "Stretch", "ui.supersampling": "Supersampling (SSAA)", diff --git a/assets/locales/es.json b/assets/locales/es.json index a8939d7e2..3097988a8 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -1012,6 +1012,7 @@ "ui.autosave_every": "Guardar automáticamente cada", "ui.axes": "Ejes", "ui.axis": "Eje", + "ui.back": "Atrás", "ui.base_point": "Punto base", "ui.blocked": "Bloqueado", "ui.bodies": "Cuerpos", @@ -1425,8 +1426,34 @@ "ui.smooth_wheel_zoom": "Zoom suave con la rueda", "ui.smooth_wheel_zoom_tip": "Desactívalo para aplicar cada movimiento de la rueda inmediatamente, sin suavizado posterior", "ui.snap": "Referencia a objetos", + "ui.space_mouse_calibrate": "Calibrar…", + "ui.space_mouse_calibrate_tip": "Mueve el capuchón como pide la ventana para que SolidCraft aprenda hacia dónde y hasta dónde va cada eje de este ratón 3D. Se guarda para este ratón 3D.", + "ui.space_mouse_calibrate_title": "Calibrar ratón 3D", + "ui.space_mouse_calibrated": "Calibrado", + "ui.space_mouse_calibration": "Calibración del ratón 3D", + "ui.space_mouse_calibration_done": "Listo. Guárdala para usarla siempre que este ratón 3D esté conectado.", + "ui.space_mouse_calibration_no_response": "Un eje apenas se movió, así que no se puede calibrar. Vuelve a empezar y mueve el capuchón más lejos cada vez.", + "ui.space_mouse_dead_zone": "Zona muerta", + "ui.space_mouse_dead_zone_tip": "Cuánto tiene que moverse el capuchón antes de que se mueva la vista, como parte de su recorrido completo. Auméntala si la vista se desplaza con el capuchón en reposo.", + "ui.space_mouse_forget": "Olvidar calibración", "ui.space_mouse_hint": "Desplaza y gira la vista a la vez; los bocetos solo permiten desplazamiento y zoom.", "ui.space_mouse_navigate": "Navegar con SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "No se encontró ningún ratón 3D", + "ui.space_mouse_not_calibrated": "Sin calibrar", + "ui.space_mouse_reading": "Lectura", + "ui.space_mouse_step_lift": "Levanta el capuchón, mantenlo y suéltalo.", + "ui.space_mouse_step_press": "Presiona el capuchón hacia abajo, mantenlo y suéltalo.", + "ui.space_mouse_step_pull": "Tira del capuchón hacia ti, mantenlo y suéltalo.", + "ui.space_mouse_step_push": "Empuja el capuchón lejos de ti, mantenlo y suéltalo.", + "ui.space_mouse_step_rest": "Suelta el capuchón y déjalo quieto.", + "ui.space_mouse_step_slide_left": "Desliza el capuchón a la izquierda, mantenlo y suéltalo.", + "ui.space_mouse_step_slide_right": "Desliza el capuchón a la derecha, mantenlo y suéltalo.", + "ui.space_mouse_step_tilt_back": "Inclina el capuchón hacia atrás (borde delantero arriba), mantenlo y suéltalo.", + "ui.space_mouse_step_tilt_forward": "Inclina el capuchón hacia delante (borde delantero abajo), mantenlo y suéltalo.", + "ui.space_mouse_step_tilt_left": "Inclina el capuchón a la izquierda (borde izquierdo abajo), mantenlo y suéltalo.", + "ui.space_mouse_step_tilt_right": "Inclina el capuchón a la derecha (borde derecho abajo), mantenlo y suéltalo.", + "ui.space_mouse_step_twist_clockwise": "Gira el capuchón en sentido horario, mantenlo y suéltalo.", + "ui.space_mouse_step_twist_counterclockwise": "Gira el capuchón en sentido antihorario, mantenlo y suéltalo.", "ui.spacing": "Espaciado", "ui.spacing_2": "Espaciado 2", "ui.sphere": "Esfera", @@ -1434,6 +1461,7 @@ "ui.split_body": "Dividir cuerpo", "ui.stand_up_tip": "Tras abrir un archivo STEP o IGES con Z hacia arriba, ofrecer un cuarto de vuelta alrededor de X", "ui.start": "Iniciar", + "ui.start_over": "Volver a empezar", "ui.start_radius": "Radio inicial", "ui.stretch": "Estirar", "ui.supersampling": "Supermuestreo (SSAA)", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 6e2feab66..319456076 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1021,6 +1021,7 @@ "ui.autosave_every": "Enregistrement automatique toutes les", "ui.axes": "Axes", "ui.axis": "Axe", + "ui.back": "Retour", "ui.base_point": "Point de base", "ui.blocked": "Inaccessible", "ui.bodies": "Corps", @@ -1441,8 +1442,34 @@ "ui.smooth_wheel_zoom": "Zoom fluide à la molette", "ui.smooth_wheel_zoom_tip": "Désactiver pour appliquer chaque cran de molette immédiatement, sans lissage", "ui.snap": "Accrochage", + "ui.space_mouse_calibrate": "Calibrer…", + "ui.space_mouse_calibrate_tip": "Déplacez le capuchon comme la fenêtre le demande, pour que SolidCraft apprenne dans quel sens et jusqu'où va chaque axe de cette souris 3D. Enregistré pour cette souris 3D.", + "ui.space_mouse_calibrate_title": "Calibrer la souris 3D", + "ui.space_mouse_calibrated": "Calibrée", + "ui.space_mouse_calibration": "Calibrage de la souris 3D", + "ui.space_mouse_calibration_done": "Terminé. Enregistrez-le pour l'utiliser chaque fois que cette souris 3D est connectée.", + "ui.space_mouse_calibration_no_response": "Un axe a à peine bougé, il ne peut donc pas être calibré. Recommencez en déplaçant le capuchon plus loin à chaque fois.", + "ui.space_mouse_dead_zone": "Zone morte", + "ui.space_mouse_dead_zone_tip": "De combien le capuchon doit bouger avant que la vue ne bouge, en part de sa course complète. Augmentez-la si la vue dérive alors que le capuchon est au repos.", + "ui.space_mouse_forget": "Oublier le calibrage", "ui.space_mouse_hint": "Déplace et fait pivoter la vue en même temps ; dans les esquisses, seuls le panoramique et le zoom sont utilisés.", "ui.space_mouse_navigate": "Naviguer avec SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "Aucune souris 3D trouvée", + "ui.space_mouse_not_calibrated": "Non calibrée", + "ui.space_mouse_reading": "Lecture", + "ui.space_mouse_step_lift": "Soulevez le capuchon, maintenez, puis relâchez.", + "ui.space_mouse_step_press": "Appuyez sur le capuchon, maintenez, puis relâchez.", + "ui.space_mouse_step_pull": "Tirez le capuchon vers vous, maintenez, puis relâchez.", + "ui.space_mouse_step_push": "Poussez le capuchon loin de vous, maintenez, puis relâchez.", + "ui.space_mouse_step_rest": "Lâchez le capuchon et laissez-le immobile.", + "ui.space_mouse_step_slide_left": "Glissez le capuchon vers la gauche, maintenez, puis relâchez.", + "ui.space_mouse_step_slide_right": "Glissez le capuchon vers la droite, maintenez, puis relâchez.", + "ui.space_mouse_step_tilt_back": "Inclinez le capuchon vers l'arrière (bord avant vers le haut), maintenez, puis relâchez.", + "ui.space_mouse_step_tilt_forward": "Inclinez le capuchon vers l'avant (bord avant vers le bas), maintenez, puis relâchez.", + "ui.space_mouse_step_tilt_left": "Inclinez le capuchon vers la gauche (bord gauche vers le bas), maintenez, puis relâchez.", + "ui.space_mouse_step_tilt_right": "Inclinez le capuchon vers la droite (bord droit vers le bas), maintenez, puis relâchez.", + "ui.space_mouse_step_twist_clockwise": "Tournez le capuchon dans le sens horaire, maintenez, puis relâchez.", + "ui.space_mouse_step_twist_counterclockwise": "Tournez le capuchon dans le sens antihoraire, maintenez, puis relâchez.", "ui.spacing": "Espacement", "ui.spacing_2": "Espacement 2", "ui.sphere": "Sphère", @@ -1450,6 +1477,7 @@ "ui.split_body": "Scinder le corps", "ui.stand_up_tip": "Après l'ouverture d'un fichier STEP ou IGES avec Z vers le haut, proposer un quart de tour autour de X", "ui.start": "Début", + "ui.start_over": "Recommencer", "ui.start_radius": "Rayon initial", "ui.stretch": "Étirer", "ui.supersampling": "Suréchantillonnage (SSAA)", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index b0960fee8..c3a8e6a4d 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -984,6 +984,7 @@ "ui.autosave_every": "Gardar automaticamente cada", "ui.axes": "Eixes", "ui.axis": "Eixe", + "ui.back": "Atrás", "ui.base_point": "Punto base", "ui.blocked": "Bloqueado", "ui.bodies": "Corpos", @@ -1389,8 +1390,34 @@ "ui.smooth_wheel_zoom": "Zoom suave coa roda", "ui.smooth_wheel_zoom_tip": "Desactívao para aplicar cada movemento da roda de inmediato, sen suavizado", "ui.snap": "Axuste", + "ui.space_mouse_calibrate": "Calibrar…", + "ui.space_mouse_calibrate_tip": "Move o capuchón como pide a xanela para que SolidCraft aprenda cara a onde e ata onde vai cada eixe deste rato 3D. Gárdase para este rato 3D.", + "ui.space_mouse_calibrate_title": "Calibrar o rato 3D", + "ui.space_mouse_calibrated": "Calibrado", + "ui.space_mouse_calibration": "Calibración do rato 3D", + "ui.space_mouse_calibration_done": "Feito. Gárdaa para usala sempre que este rato 3D estea conectado.", + "ui.space_mouse_calibration_no_response": "Un eixe case non se moveu, así que non se pode calibrar. Volve comezar e move o capuchón máis lonxe cada vez.", + "ui.space_mouse_dead_zone": "Zona morta", + "ui.space_mouse_dead_zone_tip": "Canto ten que moverse o capuchón antes de que se mova a vista, como parte do seu percorrido completo. Auméntaa se a vista se despraza co capuchón en repouso.", + "ui.space_mouse_forget": "Esquecer a calibración", "ui.space_mouse_hint": "Move e rota a vista á vez; os bosquexos só usan desprazamento e zoom.", "ui.space_mouse_navigate": "Navegar con SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "Non se atopou ningún rato 3D", + "ui.space_mouse_not_calibrated": "Sen calibrar", + "ui.space_mouse_reading": "Lectura", + "ui.space_mouse_step_lift": "Levanta o capuchón, mantéño e sóltao.", + "ui.space_mouse_step_press": "Preme o capuchón cara abaixo, mantéño e sóltao.", + "ui.space_mouse_step_pull": "Tira do capuchón cara a ti, mantéño e sóltao.", + "ui.space_mouse_step_push": "Empurra o capuchón lonxe de ti, mantéño e sóltao.", + "ui.space_mouse_step_rest": "Solta o capuchón e déixao quieto.", + "ui.space_mouse_step_slide_left": "Despraza o capuchón á esquerda, mantéño e sóltao.", + "ui.space_mouse_step_slide_right": "Despraza o capuchón á dereita, mantéño e sóltao.", + "ui.space_mouse_step_tilt_back": "Inclina o capuchón cara atrás (bordo dianteiro arriba), mantéño e sóltao.", + "ui.space_mouse_step_tilt_forward": "Inclina o capuchón cara adiante (bordo dianteiro abaixo), mantéño e sóltao.", + "ui.space_mouse_step_tilt_left": "Inclina o capuchón á esquerda (bordo esquerdo abaixo), mantéño e sóltao.", + "ui.space_mouse_step_tilt_right": "Inclina o capuchón á dereita (bordo dereito abaixo), mantéño e sóltao.", + "ui.space_mouse_step_twist_clockwise": "Xira o capuchón no sentido horario, mantéño e sóltao.", + "ui.space_mouse_step_twist_counterclockwise": "Xira o capuchón no sentido antihorario, mantéño e sóltao.", "ui.spacing": "Espazado", "ui.spacing_2": "Espazado 2", "ui.sphere": "Esfera", @@ -1398,6 +1425,7 @@ "ui.split_body": "Dividir o corpo", "ui.stand_up_tip": "Despois de abrir un ficheiro STEP ou IGES con Z cara arriba, ofrecer un cuarto de volta arredor de X", "ui.start": "Inicio", + "ui.start_over": "Volver comezar", "ui.start_radius": "Raio inicial", "ui.supersampling": "Supermostraxe (SSAA)", "ui.supersampling_adaptive": "Só cando a vista está quieta", diff --git a/assets/locales/it.json b/assets/locales/it.json index 4b02cc884..05720236e 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -1010,6 +1010,7 @@ "ui.autosave_every": "Salvataggio automatico ogni", "ui.axes": "Assi", "ui.axis": "Asse", + "ui.back": "Indietro", "ui.base_point": "Punto base", "ui.blocked": "Bloccato", "ui.bodies": "Corpi", @@ -1423,8 +1424,34 @@ "ui.smooth_wheel_zoom": "Zoom fluido con rotellina", "ui.smooth_wheel_zoom_tip": "Disattiva per applicare immediatamente ogni evento della rotellina, senza coda di interpolazione", "ui.snap": "Aggancio", + "ui.space_mouse_calibrate": "Calibra…", + "ui.space_mouse_calibrate_tip": "Muovi la manopola come chiede la finestra, così SolidCraft impara in che direzione e quanto va ogni asse di questo mouse 3D. Viene salvata per questo mouse 3D.", + "ui.space_mouse_calibrate_title": "Calibra mouse 3D", + "ui.space_mouse_calibrated": "Calibrato", + "ui.space_mouse_calibration": "Calibrazione del mouse 3D", + "ui.space_mouse_calibration_done": "Fatto. Salvala per usarla ogni volta che questo mouse 3D è collegato.", + "ui.space_mouse_calibration_no_response": "Un asse si è mosso appena, quindi non si può calibrare. Ricomincia e muovi la manopola più a fondo ogni volta.", + "ui.space_mouse_dead_zone": "Zona morta", + "ui.space_mouse_dead_zone_tip": "Quanto deve muoversi la manopola prima che si muova la vista, come quota della sua corsa completa. Aumentala se la vista si sposta con la manopola a riposo.", + "ui.space_mouse_forget": "Dimentica calibrazione", "ui.space_mouse_hint": "Sposta e ruota la vista insieme; gli schizzi usano solo panoramica e zoom.", "ui.space_mouse_navigate": "Naviga con SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "Nessun mouse 3D trovato", + "ui.space_mouse_not_calibrated": "Non calibrato", + "ui.space_mouse_reading": "Lettura", + "ui.space_mouse_step_lift": "Solleva la manopola, tienila, poi lasciala.", + "ui.space_mouse_step_press": "Premi la manopola verso il basso, tienila, poi lasciala.", + "ui.space_mouse_step_pull": "Tira la manopola verso di te, tienila, poi lasciala.", + "ui.space_mouse_step_push": "Spingi la manopola lontano da te, tienila, poi lasciala.", + "ui.space_mouse_step_rest": "Togli la mano dalla manopola e lasciala ferma.", + "ui.space_mouse_step_slide_left": "Fai scorrere la manopola a sinistra, tienila, poi lasciala.", + "ui.space_mouse_step_slide_right": "Fai scorrere la manopola a destra, tienila, poi lasciala.", + "ui.space_mouse_step_tilt_back": "Inclina la manopola all'indietro (bordo anteriore in alto), tienila, poi lasciala.", + "ui.space_mouse_step_tilt_forward": "Inclina la manopola in avanti (bordo anteriore in basso), tienila, poi lasciala.", + "ui.space_mouse_step_tilt_left": "Inclina la manopola a sinistra (bordo sinistro in basso), tienila, poi lasciala.", + "ui.space_mouse_step_tilt_right": "Inclina la manopola a destra (bordo destro in basso), tienila, poi lasciala.", + "ui.space_mouse_step_twist_clockwise": "Ruota la manopola in senso orario, tienila, poi lasciala.", + "ui.space_mouse_step_twist_counterclockwise": "Ruota la manopola in senso antiorario, tienila, poi lasciala.", "ui.spacing": "Spaziatura", "ui.spacing_2": "Spaziatura 2", "ui.sphere": "Sfera", @@ -1432,6 +1459,7 @@ "ui.split_body": "Dividi corpo", "ui.stand_up_tip": "Dopo l'apertura di un file STEP o IGES con asse Z verticale, proponi un quarto di giro attorno a X", "ui.start": "Inizio", + "ui.start_over": "Ricomincia", "ui.start_radius": "Raggio iniziale", "ui.stretch": "Stira", "ui.supersampling": "Sovracampionamento (SSAA)", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index f1f4ac468..02c5e371d 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1074,6 +1074,7 @@ "ui.autosave_every": "自動保存の間隔", "ui.axes": "軸", "ui.axis": "軸", + "ui.back": "戻る", "ui.base_point": "基点", "ui.blocked": "到達不可", "ui.bodies": "ボディ", @@ -1508,8 +1509,34 @@ "ui.smooth_wheel_zoom": "滑らかなホイールズーム", "ui.smooth_wheel_zoom_tip": "オフにすると、ホイール操作のたびにズームが即座に反映され、滑らかな減速効果は適用されません。", "ui.snap": "スナップ", + "ui.space_mouse_calibrate": "キャリブレーション…", + "ui.space_mouse_calibrate_tip": "ウィンドウの指示どおりにキャップを動かすと、この3Dマウスの各軸の向きと移動量をSolidCraftが学習します。この3Dマウス用に保存されます。", + "ui.space_mouse_calibrate_title": "3Dマウスのキャリブレーション", + "ui.space_mouse_calibrated": "キャリブレーション済み", + "ui.space_mouse_calibration": "3Dマウスのキャリブレーション", + "ui.space_mouse_calibration_done": "完了しました。保存すると、この3Dマウスを接続したときに毎回使われます。", + "ui.space_mouse_calibration_no_response": "ほとんど動かなかった軸があるため、キャリブレーションできません。最初からやり直し、毎回キャップをもっと大きく動かしてください。", + "ui.space_mouse_dead_zone": "デッドゾーン", + "ui.space_mouse_dead_zone_tip": "視点が動き出すまでにキャップを動かす量(全ストロークに対する割合)。キャップに触れていないのに視点が動く場合は大きくしてください。", + "ui.space_mouse_forget": "キャリブレーションを削除", "ui.space_mouse_hint": "視点の移動と回転を同時に行います(スケッチ中はパンとズームのみ)", "ui.space_mouse_navigate": "SpaceNavigator / SpaceMouseで視点を操作", + "ui.space_mouse_none": "3Dマウスが見つかりません", + "ui.space_mouse_not_calibrated": "未キャリブレーション", + "ui.space_mouse_reading": "読み取り値", + "ui.space_mouse_step_lift": "キャップを持ち上げて保持し、離してください。", + "ui.space_mouse_step_press": "キャップを押し下げて保持し、離してください。", + "ui.space_mouse_step_pull": "キャップを手前に引いて保持し、離してください。", + "ui.space_mouse_step_push": "キャップを奥に押して保持し、離してください。", + "ui.space_mouse_step_rest": "キャップから手を離し、動かさないでください。", + "ui.space_mouse_step_slide_left": "キャップを左にスライドして保持し、離してください。", + "ui.space_mouse_step_slide_right": "キャップを右にスライドして保持し、離してください。", + "ui.space_mouse_step_tilt_back": "キャップを後ろに傾け(手前の縁を上げて)保持し、離してください。", + "ui.space_mouse_step_tilt_forward": "キャップを前に傾け(手前の縁を下げて)保持し、離してください。", + "ui.space_mouse_step_tilt_left": "キャップを左に傾け(左の縁を下げて)保持し、離してください。", + "ui.space_mouse_step_tilt_right": "キャップを右に傾け(右の縁を下げて)保持し、離してください。", + "ui.space_mouse_step_twist_clockwise": "キャップを時計回りにひねって保持し、離してください。", + "ui.space_mouse_step_twist_counterclockwise": "キャップを反時計回りにひねって保持し、離してください。", "ui.spacing": "間隔", "ui.spacing_2": "間隔 2", "ui.sphere": "球", @@ -1517,6 +1544,7 @@ "ui.split_body": "ボディを分割", "ui.stand_up_tip": "Z軸上向きで開いたSTEPまたはIGESファイルに対し、X軸周りに90度回転させるか確認します", "ui.start": "開始", + "ui.start_over": "最初からやり直す", "ui.start_radius": "開始半径", "ui.stretch": "伸縮", "ui.supersampling": "スーパーサンプリング (SSAA)", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index ba118b798..21198a398 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -782,6 +782,7 @@ "ui.autosave_every": "자동 저장 간격", "ui.axes": "축", "ui.axis": "축", + "ui.back": "뒤로", "ui.base_point": "기준점", "ui.blocked": "막힘", "ui.bodies": "바디", @@ -1174,12 +1175,39 @@ "ui.slot": "슬롯", "ui.smooth": "부드럽게", "ui.snap": "스냅", + "ui.space_mouse_calibrate": "보정…", + "ui.space_mouse_calibrate_tip": "창의 안내대로 캡을 움직이면 SolidCraft가 이 3D 마우스의 각 축이 어느 방향으로 얼마나 움직이는지 학습합니다. 이 3D 마우스에 저장됩니다.", + "ui.space_mouse_calibrate_title": "3D 마우스 보정", + "ui.space_mouse_calibrated": "보정됨", + "ui.space_mouse_calibration": "3D 마우스 보정", + "ui.space_mouse_calibration_done": "완료했습니다. 저장하면 이 3D 마우스를 연결할 때마다 사용됩니다.", + "ui.space_mouse_calibration_no_response": "거의 움직이지 않은 축이 있어 보정할 수 없습니다. 처음부터 다시 하고 매번 캡을 더 멀리 움직이세요.", + "ui.space_mouse_dead_zone": "데드존", + "ui.space_mouse_dead_zone_tip": "보기가 움직이기 전에 캡이 움직여야 하는 정도로, 전체 이동 범위에 대한 비율입니다. 캡을 건드리지 않았는데 보기가 움직이면 높이세요.", + "ui.space_mouse_forget": "보정 삭제", + "ui.space_mouse_none": "3D 마우스를 찾을 수 없음", + "ui.space_mouse_not_calibrated": "보정 안 됨", + "ui.space_mouse_reading": "읽은 값", + "ui.space_mouse_step_lift": "캡을 위로 들어 유지한 다음 놓으세요.", + "ui.space_mouse_step_press": "캡을 아래로 눌러 유지한 다음 놓으세요.", + "ui.space_mouse_step_pull": "캡을 몸 쪽으로 당겨 유지한 다음 놓으세요.", + "ui.space_mouse_step_push": "캡을 앞쪽으로 밀어 유지한 다음 놓으세요.", + "ui.space_mouse_step_rest": "캡에서 손을 떼고 가만히 두세요.", + "ui.space_mouse_step_slide_left": "캡을 왼쪽으로 밀어 유지한 다음 놓으세요.", + "ui.space_mouse_step_slide_right": "캡을 오른쪽으로 밀어 유지한 다음 놓으세요.", + "ui.space_mouse_step_tilt_back": "캡을 뒤로 기울여(앞쪽 가장자리를 위로) 유지한 다음 놓으세요.", + "ui.space_mouse_step_tilt_forward": "캡을 앞으로 기울여(앞쪽 가장자리를 아래로) 유지한 다음 놓으세요.", + "ui.space_mouse_step_tilt_left": "캡을 왼쪽으로 기울여(왼쪽 가장자리를 아래로) 유지한 다음 놓으세요.", + "ui.space_mouse_step_tilt_right": "캡을 오른쪽으로 기울여(오른쪽 가장자리를 아래로) 유지한 다음 놓으세요.", + "ui.space_mouse_step_twist_clockwise": "캡을 시계 방향으로 돌려 유지한 다음 놓으세요.", + "ui.space_mouse_step_twist_counterclockwise": "캡을 시계 반대 방향으로 돌려 유지한 다음 놓으세요.", "ui.spacing": "간격", "ui.spacing_2": "간격 2", "ui.sphere": "구", "ui.spline": "스플라인", "ui.split_body": "바디 분할", "ui.start": "시작", + "ui.start_over": "처음부터 다시", "ui.start_radius": "시작 반지름", "ui.supersampling": "슈퍼샘플링 (SSAA)", "ui.supersampling_adaptive": "뷰가 멈춰 있을 때만", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 4e3328550..0bc5944f9 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -964,6 +964,7 @@ "ui.autosave_every": "Salvar automaticamente a cada", "ui.axes": "Eixos", "ui.axis": "Eixo", + "ui.back": "Voltar", "ui.base_point": "Ponto base", "ui.blocked": "Bloqueado", "ui.bodies": "Corpos", @@ -1369,8 +1370,34 @@ "ui.smooth_wheel_zoom": "Zoom suave com a roda", "ui.smooth_wheel_zoom_tip": "Desative para aplicar cada evento da roda na hora, sem rastro de suavização", "ui.snap": "Encaixe", + "ui.space_mouse_calibrate": "Calibrar…", + "ui.space_mouse_calibrate_tip": "Mova a tampa como a janela pedir, para que o SolidCraft aprenda para onde e até onde vai cada eixo deste mouse 3D. Salvo para este mouse 3D.", + "ui.space_mouse_calibrate_title": "Calibrar mouse 3D", + "ui.space_mouse_calibrated": "Calibrado", + "ui.space_mouse_calibration": "Calibração do mouse 3D", + "ui.space_mouse_calibration_done": "Pronto. Salve para usá-la sempre que este mouse 3D estiver conectado.", + "ui.space_mouse_calibration_no_response": "Um eixo quase não se moveu, então não dá para calibrá-lo. Recomece e mova a tampa mais longe a cada vez.", + "ui.space_mouse_dead_zone": "Zona morta", + "ui.space_mouse_dead_zone_tip": "Quanto a tampa precisa se mover antes de a vista se mover, como fração do curso completo. Aumente se a vista se mexer com a tampa parada.", + "ui.space_mouse_forget": "Esquecer calibração", "ui.space_mouse_hint": "Move e gira a vista juntos; esboços usam apenas deslocamento e zoom.", "ui.space_mouse_navigate": "Navegar com SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "Nenhum mouse 3D encontrado", + "ui.space_mouse_not_calibrated": "Não calibrado", + "ui.space_mouse_reading": "Leitura", + "ui.space_mouse_step_lift": "Levante a tampa, segure e solte.", + "ui.space_mouse_step_press": "Pressione a tampa para baixo, segure e solte.", + "ui.space_mouse_step_pull": "Puxe a tampa na sua direção, segure e solte.", + "ui.space_mouse_step_push": "Empurre a tampa para longe de você, segure e solte.", + "ui.space_mouse_step_rest": "Tire a mão da tampa e deixe-a parada.", + "ui.space_mouse_step_slide_left": "Deslize a tampa para a esquerda, segure e solte.", + "ui.space_mouse_step_slide_right": "Deslize a tampa para a direita, segure e solte.", + "ui.space_mouse_step_tilt_back": "Incline a tampa para trás (borda da frente para cima), segure e solte.", + "ui.space_mouse_step_tilt_forward": "Incline a tampa para a frente (borda da frente para baixo), segure e solte.", + "ui.space_mouse_step_tilt_left": "Incline a tampa para a esquerda (borda esquerda para baixo), segure e solte.", + "ui.space_mouse_step_tilt_right": "Incline a tampa para a direita (borda direita para baixo), segure e solte.", + "ui.space_mouse_step_twist_clockwise": "Gire a tampa no sentido horário, segure e solte.", + "ui.space_mouse_step_twist_counterclockwise": "Gire a tampa no sentido anti-horário, segure e solte.", "ui.spacing": "Espaçamento", "ui.spacing_2": "Espaçamento 2", "ui.sphere": "Esfera", @@ -1378,6 +1405,7 @@ "ui.split_body": "Dividir corpo", "ui.stand_up_tip": "Depois que um arquivo STEP ou IGES abrir com Z para cima, oferecer um quarto de volta em torno de X", "ui.start": "Início", + "ui.start_over": "Recomeçar", "ui.start_radius": "Raio inicial", "ui.supersampling": "Supersampling (SSAA)", "ui.supersampling_adaptive": "Só quando a vista está parada", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 7cc15552e..9cd04228a 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -776,6 +776,7 @@ "ui.autosave_every": "Автосохранение каждые", "ui.axes": "Оси", "ui.axis": "Ось", + "ui.back": "Назад", "ui.base_point": "Базовая точка", "ui.bodies": "Тела", "ui.box": "Бокс", @@ -1177,8 +1178,34 @@ "ui.smooth_wheel_zoom": "Плавное масштабирование колесом", "ui.smooth_wheel_zoom_tip": "Отключите, чтобы каждое движение колеса применялось сразу, без сглаживания", "ui.snap": "Привязка", + "ui.space_mouse_calibrate": "Калибровать…", + "ui.space_mouse_calibrate_tip": "Двигайте колпачок так, как просит окно, чтобы SolidCraft узнал, куда и насколько далеко движется каждая ось этой 3D-мыши. Сохраняется для этой 3D-мыши.", + "ui.space_mouse_calibrate_title": "Калибровка 3D-мыши", + "ui.space_mouse_calibrated": "Откалибрована", + "ui.space_mouse_calibration": "Калибровка 3D-мыши", + "ui.space_mouse_calibration_done": "Готово. Сохраните её, чтобы она применялась всякий раз, когда подключена эта 3D-мышь.", + "ui.space_mouse_calibration_no_response": "Одна ось почти не сдвинулась, поэтому её нельзя откалибровать. Начните заново и каждый раз двигайте колпачок дальше.", + "ui.space_mouse_dead_zone": "Мёртвая зона", + "ui.space_mouse_dead_zone_tip": "Насколько нужно сдвинуть колпачок, прежде чем сдвинется вид, в доле от полного хода. Увеличьте, если вид смещается, когда колпачок в покое.", + "ui.space_mouse_forget": "Забыть калибровку", "ui.space_mouse_hint": "Совместное перемещение и вращение вида; в эскизе — только панорама и масштаб.", "ui.space_mouse_navigate": "Навигация через SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "3D-мышь не найдена", + "ui.space_mouse_not_calibrated": "Не откалибрована", + "ui.space_mouse_reading": "Показания", + "ui.space_mouse_step_lift": "Поднимите колпачок вверх, удержите и отпустите.", + "ui.space_mouse_step_press": "Нажмите на колпачок вниз, удержите и отпустите.", + "ui.space_mouse_step_pull": "Потяните колпачок на себя, удержите и отпустите.", + "ui.space_mouse_step_push": "Толкните колпачок от себя, удержите и отпустите.", + "ui.space_mouse_step_rest": "Уберите руку с колпачка и не трогайте его.", + "ui.space_mouse_step_slide_left": "Сдвиньте колпачок влево, удержите и отпустите.", + "ui.space_mouse_step_slide_right": "Сдвиньте колпачок вправо, удержите и отпустите.", + "ui.space_mouse_step_tilt_back": "Наклоните колпачок назад (передний край вверх), удержите и отпустите.", + "ui.space_mouse_step_tilt_forward": "Наклоните колпачок вперёд (передний край вниз), удержите и отпустите.", + "ui.space_mouse_step_tilt_left": "Наклоните колпачок влево (левый край вниз), удержите и отпустите.", + "ui.space_mouse_step_tilt_right": "Наклоните колпачок вправо (правый край вниз), удержите и отпустите.", + "ui.space_mouse_step_twist_clockwise": "Поверните колпачок по часовой стрелке, удержите и отпустите.", + "ui.space_mouse_step_twist_counterclockwise": "Поверните колпачок против часовой стрелки, удержите и отпустите.", "ui.spacing": "Интервал", "ui.spacing_2": "Интервал 2", "ui.sphere": "Сфера", @@ -1186,6 +1213,7 @@ "ui.split_body": "Разделить тело", "ui.stand_up_tip": "Если файл STEP или IGES открывается с Z вверх, предложить поворот на четверть оборота вокруг X", "ui.start": "Старт", + "ui.start_over": "Начать заново", "ui.start_radius": "Начальный радиус", "ui.suppress": "Подавить", "ui.sweep": "Сдвиг", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 861dd5fc5..f22c0478b 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -913,6 +913,7 @@ "ui.autosave_every": "Otomatik kaydetme aralığı", "ui.axes": "Eksenler", "ui.axis": "Eksen", + "ui.back": "Geri", "ui.base_point": "Temel nokta", "ui.blocked": "Engellenmiş", "ui.bodies": "Gövdeler", @@ -1316,8 +1317,34 @@ "ui.smooth_wheel_zoom": "Yumuşak tekerlek yakınlaştırması", "ui.smooth_wheel_zoom_tip": "Her tekerlek hareketini yumuşatma olmadan hemen uygulamak için kapatın", "ui.snap": "Yakala", + "ui.space_mouse_calibrate": "Kalibre et…", + "ui.space_mouse_calibrate_tip": "Pencerenin istediği gibi başlığı hareket ettirin; SolidCraft bu 3B farenin her ekseninin hangi yöne ve ne kadar gittiğini öğrensin. Bu 3B fare için kaydedilir.", + "ui.space_mouse_calibrate_title": "3B fareyi kalibre et", + "ui.space_mouse_calibrated": "Kalibre edildi", + "ui.space_mouse_calibration": "3B fare kalibrasyonu", + "ui.space_mouse_calibration_done": "Bitti. Bu 3B fare her bağlandığında kullanılması için kaydedin.", + "ui.space_mouse_calibration_no_response": "Bir eksen neredeyse hiç hareket etmedi, bu yüzden kalibre edilemiyor. Baştan başlayın ve başlığı her seferinde daha fazla hareket ettirin.", + "ui.space_mouse_dead_zone": "Ölü bölge", + "ui.space_mouse_dead_zone_tip": "Görünüm hareket etmeden önce başlığın ne kadar hareket etmesi gerektiği, tam hareket aralığının oranı olarak. Başlık dururken görünüm kayıyorsa artırın.", + "ui.space_mouse_forget": "Kalibrasyonu unut", "ui.space_mouse_hint": "Görünümü aynı anda kaydırın ve döndürün; eskizlerde yalnızca kaydırma ve yakınlaştırma kullanılır.", "ui.space_mouse_navigate": "SpaceNavigator / SpaceMouse ile gezin", + "ui.space_mouse_none": "3B fare bulunamadı", + "ui.space_mouse_not_calibrated": "Kalibre edilmedi", + "ui.space_mouse_reading": "Okunan değer", + "ui.space_mouse_step_lift": "Başlığı yukarı kaldırın, tutun, sonra bırakın.", + "ui.space_mouse_step_press": "Başlığı aşağı bastırın, tutun, sonra bırakın.", + "ui.space_mouse_step_pull": "Başlığı kendinize doğru çekin, tutun, sonra bırakın.", + "ui.space_mouse_step_push": "Başlığı sizden uzağa itin, tutun, sonra bırakın.", + "ui.space_mouse_step_rest": "Elinizi başlıktan çekin ve hareketsiz bırakın.", + "ui.space_mouse_step_slide_left": "Başlığı sola kaydırın, tutun, sonra bırakın.", + "ui.space_mouse_step_slide_right": "Başlığı sağa kaydırın, tutun, sonra bırakın.", + "ui.space_mouse_step_tilt_back": "Başlığı geriye eğin (ön kenar yukarı), tutun, sonra bırakın.", + "ui.space_mouse_step_tilt_forward": "Başlığı öne eğin (ön kenar aşağı), tutun, sonra bırakın.", + "ui.space_mouse_step_tilt_left": "Başlığı sola eğin (sol kenar aşağı), tutun, sonra bırakın.", + "ui.space_mouse_step_tilt_right": "Başlığı sağa eğin (sağ kenar aşağı), tutun, sonra bırakın.", + "ui.space_mouse_step_twist_clockwise": "Başlığı saat yönünde çevirin, tutun, sonra bırakın.", + "ui.space_mouse_step_twist_counterclockwise": "Başlığı saat yönünün tersine çevirin, tutun, sonra bırakın.", "ui.spacing": "Aralık", "ui.spacing_2": "Aralık 2", "ui.sphere": "Küre", @@ -1325,6 +1352,7 @@ "ui.split_body": "Gövdeyi böl", "ui.stand_up_tip": "Bir STEP veya IGES dosyası Z yukarı olarak açıldığında X etrafında çeyrek tur döndürmeyi öner", "ui.start": "Başlangıç", + "ui.start_over": "Baştan başla", "ui.start_radius": "Başlangıç yarıçapı", "ui.supersampling": "Süper örnekleme (SSAA)", "ui.supersampling_adaptive": "Yalnızca görünüm hareketsizken", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 2a936339b..ad83c4703 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -987,6 +987,7 @@ "ui.autosave_every": "Автозбереження кожні", "ui.axes": "Осі", "ui.axis": "Вісь", + "ui.back": "Назад", "ui.base_point": "Базова точка", "ui.blocked": "Заблоковані", "ui.bodies": "Тіла", @@ -1392,8 +1393,34 @@ "ui.smooth_wheel_zoom": "Плавне масштабування колесом", "ui.smooth_wheel_zoom_tip": "Вимкніть, щоб застосовувати кожну подію колеса негайно, без плавного завершення", "ui.snap": "Прив'язка", + "ui.space_mouse_calibrate": "Калібрувати…", + "ui.space_mouse_calibrate_tip": "Рухайте ковпачок так, як просить вікно, щоб SolidCraft дізнався, куди й наскільки далеко рухається кожна вісь цієї 3D-миші. Зберігається для цієї 3D-миші.", + "ui.space_mouse_calibrate_title": "Калібрування 3D-миші", + "ui.space_mouse_calibrated": "Відкалібровано", + "ui.space_mouse_calibration": "Калібрування 3D-миші", + "ui.space_mouse_calibration_done": "Готово. Збережіть його, щоб воно застосовувалося щоразу, коли підключено цю 3D-мишу.", + "ui.space_mouse_calibration_no_response": "Одна вісь майже не зрушила, тому її не можна відкалібрувати. Почніть спочатку й щоразу рухайте ковпачок далі.", + "ui.space_mouse_dead_zone": "Мертва зона", + "ui.space_mouse_dead_zone_tip": "Наскільки треба зсунути ковпачок, перш ніж зрушить вигляд, у частці від повного ходу. Збільште, якщо вигляд зміщується, коли ковпачок у спокої.", + "ui.space_mouse_forget": "Забути калібрування", "ui.space_mouse_hint": "Переміщуйте й обертайте вид разом; в ескізах доступні лише панорамування та масштаб.", "ui.space_mouse_navigate": "Навігація за допомогою SpaceNavigator / SpaceMouse", + "ui.space_mouse_none": "3D-мишу не знайдено", + "ui.space_mouse_not_calibrated": "Не відкалібровано", + "ui.space_mouse_reading": "Показники", + "ui.space_mouse_step_lift": "Підніміть ковпачок угору, утримайте й відпустіть.", + "ui.space_mouse_step_press": "Натисніть ковпачок униз, утримайте й відпустіть.", + "ui.space_mouse_step_pull": "Потягніть ковпачок до себе, утримайте й відпустіть.", + "ui.space_mouse_step_push": "Штовхніть ковпачок від себе, утримайте й відпустіть.", + "ui.space_mouse_step_rest": "Приберіть руку з ковпачка й не торкайтеся його.", + "ui.space_mouse_step_slide_left": "Зсуньте ковпачок ліворуч, утримайте й відпустіть.", + "ui.space_mouse_step_slide_right": "Зсуньте ковпачок праворуч, утримайте й відпустіть.", + "ui.space_mouse_step_tilt_back": "Нахиліть ковпачок назад (передній край угору), утримайте й відпустіть.", + "ui.space_mouse_step_tilt_forward": "Нахиліть ковпачок уперед (передній край униз), утримайте й відпустіть.", + "ui.space_mouse_step_tilt_left": "Нахиліть ковпачок ліворуч (лівий край униз), утримайте й відпустіть.", + "ui.space_mouse_step_tilt_right": "Нахиліть ковпачок праворуч (правий край униз), утримайте й відпустіть.", + "ui.space_mouse_step_twist_clockwise": "Поверніть ковпачок за годинниковою стрілкою, утримайте й відпустіть.", + "ui.space_mouse_step_twist_counterclockwise": "Поверніть ковпачок проти годинникової стрілки, утримайте й відпустіть.", "ui.spacing": "Крок", "ui.spacing_2": "Крок 2", "ui.sphere": "Куля", @@ -1401,6 +1428,7 @@ "ui.split_body": "Розділити тіло", "ui.stand_up_tip": "Після відкриття файлу STEP або IGES з напрямком Z вгору пропонувати поворот на чверть оберту навколо X", "ui.start": "Початок", + "ui.start_over": "Почати спочатку", "ui.start_radius": "Початковий радіус", "ui.supersampling": "Наддискретизація (SSAA)", "ui.supersampling_adaptive": "Лише коли вид нерухомий", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 7298363f4..f36707f37 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1074,6 +1074,7 @@ "ui.autosave_every": "自动保存间隔", "ui.axes": "轴", "ui.axis": "轴", + "ui.back": "返回", "ui.base_point": "基点", "ui.blocked": "被遮挡", "ui.bodies": "实体", @@ -1508,8 +1509,34 @@ "ui.smooth_wheel_zoom": "平滑滚轮缩放", "ui.smooth_wheel_zoom_tip": "关闭后每个滚轮事件立即生效,不做平滑延迟", "ui.snap": "捕捉", + "ui.space_mouse_calibrate": "校准…", + "ui.space_mouse_calibrate_tip": "按窗口提示移动摇杆帽,SolidCraft 会记住这个 3D 鼠标每个轴的方向和行程。校准结果按此 3D 鼠标保存。", + "ui.space_mouse_calibrate_title": "校准 3D 鼠标", + "ui.space_mouse_calibrated": "已校准", + "ui.space_mouse_calibration": "3D 鼠标校准", + "ui.space_mouse_calibration_done": "完成。保存后,每次连接此 3D 鼠标都会使用它。", + "ui.space_mouse_calibration_no_response": "有一个轴几乎没有移动,因此无法校准。请重新开始,并且每次把摇杆帽移得更远。", + "ui.space_mouse_dead_zone": "死区", + "ui.space_mouse_dead_zone_tip": "视图开始移动前摇杆帽需要移动的距离,以其全行程的比例表示。如果摇杆帽静止时视图仍在漂移,请调大。", + "ui.space_mouse_forget": "清除校准", "ui.space_mouse_hint": "同时移动和旋转视图;草图中仅支持平移和缩放。", "ui.space_mouse_navigate": "使用 SpaceNavigator / SpaceMouse 导航", + "ui.space_mouse_none": "未找到 3D 鼠标", + "ui.space_mouse_not_calibrated": "未校准", + "ui.space_mouse_reading": "读数", + "ui.space_mouse_step_lift": "向上提起摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_press": "向下按压摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_pull": "把摇杆帽拉向自己,保持住,然后松开。", + "ui.space_mouse_step_push": "把摇杆帽推离自己,保持住,然后松开。", + "ui.space_mouse_step_rest": "请把手从摇杆帽上移开,让它保持静止。", + "ui.space_mouse_step_slide_left": "向左推动摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_slide_right": "向右推动摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_tilt_back": "向后倾斜摇杆帽(前缘向上),保持住,然后松开。", + "ui.space_mouse_step_tilt_forward": "向前倾斜摇杆帽(前缘向下),保持住,然后松开。", + "ui.space_mouse_step_tilt_left": "向左倾斜摇杆帽(左缘向下),保持住,然后松开。", + "ui.space_mouse_step_tilt_right": "向右倾斜摇杆帽(右缘向下),保持住,然后松开。", + "ui.space_mouse_step_twist_clockwise": "顺时针扭转摇杆帽,保持住,然后松开。", + "ui.space_mouse_step_twist_counterclockwise": "逆时针扭转摇杆帽,保持住,然后松开。", "ui.spacing": "间距", "ui.spacing_2": "间距 2", "ui.sphere": "球体", @@ -1517,6 +1544,7 @@ "ui.split_body": "分割实体", "ui.stand_up_tip": "当 Z 朝上的 STEP 或 IGES 文件打开后,提示绕 X 轴旋转四分之一周", "ui.start": "开始", + "ui.start_over": "重新开始", "ui.start_radius": "起始半径", "ui.stretch": "伸展", "ui.supersampling": "超级采样 (SSAA)", diff --git a/crates/space-mouse/Cargo.toml b/crates/space-mouse/Cargo.toml index 7ae84345e..264ba6ab2 100644 --- a/crates/space-mouse/Cargo.toml +++ b/crates/space-mouse/Cargo.toml @@ -7,3 +7,7 @@ license.workspace = true [lints] workspace = true + +[dependencies] +# Saving a calibration with the app's preferences; off by default, so the crate needs nothing. +serde = { workspace = true, optional = true } diff --git a/crates/space-mouse/src/calibration.rs b/crates/space-mouse/src/calibration.rs new file mode 100644 index 000000000..bf8242520 --- /dev/null +++ b/crates/space-mouse/src/calibration.rs @@ -0,0 +1,1357 @@ +//! Calibration: which of a device's raw axes is which, and how far each one goes. The user holds +//! the cap still, then moves it along each axis both ways; [`Recording::solve`] turns what the +//! device sent into a [`Calibration`] that maps any reading onto 3Dconnexion's axes (X right, +//! Y towards the user, Z down, the rotations about them right-handed), ±[`FULL_SCALE`] at full +//! deflection. Everything after that, the driver mapping and the user's per-axis choices, then +//! treats every device the same. + +use crate::FULL_SCALE; + +/// One motion the user is asked for: a canonical axis, one way. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Step { + /// 0..3 = X, Y, Z; 3..6 = rotation about them. + pub axis: usize, + pub positive: bool, +} + +/// The motions, in the order they are asked for. The positive direction of each is what both +/// 3Dconnexion devices we measured report as positive: slide right, pull towards you, press down, +/// tilt back, tilt left, twist clockwise seen from above. +pub const STEPS: [Step; 12] = { + let mut steps = [Step { axis: 0, positive: true }; 12]; + let mut i = 0; + while i < 12 { + steps[i] = Step { axis: i / 2, positive: i % 2 == 0 }; + i += 1; + } + steps +}; + +/// Where one canonical axis comes from, and how to scale it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct AxisCalibration { + /// The raw axis it is read from. + pub source: usize, + /// The raw axis runs the other way. + pub reversed: bool, + /// The raw value with the cap at rest. + pub rest: i16, + /// How far from `rest` the value wanders with nobody touching the cap; readings within it are 0. + pub dead_zone: u16, + /// How far below and above `rest` the value goes at full deflection; each reads as + /// ±[`FULL_SCALE`], so a device that goes further one way than the other still reaches full + /// scale both ways. + pub full: [u16; 2], +} + +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Calibration { + /// The user's dead zone on top of each axis's measured one, as a share of full deflection + /// (up to [`MAX_DEAD_ZONE_SHARE`]): readings within it are 0, and the rest of the travel + /// still reaches full scale. Widening it settles a device that drifts at rest, or whose rest + /// calibrated off. Calibrations saved before it existed read as 0. + #[cfg_attr(feature = "serde", serde(default))] + pub dead_zone_share: f32, + pub axes: [AxisCalibration; 6], +} + +/// The widest dead zone a calibration takes, as a share of full deflection. +pub const MAX_DEAD_ZONE_SHARE: f32 = 0.5; + +impl Calibration { + /// A reading in the device's raw axes, on the canonical ones. Past full deflection the value + /// keeps growing, up to the i16 range; a source the device doesn't have reads 0. + pub fn apply(&self, raw: [i16; 6]) -> [i16; 6] { + let share = if self.dead_zone_share.is_finite() { self.dead_zone_share.clamp(0.0, MAX_DEAD_ZONE_SHARE) } else { 0.0 }; + let shared = (f64::from(share) * f64::from(FULL_SCALE)).round() as i32; + self.axes.map(|axis| { + let Some(&value) = raw.get(axis.source) else { return 0 }; + let offset = i32::from(value) - i32::from(axis.rest); + let dead = i32::from(axis.dead_zone); + let full = axis.full[usize::from(offset > 0)]; + let span = (i32::from(full) - dead).max(1); + let past = offset.abs() - dead; + if past <= 0 { + return 0; + } + // In i64: a short calibrated range and an extreme reading go far past i32 here. + let full_scale = i64::from(FULL_SCALE); + let scaled = i64::from(past) * full_scale / i64::from(span); + // The user's dead zone, in the same units; the travel past it stretches back to full scale. + if scaled <= i64::from(shared) { + return 0; + } + let scaled = ((scaled - i64::from(shared)) * full_scale / (full_scale - i64::from(shared))).min(i64::from(i16::MAX)); + let signed = if (offset < 0) != axis.reversed { -scaled } else { scaled }; + i16::try_from(signed).unwrap_or(0) + }) + } + + /// How far each canonical axis is through its travel before any dead zone: ±1 at full + /// deflection either way, further past it. Where a reading sits on a picture of the axis. + pub fn travel(&self, raw: [i16; 6]) -> [f32; 6] { + self.axes.map(|axis| { + let Some(&value) = raw.get(axis.source) else { return 0.0 }; + let offset = f32::from(value) - f32::from(axis.rest); + let share = offset / f32::from(axis.full[usize::from(offset > 0.0)]).max(1.0); + if axis.reversed { -share } else { share } + }) + } + + /// How much of each canonical axis's travel reads as no motion, `[negative, positive]` as + /// shares of it: the measured dead zone with the user's on top, as [`Calibration::apply`] has it. + pub fn dead_zone_shares(&self) -> [[f32; 2]; 6] { + let user = if self.dead_zone_share.is_finite() { self.dead_zone_share.clamp(0.0, MAX_DEAD_ZONE_SHARE) } else { 0.0 }; + self.axes.map(|axis| { + let [below, above] = axis.full.map(|full| (f32::from(axis.dead_zone) / f32::from(full).max(1.0)).min(1.0)); + let sides = if axis.reversed { [above, below] } else { [below, above] }; + sides.map(|measured| measured + (1.0 - measured) * user) + }) + } + + /// Each raw axis's value at rest, which calibrates to no motion: what an app reads a raw axis + /// as while it has nothing fresh from it. A raw axis no canonical one reads rests at 0. + pub fn raw_rest(&self) -> [i16; 6] { + let mut rest = [0; 6]; + for axis in &self.axes { + if let Some(raw) = rest.get_mut(axis.source) { + *raw = axis.rest; + } + } + rest + } + + /// Whether it can be used as it is: each canonical axis reads its own raw axis, and goes + /// further both ways at full deflection than it wanders at rest. Every calibration + /// [`Recording::solve`] gives is; one from a hand-edited settings file may not be, and could + /// turn any touch of the cap into full speed. Its dead zone has to be a share from 0 to + /// [`MAX_DEAD_ZONE_SHARE`]. + pub fn is_usable(&self) -> bool { + let mut used = [false; 6]; + (0.0..=MAX_DEAD_ZONE_SHARE).contains(&self.dead_zone_share) + && self.axes.iter().all(|axis| { + axis.full.iter().all(|&full| full > axis.dead_zone) && used.get_mut(axis.source).is_some_and(|used| !std::mem::replace(used, true)) + }) + } +} + +/// Why a recording didn't give a calibration. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Problem { + /// Nothing was recorded with the cap at rest. + NoRest, + /// Nothing was recorded for this step. + NotRecorded(Step), + /// Moving the cap along this canonical axis barely moved its raw axis one way: less than twice + /// what it wanders at rest, or less than [`MIN_SHARE`] of how far any axis went. + NoResponse(usize), +} + +#[derive(Clone, Copy, Debug)] +struct Samples { + sum: [f64; 6], + count: u32, + min: [i16; 6], + max: [i16; 6], +} + +impl Default for Samples { + fn default() -> Self { + Self { sum: [0.0; 6], count: 0, min: [i16::MAX; 6], max: [i16::MIN; 6] } + } +} + +impl Samples { + fn add(&mut self, raw: [i16; 6]) { + for (((sum, min), max), value) in self.sum.iter_mut().zip(&mut self.min).zip(&mut self.max).zip(raw) { + *sum += f64::from(value); + *min = (*min).min(value); + *max = (*max).max(value); + } + self.count += 1; + } + + fn mean(&self) -> Option<[f64; 6]> { + (self.count > 0).then(|| self.sum.map(|sum| sum / f64::from(self.count))) + } + + /// Where raw axis `r` rests (its mean, rounded) and how far its readings went from there; + /// `None` without readings. + fn rest_and_wander(&self, r: usize) -> Option<(f64, f64)> { + let rest = self.mean()?.get(r)?.round(); + let (min, max) = (f64::from(*self.min.get(r)?), f64::from(*self.max.get(r)?)); + Some((rest, (max - rest).max(rest - min).max(0.0))) + } + + /// How far apart raw axis `r`'s lowest and highest readings were; 0 without readings. + fn spread(&self, r: usize) -> f64 { + match (self.min.get(r), self.max.get(r)) { + (Some(&min), Some(&max)) => (f64::from(max) - f64::from(min)).max(0.0), + _ => 0.0, + } + } +} + +/// What the device sent during calibration: readings at rest, during each of [`STEPS`], and +/// where the cap came back to after each one. +#[derive(Clone, Debug, Default)] +pub struct Recording { + rest: Samples, + steps: [Samples; 12], + /// The readings the cap settled on after step `n` was let go: all of a steady run. + settled: [Samples; 12], +} + +impl Recording { + /// One reading with nobody touching the cap. + pub fn rest(&mut self, raw: [i16; 6]) { + self.rest.add(raw); + } + + /// One reading during step `index` of [`STEPS`]; any other index is ignored. + pub fn step(&mut self, index: usize, raw: [i16; 6]) { + if let Some(samples) = self.steps.get_mut(index) { + samples.add(raw); + } + } + + /// One reading of where the cap settled after step `index` was let go; any other index is ignored. + pub fn settled(&mut self, index: usize, raw: [i16; 6]) { + if let Some(settled) = self.settled.get_mut(index) { + settled.add(raw); + } + } + + /// Whether step `index` has a reading yet. + pub fn has_step(&self, index: usize) -> bool { + self.steps.get(index).is_some_and(|samples| samples.count > 0) + } + + /// Forgets what was recorded for step `index`. + fn clear_step(&mut self, index: usize) { + if let Some(samples) = self.steps.get_mut(index) { + *samples = Samples::default(); + } + if let Some(settled) = self.settled.get_mut(index) { + *settled = Samples::default(); + } + } + + /// The calibration the recording gives. Hands are never exact: sliding the cap tilts it a + /// little and tilting it slides it, sometimes further than the axis being asked for. So the + /// raw axis for each canonical one isn't the one that moved most in its step. It is the + /// one-to-one assignment that best explains all six axes together, scored by how far each + /// raw axis moved between the step's two directions, as a share of the furthest it moved in + /// any step: an axis with a wider range doesn't win through cross-talk alone. A raw axis that + /// only wandered scores low, since its share is of at least four times its wander at rest. + /// + /// A device that doesn't come back to the same place after each release (a drifting stick, or + /// spacenavd keeping a relative-axis device's last small report, #2778) rests, here, at the + /// middle of everything it read at rest and after each release, and its dead zone covers all of + /// it, so where it stops doesn't creep. + pub fn solve(&self) -> Result { + let rest = self.rest.mean().ok_or(Problem::NoRest)?; + let mut means = [[0.0; 6]; 12]; + for ((mean, samples), step) in means.iter_mut().zip(&self.steps).zip(STEPS) { + *mean = samples.mean().ok_or(Problem::NotRecorded(step))?; + } + // travel[c][r]: how far raw axis r moved from canonical axis c's negative step to its positive one. + let travel: [[f64; 6]; 6] = std::array::from_fn(|c| std::array::from_fn(|r| means[2 * c][r] - means[2 * c + 1][r])); + let widest: [f64; 6] = std::array::from_fn(|r| travel.iter().map(|row| row[r].abs()).fold(4.0 * self.rest.spread(r), f64::max).max(1.0)); + let shares: [[f64; 6]; 6] = std::array::from_fn(|c| std::array::from_fn(|r| travel[c][r].abs() / widest[r])); + let sources = best_assignment(&shares); + let mut axes = [AxisCalibration { source: 0, reversed: false, rest: 0, dead_zone: 0, full: [0; 2] }; 6]; + for (c, (axis, source)) in axes.iter_mut().zip(sources).enumerate() { + let (rest_value, wander) = self.rest.rest_and_wander(source).unwrap_or((rest[source].round(), 0.0)); + let (rest_value, wander) = self.settled_rest(source, rest_value, wander); + let (positive, negative) = (&self.steps[2 * c], &self.steps[2 * c + 1]); + let reversed = travel[c][source] < 0.0; + // The steps that push the raw axis above and below rest, and how far each got. + let (above, below) = if reversed { (negative, positive) } else { (positive, negative) }; + let full = [rest_value - f64::from(below.min[source]), f64::from(above.max[source]) - rest_value]; + if full.iter().any(|&full| full < 2.0 * wander || full < 1.0) { + return Err(Problem::NoResponse(c)); + } + *axis = AxisCalibration { + source, + reversed, + rest: rest_value.clamp(f64::from(i16::MIN), f64::from(i16::MAX)) as i16, + dead_zone: wander.min(f64::from(u16::MAX)) as u16, + full: full.map(|full| full.min(f64::from(u16::MAX)) as u16), + }; + } + let most = axes.iter().flat_map(|axis| axis.full).max().unwrap_or(0); + if let Some(c) = axes.iter().position(|axis| axis.full.iter().any(|&full| f64::from(full) < MIN_SHARE * f64::from(most))) { + return Err(Problem::NoResponse(c)); + } + Ok(Calibration { dead_zone_share: 0.0, axes }) + } +} + +impl Recording { + /// Raw axis `r`'s rest and dead zone, given the rest stage's: unchanged while every reading + /// after a release stayed within the wander; otherwise the middle of everything read at rest + /// and after the releases, with a dead zone reaching every one of those readings. + fn settled_rest(&self, r: usize, rest: f64, wander: f64) -> (f64, f64) { + let (mut low, mut high) = (rest - wander, rest + wander); + for settled in self.settled.iter().filter(|settled| settled.count > 0) { + if let (Some(&min), Some(&max)) = (settled.min.get(r), settled.max.get(r)) { + (low, high) = (low.min(f64::from(min)), high.max(f64::from(max))); + } + } + if low >= rest - wander && high <= rest + wander { + return (rest, wander); + } + let middle = ((low + high) / 2.0).round(); + (middle, (high - middle).max(middle - low)) + } +} + +/// The raw axis for each canonical one, each raw axis used once, with the highest total share. +fn best_assignment(shares: &[[f64; 6]; 6]) -> [usize; 6] { + fn search(shares: &[[f64; 6]; 6], canonical: usize, used: [bool; 6], current: &mut [usize; 6], total: f64, best: &mut ([usize; 6], f64)) { + if canonical == 6 { + if total > best.1 { + *best = (*current, total); + } + return; + } + for raw in 0..6 { + if !used[raw] { + let mut now_used = used; + now_used[raw] = true; + current[canonical] = raw; + search(shares, canonical + 1, now_used, current, total + shares[canonical][raw], best); + } + } + } + let mut best = ([0, 1, 2, 3, 4, 5], f64::NEG_INFINITY); + search(shares, 0, [false; 6], &mut [0; 6], 0.0, &mut best); + best.0 +} + +/// The least a direction may go, as a share of how far the furthest axis went, before it counts +/// as not having responded. It turns away a step that recorded a resting hand rather than a push, +/// which would otherwise scale a few units of noise up to full speed, and still lets a homemade +/// device go ten times further one way than the other. +pub const MIN_SHARE: f64 = 1.0 / 12.0; + +/// Seconds of readings with the cap at rest before the first step. +pub const REST_SECONDS: f64 = 1.5; +/// Seconds the cap has to be held out in a step's direction before letting go finishes it. +pub const HOLD_SECONDS: f64 = 0.4; +/// Seconds the reading has to stay steady, back close to rest, to count as let go even outside the +/// rest wander: the cap stopped short of rest, as a drifting stick does, or spacenavd with a +/// relative-axis device (#2778). Back close to rest means the axis that went furthest this step is +/// at least [`RETURNED_SHARE`] of the way back, and some axis that moved about as far (at least +/// half as far) is within [`SETTLED_SHARE`] of its own peak: cross-talk can move another raw axis +/// further than the one being asked for, and which raw axis that is isn't known yet. Steady means +/// each raw axis's readings span no more than twice its rest wander, at least 4 units (±2) and +/// [`STEADY_SHARE`] of the furthest that axis has gone in any step: an axis that read flat at rest +/// may still dither once it's off-centre. +pub const SETTLE_SECONDS: f64 = 0.5; +/// How far from rest, as a share of its peak this step, an axis that moved has to be to count as let go. +pub const SETTLED_SHARE: f64 = 0.25; +/// How far from rest, as a share of its peak, the axis that went furthest may still be when the +/// step counts as let go. A hand still holding the push keeps it out. +pub const RETURNED_SHARE: f64 = 0.5; +/// The least spread steady readings may have, as a share of the furthest the axis has gone. +pub const STEADY_SHARE: f64 = 1.0 / 50.0; + +/// Where the guided calibration is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stage { + /// Hands off the cap. + Rest, + /// Step `n` of [`STEPS`]. + Step(usize), + /// Every step is recorded. + Done, +} + +/// The guided calibration: it records the cap at rest, then each of [`STEPS`] in turn, and moves +/// on by itself, so the user's hand stays on the cap. A step is done once the cap has been held +/// out for [`HOLD_SECONDS`] in one go and let go. Before calibration nothing says how far a raw +/// axis goes, so "held out" only means some raw axis is at least twice as far from rest as it +/// wandered at rest, each axis measured against its own wander: the least [`Recording::solve`] +/// accepts. So whatever the solver would accept can be recorded, a noisy axis doesn't hold up a +/// quiet one, and the solver judges whether each direction went far enough. "Let go" means every +/// raw axis is back within its rest wander, or the reading has gone steady close to rest +/// ([`SETTLE_SECONDS`], [`SETTLED_SHARE`]). +#[derive(Clone, Debug)] +pub struct Wizard { + stage: Stage, + recording: Recording, + /// Seconds spent in the current stage: at rest, or held out. + seconds: f64, + /// The dead zone the user set while calibrating, which the result carries. + dead_zone_share: f32, + /// The readings since the reading went steady, and for how long. + run: Samples, + steady: f64, + /// How far each raw axis went from rest in this step, in raw units. + peaks: [f64; 6], + /// The furthest each raw axis went from rest in any step so far. + reach: [f64; 6], + /// The readings the previous step settled on: while a reading stays within their spread, nobody has touched the cap. + settled: Option, +} + +impl Default for Wizard { + fn default() -> Self { + Self { + stage: Stage::Rest, + recording: Recording::default(), + seconds: 0.0, + dead_zone_share: 0.0, + run: Samples::default(), + steady: 0.0, + peaks: [0.0; 6], + reach: [0.0; 6], + settled: None, + } + } +} + +impl Wizard { + pub fn stage(&self) -> Stage { + self.stage + } + + /// How far through the current stage, 0..=1: the time at rest, or held out. + pub fn progress(&self) -> f64 { + match self.stage { + Stage::Rest => (self.seconds / REST_SECONDS).min(1.0), + Stage::Step(_) => (self.seconds / HOLD_SECONDS).min(1.0), + Stage::Done => 1.0, + } + } + + /// One reading, `seconds` after the previous one. + pub fn feed(&mut self, raw: [i16; 6], seconds: f64) { + // A stalled frame shouldn't finish a stage on its own. + let seconds = if seconds.is_finite() { seconds.clamp(0.0, 0.1) } else { 0.0 }; + // Steady while every axis's readings since the run began stay within its noise. + let mut run = self.run; + run.add(raw); + if (0..6).all(|r| run.spread(r) <= self.tolerance(r)) { + self.steady += seconds; + } else { + (run, self.steady) = (Samples::default(), 0.0); + run.add(raw); + } + self.run = run; + match self.stage { + Stage::Rest => { + self.recording.rest(raw); + self.seconds += seconds; + if self.seconds >= REST_SECONDS { + self.enter(Stage::Step(0)); + } + } + Stage::Step(index) => { + // Still where the last step settled: the cap hasn't been touched yet. Deliberately + // skips the peak and hold bookkeeping; a device that rests exactly there reads as + // untouched until it moves, which is what it is. + if self.settled.is_some_and(|settled| self.near(settled, raw)) { + return; + } + self.settled = None; + let away = self.away(raw); + let offsets = self.offsets(raw); + for ((peak, reach), offset) in self.peaks.iter_mut().zip(&mut self.reach).zip(offsets) { + *peak = peak.max(offset); + *reach = reach.max(offset); + } + let furthest = self.peaks.iter().copied().fold(0.0, f64::max); + let peaks = self.peaks; + // Close to rest is the cap settling, never held; it has let go once it's steady there. + // Every axis that moved about as far as the furthest has to be back by + // `RETURNED_SHARE` of its own peak too, or a lesser axis still held out would be + // missed while a larger cross-talk axis relaxes. + let settling = (0..6).any(|r| peaks[r] == furthest && offsets[r] <= RETURNED_SHARE * furthest) + && (0..6).any(|r| peaks[r] >= 0.5 * furthest && offsets[r] <= SETTLED_SHARE * peaks[r]) + && (0..6).all(|r| peaks[r] < 0.5 * furthest || offsets[r] <= RETURNED_SHARE * peaks[r]); + let stopped = settling && (self.steady >= SETTLE_SECONDS); + if away <= 0.5 || stopped { + // Where it settled: every reading of the steady run, or just this one. + let mut settled = Samples::default(); + settled.add(raw); + if stopped { + settled = self.run; + } + if self.seconds >= HOLD_SECONDS { + // Every reading of the steady run, so the dead zone covers all of them. + if stopped { + self.recording.settled[index] = self.run; + } else { + self.recording.settled(index, raw); + } + self.enter(if index + 1 < STEPS.len() { Stage::Step(index + 1) } else { Stage::Done }); + self.settled = Some(settled); + } else if self.seconds > 0.0 { + // Let go too soon: the hold starts over, and only a whole one is kept. + self.recording.clear_step(index); + self.enter(Stage::Step(index)); + self.settled = Some(settled); + } + } else if away >= 1.0 && !settling { + self.recording.step(index, raw); + self.seconds += seconds; + } + } + Stage::Done => {} + } + } + + /// Goes back one step and records it again; from the first step, back to rest. + pub fn back(&mut self) { + match self.stage { + Stage::Rest => {} + Stage::Step(0) => *self = Self::default(), + Stage::Step(index) => { + self.recording.clear_step(index); + self.recording.clear_step(index - 1); + self.enter(Stage::Step(index - 1)); + } + Stage::Done => { + self.recording.clear_step(STEPS.len() - 1); + self.enter(Stage::Step(STEPS.len() - 1)); + } + } + } + + /// Once every step is recorded, the calibration they give, with the dead zone set here. + pub fn result(&self) -> Option> { + (self.stage == Stage::Done) + .then(|| self.recording.solve().map(|calibration| Calibration { dead_zone_share: self.dead_zone_share, ..calibration })) + } + + pub fn dead_zone_share(&self) -> f32 { + self.dead_zone_share + } + + /// Sets the dead zone the result carries, a share from 0 to [`MAX_DEAD_ZONE_SHARE`]; anything + /// else is held to that range, and a value that isn't a number reads as 0. + pub fn set_dead_zone_share(&mut self, share: f32) { + self.dead_zone_share = if share.is_finite() { share.clamp(0.0, MAX_DEAD_ZONE_SHARE) } else { 0.0 }; + } + + fn enter(&mut self, stage: Stage) { + self.stage = stage; + self.seconds = 0.0; + self.peaks = [0.0; 6]; + // A new stage's steadiness starts with its own readings. + (self.run, self.steady) = (Samples::default(), 0.0); + } + + /// How far each raw axis is from rest, in raw units. + fn offsets(&self, raw: [i16; 6]) -> [f64; 6] { + std::array::from_fn(|r| (f64::from(raw[r]) - self.recording.rest.rest_and_wander(r).map_or(0.0, |(rest, _)| rest)).abs()) + } + + /// How far apart raw axis `r`'s readings may be and still be one position: its noise's whole + /// spread (twice its rest wander), at least 4 units (±2) and [`STEADY_SHARE`] of the furthest it + /// has gone in any step. + fn tolerance(&self, r: usize) -> f64 { + let wander = self.recording.rest.rest_and_wander(r).map_or(0.0, |(_, wander)| wander); + (2.0 * wander).max(4.0).max(STEADY_SHARE * self.reach.get(r).copied().unwrap_or(0.0)) + } + + /// Whether `raw` is still where `settled` was: adding it keeps every axis within [`Self::tolerance`], + /// the same band the steadiness check accepts. + fn near(&self, mut settled: Samples, raw: [i16; 6]) -> bool { + settled.add(raw); + (0..6).all(|r| settled.spread(r) <= self.tolerance(r)) + } + + /// How far the reading is from rest, on the raw axis furthest out, as a share of what counts as + /// held out for that axis (twice its rest wander, at least one unit): 1 or more is held out, + /// half or less is back within its wander. + fn away(&self, raw: [i16; 6]) -> f64 { + raw.iter() + .enumerate() + .map(|(r, &value)| { + let (rest, wander) = self.recording.rest.rest_and_wander(r).unwrap_or((0.0, 0.0)); + (f64::from(value) - rest).abs() / (2.0 * wander).max(1.0) + }) + .fold(0.0, f64::max) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The mean of each axis (X Y Z Rx Ry Rz) during each step, in `STEPS` order, as measured + /// with our own SpaceMouse Pro (046d:c62b) following capture prompts. Note the slide right + /// row: Ry moved further than X. + const PRO: [[i16; 6]; 12] = [ + [250, -10, 0, 0, -336, 0], // slide right + [-277, 55, 86, -36, -196, 0], // slide left + [0, 324, 82, -26, -3, -28], // pull towards you + [-2, -340, 219, -26, -20, 0], // push away + [-1, -3, 344, 0, -37, 0], // press down + [41, -24, -341, -11, -10, 32], // lift up + [0, 193, 0, 333, -26, 0], // tilt back + [0, -339, 163, -183, 0, 0], // tilt forward + [61, 0, 1, -12, 328, 0], // tilt left + [9, 80, 1, 0, -330, -6], // tilt right + [0, -1, 78, 0, 0, 341], // twist clockwise + [0, -6, 0, 0, -4, -337], // twist counterclockwise + ]; + + /// The same with our own SpaceMouse Wireless (256f:c63a), all six axes in one report. + const WIRELESS: [[i16; 6]; 12] = [ + [325, 92, 72, 0, 44, -6], + [-336, 38, 104, 19, -66, 5], + [-5, 339, 73, -71, 0, 0], + [-18, -323, 144, -2, 1, 0], + [0, 1, 341, -2, 2, 0], + [0, 1, -320, 1, -43, 0], + [0, -12, 3, 330, 4, -24], + [0, 51, 17, -319, -20, 0], + [-23, 0, 0, -1, 333, 0], + [7, 41, 23, 15, -163, -13], + [-13, 4, 44, -12, -12, 326], + [0, -1, -1, 1, -9, -313], + ]; + + fn record(steps: [[i16; 6]; 12], rest: [[i16; 6]; 2]) -> Recording { + let mut recording = Recording::default(); + for reading in rest { + recording.rest(reading); + } + for (index, reading) in steps.into_iter().enumerate() { + recording.step(index, reading); + } + recording + } + + const STILL: [[i16; 6]; 2] = [[-3, 2, 0, 1, -2, 0], [3, -2, 0, -1, 2, 0]]; + + #[test] + fn both_3dconnexion_devices_calibrate_to_their_own_axes() { + for steps in [PRO, WIRELESS] { + let calibration = record(steps, STILL).solve().unwrap(); + for (c, axis) in calibration.axes.iter().enumerate() { + assert_eq!((axis.source, axis.reversed), (c, false), "axis {c}"); + assert!(axis.full.iter().all(|full| (150..=350).contains(full)), "axis {c}: {axis:?}"); + } + } + } + + #[test] + fn a_homemade_device_with_shuffled_reversed_wider_axes_is_found() { + // A device reporting ±32767, its axes in another order (raw r carries canonical + // ORDER[r]), the odd ones running the other way, at rest around 100. + const ORDER: [usize; 6] = [4, 0, 5, 2, 1, 3]; + let wire = |canonical: [i16; 6]| -> [i16; 6] { + std::array::from_fn(|r| { + let v = i32::from(canonical[ORDER[r]]) * 32767 / 350; + i16::try_from(if r % 2 == 1 { -v } else { v } + 100).unwrap() + }) + }; + let calibration = record(PRO.map(wire), STILL.map(wire)).solve().unwrap(); + for (c, axis) in calibration.axes.iter().enumerate() { + let r = ORDER.iter().position(|&o| o == c).unwrap(); + assert_eq!((axis.source, axis.reversed), (r, r % 2 == 1), "axis {c}"); + assert_eq!(axis.rest, 100); + } + // Each step now reads on its own axis, the right way, at full scale: each direction is + // scaled on its own, so the Pro's shorter tilt forward gets there too. + for (step, reading) in STEPS.iter().zip(PRO.map(wire)) { + let value = calibration.apply(reading)[step.axis]; + assert_eq!(value, if step.positive { FULL_SCALE } else { -FULL_SCALE }, "{step:?}"); + } + } + + #[test] + fn readings_within_the_rest_wander_are_zero_and_full_deflection_is_full_scale() { + let axis = AxisCalibration { source: 1, reversed: true, rest: 10, dead_zone: 5, full: [105; 2] }; + let calibration = Calibration { dead_zone_share: 0.0, axes: [axis; 6] }; + assert_eq!(calibration.apply([0, 14, 0, 0, 0, 0]), [0; 6]); + assert_eq!(calibration.apply([0, 115, 0, 0, 0, 0]), [-FULL_SCALE; 6]); + assert_eq!(calibration.apply([0, -95, 0, 0, 0, 0]), [FULL_SCALE; 6]); + // Past full deflection the value keeps going, up to the i16 range. + assert_eq!(calibration.apply([0, i16::MIN, 0, 0, 0, 0]), [i16::MAX; 6]); + } + + #[test] + fn a_device_that_goes_further_one_way_reaches_full_scale_both_ways() { + let axis = AxisCalibration { source: 0, reversed: false, rest: 0, dead_zone: 0, full: [200, 500] }; + let calibration = Calibration { dead_zone_share: 0.0, axes: [axis; 6] }; + assert_eq!(calibration.apply([500, 0, 0, 0, 0, 0]), [FULL_SCALE; 6]); + assert_eq!(calibration.apply([-200, 0, 0, 0, 0, 0]), [-FULL_SCALE; 6]); + assert_eq!(calibration.apply([-100, 0, 0, 0, 0, 0]), [-FULL_SCALE / 2; 6]); + } + + #[test] + fn the_users_dead_zone_comes_off_the_bottom_and_full_deflection_stays_full_scale() { + let axis = AxisCalibration { source: 0, reversed: false, rest: 0, dead_zone: 0, full: [350; 2] }; + let calibration = Calibration { dead_zone_share: 0.2, axes: [axis; 6] }; + assert_eq!(calibration.apply([70, 0, 0, 0, 0, 0])[0], 0, "a fifth of the travel is inside it"); + assert_eq!(calibration.apply([210, 0, 0, 0, 0, 0])[0], 175, "60% of the travel is halfway past it"); + assert_eq!(calibration.apply([-350, 0, 0, 0, 0, 0])[0], -FULL_SCALE); + // Out of range or not a number: held to the range, or none. + assert_eq!(Calibration { dead_zone_share: 9.0, ..calibration }.apply([170, 0, 0, 0, 0, 0])[0], 0); + assert_eq!(Calibration { dead_zone_share: f32::NAN, ..calibration }.apply([70, 0, 0, 0, 0, 0])[0], 70); + let solved = record(PRO, STILL).solve().unwrap(); + assert!(Calibration { dead_zone_share: 0.5, ..solved }.is_usable()); + assert!(!Calibration { dead_zone_share: 0.6, ..solved }.is_usable()); + assert!(!Calibration { dead_zone_share: f32::NAN, ..solved }.is_usable()); + assert!(!Calibration { dead_zone_share: -0.1, ..solved }.is_usable()); + } + + #[test] + fn extreme_readings_on_a_short_range_saturate_with_the_right_sign() { + // Six distinct sources, each with a range of one unit: any real reading is far past it. + let axes: [AxisCalibration; 6] = std::array::from_fn(|c| AxisCalibration { + source: (c + 2) % 6, + reversed: c % 2 == 1, + rest: if c < 3 { 0 } else { i16::MIN }, + dead_zone: 0, + full: [1, 1], + }); + for dead_zone_share in [0.0, MAX_DEAD_ZONE_SHARE] { + let calibration = Calibration { dead_zone_share, axes }; + assert!(calibration.is_usable()); + let read = |raw: [i16; 6]| calibration.apply(raw); + for (raw, sign) in [(i16::MAX, 1), (i16::MIN, -1)] { + let out = read([raw; 6]); + for (c, axis) in calibration.axes.iter().enumerate() { + let offset = i32::from(raw) - i32::from(axis.rest); + let expected = if offset == 0 { + 0 + } else { + let positive = (offset > 0) != axis.reversed; + if positive { i16::MAX } else { -i16::MAX } + }; + assert_eq!(out[c], expected, "share {dead_zone_share}, raw {raw} (sign {sign}), axis {c}: {axis:?}"); + } + } + } + } + + #[test] + fn the_dead_zone_set_while_calibrating_goes_with_the_result() { + let mut wizard = Wizard::default(); + wizard.set_dead_zone_share(0.15); + rest_then(&mut wizard); + for reading in PRO { + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, STILL[0], 0.1); + } + assert_eq!(wizard.result().unwrap().unwrap().dead_zone_share, 0.15); + wizard.set_dead_zone_share(f32::NAN); + assert_eq!(wizard.dead_zone_share(), 0.0); + wizard.set_dead_zone_share(2.0); + assert_eq!(wizard.dead_zone_share(), MAX_DEAD_ZONE_SHARE); + } + + #[test] + fn a_device_at_its_raw_rest_reads_no_motion() { + let axis = |source, rest| AxisCalibration { source, reversed: source % 2 == 1, rest, dead_zone: 0, full: [350; 2] }; + let calibration = + Calibration { dead_zone_share: 0.0, axes: [axis(3, 100), axis(0, -40), axis(1, 7), axis(2, 0), axis(5, 1000), axis(4, -1)] }; + assert_eq!(calibration.raw_rest(), [-40, 7, 0, 100, -1, 1000]); + assert_eq!(calibration.apply(calibration.raw_rest()), [0; 6]); + } + + #[test] + fn a_source_the_device_doesnt_have_reads_zero() { + let axis = AxisCalibration { source: 9, reversed: false, rest: 0, dead_zone: 0, full: [350; 2] }; + assert_eq!(Calibration { dead_zone_share: 0.0, axes: [axis; 6] }.apply([350; 6]), [0; 6]); + } + + #[test] + fn a_missing_step_or_rest_is_named() { + let mut recording = record(PRO, STILL); + recording.steps[7] = Samples::default(); + assert_eq!(recording.solve(), Err(Problem::NotRecorded(STEPS[7]))); + assert!(!recording.has_step(7) && recording.has_step(6)); + assert_eq!(Recording::default().solve(), Err(Problem::NoRest)); + } + + #[test] + fn an_axis_that_barely_moves_is_named() { + let mut steps = PRO; + // Twisting did nothing beyond what the cap wanders at rest. + steps[10] = [0, 0, 0, 0, 0, 20]; + steps[11] = [0, 0, 0, 0, 0, -20]; + assert_eq!(record(steps, STILL).solve(), Err(Problem::NoResponse(5))); + } + + /// Feeds `reading` for `seconds`, a frame every 20 ms. + fn hold(wizard: &mut Wizard, reading: [i16; 6], seconds: f64) { + for _ in 0..(seconds / 0.02).round() as usize { + wizard.feed(reading, 0.02); + } + } + + fn rest_then(wizard: &mut Wizard) { + for _ in 0..40 { + hold(wizard, STILL[0], 0.02); + hold(wizard, STILL[1], 0.02); + } + } + + #[test] + fn the_wizard_moves_on_by_itself_and_ends_with_the_calibration() { + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + hold(&mut wizard, reading, 0.5); + assert_eq!(wizard.progress(), 1.0); + hold(&mut wizard, STILL[0], 0.1); + } + assert_eq!(wizard.stage(), Stage::Done); + let calibration = wizard.result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed)); + } + + #[test] + fn a_quick_twitch_or_a_hold_without_letting_go_doesnt_finish_a_step() { + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + hold(&mut wizard, PRO[0], 0.2); + hold(&mut wizard, STILL[0], 0.1); + assert_eq!(wizard.stage(), Stage::Step(0)); + hold(&mut wizard, PRO[0], 2.0); + assert_eq!(wizard.stage(), Stage::Step(0)); + // A stalled frame counts as a short one. + let mut stalled = Wizard::default(); + rest_then(&mut stalled); + stalled.feed(PRO[0], 5.0); + assert!(stalled.progress() < 1.0); + } + + #[test] + fn back_records_the_previous_step_again() { + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for reading in &PRO[..2] { + hold(&mut wizard, *reading, 0.5); + hold(&mut wizard, STILL[0], 0.1); + } + assert_eq!(wizard.stage(), Stage::Step(2)); + wizard.back(); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert!(wizard.recording.has_step(0) && !wizard.recording.has_step(1)); + wizard.back(); + wizard.back(); + assert_eq!(wizard.stage(), Stage::Rest); + assert!(wizard.result().is_none()); + } + + #[test] + fn a_device_whose_rotations_go_a_fifth_as_far_as_its_slides_finishes_and_calibrates() { + let weak = |reading: [i16; 6]| -> [i16; 6] { std::array::from_fn(|r| if r < 3 { reading[r] } else { reading[r] / 5 }) }; + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for (index, reading) in PRO.map(weak).into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, STILL[0], 0.1); + } + let calibration = wizard.result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed), "{calibration:?}"); + } + + #[test] + fn two_short_nudges_dont_add_up_to_a_hold() { + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for _ in 0..2 { + hold(&mut wizard, PRO[0], 0.24); + hold(&mut wizard, STILL[0], 0.1); + } + assert_eq!(wizard.stage(), Stage::Step(0)); + assert_eq!(wizard.progress(), 0.0); + assert!(!wizard.recording.has_step(0)); + } + + #[test] + fn a_device_that_goes_ten_times_further_one_way_finishes_and_calibrates() { + // Slide right goes to +500, slide left only to -50; the other axes as the Pro. + let mut steps = PRO; + steps[0][0] = 500; + steps[1][0] = -50; + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for (index, reading) in steps.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, STILL[0], 0.1); + } + let calibration = wizard.result().unwrap().unwrap(); + assert_eq!((calibration.axes[0].source, calibration.axes[0].full), (0, [50, 500])); + assert_eq!(calibration.apply([-50, 0, 0, 0, 0, 0])[0], -FULL_SCALE); + } + + /// Runs the whole wizard: `rest` alternating for the rest stage, then each step held and let + /// go back to `rest[0]`. + fn walk(rest: [[i16; 6]; 2], steps: [[i16; 6]; 12]) -> Wizard { + let mut wizard = Wizard::default(); + for _ in 0..40 { + hold(&mut wizard, rest[0], 0.02); + hold(&mut wizard, rest[1], 0.02); + } + for (index, reading) in steps.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index), "{rest:?}"); + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, rest[0], 0.1); + } + wizard + } + + /// Where a relative-axis device read through spacenavd stops after each release: its last + /// small report, never zero (#2778). Ours, in the range that issue measured. + const STUCK: [[i16; 6]; 13] = [ + [11, -34, -40, -5, -5, 15], + [0, 0, -60, 0, 0, 0], + [-8, 21, 13, 4, -9, -3], + [25, -6, 0, -12, 7, 2], + [-30, 12, 9, 0, 18, -7], + [4, 38, -15, 6, -2, 0], + [0, -17, 33, -20, 1, 9], + [9, 3, -4, 28, -11, 0], + [-2, -9, 6, -3, 24, -12], + [14, 0, -11, 7, -30, 5], + [-6, 10, 2, 0, 3, 31], + [3, -4, 0, 2, -6, -27], + [0, 0, 0, 0, 0, 0], + ]; + + #[test] + fn a_device_that_stops_short_of_rest_after_each_release_finishes_and_doesnt_creep() { + // Nothing arrives at rest, so the reading stays exactly where the last report left it: + // first wherever the cap was last let go, then after each step a different place. + let mut wizard = Wizard::default(); + hold(&mut wizard, STUCK[0], REST_SECONDS + 0.1); + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + // While the cap hasn't been touched, the last step's stuck reading isn't a hold. + hold(&mut wizard, STUCK[index], 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(index), 0.0)); + hold(&mut wizard, reading, 0.5); + hold(&mut wizard, STUCK[index + 1], SETTLE_SECONDS + 0.1); + } + assert_eq!(wizard.stage(), Stage::Done); + let calibration = wizard.result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed), "{calibration:?}"); + for stuck in STUCK { + assert_eq!(calibration.apply(stuck), [0; 6], "{stuck:?} {calibration:?}"); + } + // The cap still reaches full speed, and a push past the stuck range still moves. + assert!(calibration.apply(PRO[0])[0] >= FULL_SCALE - 1, "{calibration:?}"); + assert!(calibration.apply([120, 0, 0, 0, 0, 0])[0] > 0); + } + + #[test] + fn a_steady_hold_that_repeats_one_reading_is_still_a_hold() { + // spacenavd sends only on change, so a cap held still at full deflection repeats one + // reading for far longer than SETTLE_SECONDS; it is held, not let go. + let mut wizard = Wizard::default(); + hold(&mut wizard, STUCK[0], REST_SECONDS + 0.1); + hold(&mut wizard, PRO[0], 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(0), 1.0)); + hold(&mut wizard, STUCK[1], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + } + + /// `reading` and `reading + jitter` in turn, for `seconds`, a frame every 20 ms. + fn jitter(wizard: &mut Wizard, reading: [i16; 6], jitter: [i16; 6], seconds: f64) { + let shaken: [i16; 6] = std::array::from_fn(|r| reading[r] + jitter[r]); + for frame in 0..(seconds / 0.02).round() as usize { + wizard.feed(if frame % 2 == 0 { reading } else { shaken }, 0.02); + } + } + + #[test] + fn a_drifting_device_that_settles_off_centre_after_each_release_finishes_and_doesnt_creep() { + // It keeps reporting, noisily, but after each release settles somewhere off its rest: + // a worn stick, not only spacenavd. The noise stays within its rest wander (`STILL`). + const NOISE: [i16; 6] = [3, -2, 0, 1, 2, 0]; + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + if index > 0 { + // Sitting where the last step settled isn't a hold. + jitter(&mut wizard, STUCK[index], NOISE, 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(index), 0.0)); + } + hold(&mut wizard, reading, 0.5); + jitter(&mut wizard, STUCK[index + 1], NOISE, SETTLE_SECONDS + 0.1); + } + assert_eq!(wizard.stage(), Stage::Done); + let calibration = wizard.result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed), "{calibration:?}"); + for stuck in &STUCK[1..] { + let shaken: [i16; 6] = std::array::from_fn(|r| stuck[r] + NOISE[r]); + assert_eq!((calibration.apply(*stuck), calibration.apply(shaken)), ([0; 6], [0; 6]), "{stuck:?} {calibration:?}"); + } + assert!(calibration.apply(PRO[0])[0] >= FULL_SCALE - 1, "{calibration:?}"); + } + + #[test] + fn both_ends_of_an_odd_width_settled_run_are_untouched_and_one_unit_beyond_is_movement() { + // Silent at rest (no wander) and a 250 push on X: tolerance is max(4, 250 / 50) = 5, odd. + // The release dithers over 10..15, as wide as that, so its middle rounds to 13 and 10 is + // 3 from it, more than half of 5. + let wizard = || { + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [250, 0, 0, 0, 0, 0], 0.5); + cycle(&mut wizard, &[[10, 0, 0, 0, 0, 0], [15, 0, 0, 0, 0, 0]], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + wizard + }; + for (x, touched) in [(10, false), (15, false), (9, true), (16, true)] { + let mut wizard = wizard(); + assert_eq!(wizard.tolerance(0), 5.0); + wizard.feed([x, 0, 0, 0, 0, 0], 0.02); + assert_eq!(wizard.progress() > 0.0, touched, "{x}"); + } + } + + #[test] + fn a_reading_still_moving_close_to_rest_doesnt_end_a_step() { + // Past the peak and close to rest, but moving more than the noise: still on the way back. + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + hold(&mut wizard, PRO[0], 0.5); + jitter(&mut wizard, PRO[0].map(|value| value / 5), [20, 0, 0, 0, 0, 0], 1.0); + assert_eq!(wizard.stage(), Stage::Step(0)); + } + + /// `readings` in turn, from the first, for `seconds`, a frame every 20 ms. + fn cycle(wizard: &mut Wizard, readings: &[[i16; 6]], seconds: f64) { + for frame in 0..(seconds / 0.02).round() as usize { + wizard.feed(readings[frame % readings.len()], 0.02); + } + } + + #[test] + fn an_axis_flat_at_rest_that_dithers_once_off_centre_still_settles() { + // Silent at rest, so no wander was measured, but ±2 around where each release stops. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + let dither = |at: [i16; 6]| [at.map(|value| value - 2), at, at.map(|value| value + 2)]; + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + if index > 0 { + // Dithering where the last step settled doesn't fill this one. + cycle(&mut wizard, &dither(STUCK[index]), 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(index), 0.0)); + } + hold(&mut wizard, reading, 0.5); + cycle(&mut wizard, &dither(STUCK[index + 1]), SETTLE_SECONDS + 0.1); + } + assert_eq!(wizard.stage(), Stage::Done); + let calibration = wizard.result().unwrap().unwrap(); + for at in &STUCK[1..] { + for still in dither(*at) { + assert_eq!(calibration.apply(still), [0; 6], "{still:?} {calibration:?}"); + } + } + } + + #[test] + fn noise_that_starts_at_one_edge_of_its_spread_is_steady_and_settles_at_its_middle() { + // X wanders -3..+3 at rest; after the release it cycles -3, 0, +3 around +40. + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + hold(&mut wizard, PRO[0], 0.5); + cycle(&mut wizard, &[[37, 0, 0, 0, 0, 0], [40, 0, 0, 0, 0, 0], [43, 0, 0, 0, 0, 0]], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert_eq!(wizard.recording.settled[0].mean().map(|mean| mean[0].round()), Some(40.0)); + } + + #[test] + fn the_four_unit_floor_alone_lets_a_two_unit_dither_settle_on_a_short_range() { + // Flat at rest, and the biggest push only reaches 100, so the reach share is 2 and only + // the floor (4, i.e. ±2) lets this ±2 dither count as steady. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + cycle(&mut wizard, &[[8, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [12, 0, 0, 0, 0, 0]], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + } + + #[test] + fn dither_the_steadiness_check_rejects_isnt_skipped_as_untouched_either() { + // Step 0 settles on a ±2 dither around 10. Sitting there is untouched; ±3 around it is wider + // than the steadiness check calls one position, so it is movement and starts a hold. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + cycle(&mut wizard, &[[8, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [12, 0, 0, 0, 0, 0]], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + cycle(&mut wizard, &[[8, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [12, 0, 0, 0, 0, 0]], 0.2); + assert_eq!(wizard.progress(), 0.0); + cycle(&mut wizard, &[[7, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [13, 0, 0, 0, 0, 0]], 0.2); + assert!(wizard.progress() > 0.0); + } + + #[test] + fn a_push_after_a_single_reading_settle_starts_a_hold() { + // One reading back at rest, not a steady run, is all the settle stores; a full push after + // it is still movement. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + wizard.feed([0; 6], 0.02); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert_eq!(wizard.settled.map(|settled| settled.count), Some(1)); + hold(&mut wizard, [-100, 0, 0, 0, 0, 0], 0.2); + assert_eq!((wizard.stage(), wizard.progress() > 0.0), (Stage::Step(1), true)); + } + + #[test] + fn a_narrow_settled_run_skips_a_whole_tolerance_either_side_and_the_band_stays_anchored() { + // Flat at rest and a 100 push: tolerance is exactly 4. The release settles flat at 10, so a + // reading 4 either side (6, 14) is untouched, repeated or not; one more unit is movement. + let wizard = || { + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [10, 0, 0, 0, 0, 0], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert_eq!(wizard.tolerance(0), 4.0); + wizard + }; + let mut edges = wizard(); + cycle(&mut edges, &[[6, 0, 0, 0, 0, 0], [14, 0, 0, 0, 0, 0]], 0.2); + hold(&mut edges, [14, 0, 0, 0, 0, 0], 0.2); + assert_eq!(edges.progress(), 0.0); + // Skipped readings don't widen the band: after all those 14s, 15 is still movement. + edges.feed([15, 0, 0, 0, 0, 0], 0.02); + assert!(edges.progress() > 0.0); + for x in [5, 15] { + let mut wizard = wizard(); + wizard.feed([x, 0, 0, 0, 0, 0], 0.02); + assert!(wizard.progress() > 0.0, "{x}"); + } + } + + #[test] + fn a_step_settles_on_its_own_axis_when_another_with_a_wider_range_stays_out() { + // The step's own axis only goes to 100; another axis stays 30 out after the release, + // more than a quarter of 100, which mustn't hold the step up. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [5, 30, 0, 0, 0, 0], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + } + + #[test] + fn a_step_stays_held_when_the_lesser_axis_is_held_while_the_larger_one_relaxes() { + for held in [[100, 5, 0, 0, 0, 0], [100, 60, 0, 0, 0, 0], [100, 200, 0, 0, 0, 0]] { + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 200, 0, 0, 0, 0], 0.5); + hold(&mut wizard, held, SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(0), "{held:?}"); + } + // A plain hold of a single axis. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(0)); + } + + #[test] + fn a_step_settles_when_cross_talk_moved_another_axis_further_than_its_own() { + // Nula's case: the push moves raw 1 twice as far as raw 0, which may be the one asked + // for. Raw 0 comes back to 5 % and raw 1 stays at 30 %: let go, both steady. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 200, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [5, 60, 0, 0, 0, 0], SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + // Still holding the push, with only the lesser axis back, isn't let go. + let mut holding = Wizard::default(); + hold(&mut holding, [0; 6], REST_SECONDS + 0.1); + hold(&mut holding, [100, 200, 0, 0, 0, 0], 0.5); + hold(&mut holding, [5, 200, 0, 0, 0, 0], 1.0); + assert_eq!(holding.stage(), Stage::Step(0)); + } + + #[test] + fn a_lopsided_dither_that_settled_a_step_isnt_movement_in_the_next() { + // Mostly 10 with an occasional 14: spread 4, so steady, but the mean sits near 11 and the 14 + // is the far edge. Sitting there stays untouched; 15 is wider than the steadiness check allows. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 0, 0, 0, 0, 0], 0.5); + let lopsided = [[10, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0], [14, 0, 0, 0, 0, 0]]; + cycle(&mut wizard, &lopsided, SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + cycle(&mut wizard, &lopsided, 1.0); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(1), 0.0)); + hold(&mut wizard, [16, 0, 0, 0, 0, 0], 0.2); + assert!(wizard.progress() > 0.0); + } + + #[test] + fn cross_talk_that_leaves_the_bigger_axis_well_out_keeps_the_step_open() { + // The documented limit (Grok's case): raw 0 moved less than half as far as raw 1, so it + // never qualifies, and raw 1 at 90 is above a quarter of its 300 peak. + let mut wizard = Wizard::default(); + hold(&mut wizard, [0; 6], REST_SECONDS + 0.1); + hold(&mut wizard, [100, 300, 0, 0, 0, 0], 0.5); + hold(&mut wizard, [5, 90, 0, 0, 0, 0], SETTLE_SECONDS + 1.0); + assert_eq!(wizard.stage(), Stage::Step(0)); + } + + #[test] + fn a_hand_held_still_close_to_rest_after_the_push_counts_as_let_go() { + // The known limit: held exactly still at a fifth of the way out, on any device, ends the + // step there, and that axis's dead zone widens to cover it. + let low = PRO[0].map(|value| value / 5); + let mut wizard = Wizard::default(); + rest_then(&mut wizard); + hold(&mut wizard, PRO[0], 0.5); + hold(&mut wizard, low, SETTLE_SECONDS + 0.1); + assert_eq!(wizard.stage(), Stage::Step(1)); + assert_eq!((wizard.recording.settled[0].min, wizard.recording.settled[0].max), (low, low)); + // Coming back to its true rest afterwards doesn't undo that: the next step is waiting. + hold(&mut wizard, STILL[0], 0.5); + assert_eq!((wizard.stage(), wizard.progress()), (Stage::Step(1), 0.0)); + // No frame of where it settled went into the step as held. + assert_eq!((wizard.recording.steps[0].min[0], wizard.recording.steps[0].max[4]), (PRO[0][0], PRO[0][4])); + } + + #[test] + fn every_reading_of_a_release_that_was_let_go_falls_in_the_dead_zone() { + // Nula's case: X wanders -4..+4 at rest. Half the releases dither over +8..+16, the other + // half over -16..-8. Keeping one reading of each, padded by the wander, can miss the edges. + let wander = [[-4, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0]]; + let x = |value: i16| [value, 0, 0, 0, 0, 0]; + let (above, below) = ([x(16), x(12), x(8)], [x(-8), x(-12), x(-16)]); + let mut wizard = Wizard::default(); + for _ in 0..40 { + hold(&mut wizard, wander[0], 0.02); + hold(&mut wizard, wander[1], 0.02); + } + for (index, reading) in PRO.into_iter().enumerate() { + assert_eq!(wizard.stage(), Stage::Step(index)); + hold(&mut wizard, reading, 0.5); + cycle(&mut wizard, if index % 2 == 0 { &above } else { &below }, SETTLE_SECONDS + 0.1); + } + let calibration = wizard.result().unwrap().unwrap(); + for still in above.iter().chain(&below).chain(&wander) { + assert_eq!(calibration.apply(*still), [0; 6], "{still:?} {calibration:?}"); + } + } + + #[test] + fn two_steps_in_a_row_that_stop_at_the_same_place_both_finish() { + let mut wizard = Wizard::default(); + hold(&mut wizard, STUCK[0], REST_SECONDS + 0.1); + for reading in &PRO[..2] { + hold(&mut wizard, *reading, 0.5); + hold(&mut wizard, STUCK[1], SETTLE_SECONDS + 0.1); + } + assert_eq!(wizard.stage(), Stage::Step(2)); + } + + #[test] + fn recentring_on_where_the_cap_settled_keeps_the_whole_rest_wander_inside_the_dead_zone() { + // X wanders -4..+4 at rest, and every release settles at +12. + let wander = [[-4, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0]]; + let mut recording = record(PRO, wander); + for index in 0..12 { + recording.settled(index, [12, 0, 0, 0, 0, 0]); + } + let calibration = recording.solve().unwrap(); + for still in [wander[0], wander[1], [12, 0, 0, 0, 0, 0]] { + assert_eq!(calibration.apply(still), [0; 6], "{still:?} {calibration:?}"); + } + } + + #[test] + fn the_dead_zone_shares_are_where_apply_starts_moving() { + // A lopsided, reversed axis with the user's dead zone on top. + let mut calibration = walk(STILL, PRO).result().unwrap().unwrap(); + calibration.axes[0] = AxisCalibration { source: 0, reversed: true, rest: 10, dead_zone: 20, full: [100, 400] }; + calibration.dead_zone_share = 0.1; + let [negative, positive] = calibration.dead_zone_shares()[0]; + // Canonical negative is raw above rest here: 400 of travel, 20 measured. + assert!((negative - (0.05 + 0.95 * 0.1)).abs() < 1e-6 && (positive - (0.2 + 0.8 * 0.1)).abs() < 1e-6); + let at = |raw: i16| [raw, 0, 0, 0, 0, 0]; + let inside = |share: f32, full: f32| (share * full).floor() as i16 - 1; + assert_eq!(calibration.apply(at(10 + inside(negative, 400.0)))[0], 0); + assert!(calibration.apply(at(10 + inside(negative, 400.0) + 3))[0] < 0); + assert_eq!(calibration.apply(at(10 - inside(positive, 100.0)))[0], 0); + assert!(calibration.apply(at(10 - inside(positive, 100.0) - 3))[0] > 0); + // Full deflection is ±1 of travel, the reversed way round. + assert_eq!(calibration.travel(at(410))[0], -1.0); + assert_eq!(calibration.travel(at(-90))[0], 1.0); + } + + #[test] + fn a_device_that_comes_back_to_rest_keeps_its_measured_rest_and_dead_zone() { + let mut settled = record(PRO, STILL); + let plain = settled.solve().unwrap(); + for index in 0..12 { + settled.settled(index, STILL[index % 2]); + } + assert_eq!(settled.solve().unwrap(), plain); + } + + #[test] + fn a_noisy_axis_at_rest_holds_up_neither_itself_nor_a_quiet_one() { + // X wanders ±4 at rest, and goes +500 one way but only -50 the other: the solver accepts + // that, so the wizard has to be able to record it. + let mut steps = PRO; + steps[0][0] = 500; + steps[1][0] = -50; + let noisy_x = [[-4, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0]]; + let calibration = walk(noisy_x, steps).result().unwrap().unwrap(); + assert_eq!((calibration.axes[0].source, calibration.axes[0].dead_zone, calibration.axes[0].full), (0, 4, [50, 500])); + // Rz wanders ±40 at rest: every other axis still records against its own quiet rest. + let noisy_rz = [[0, 0, 0, 0, 0, -40], [0, 0, 0, 0, 0, 40]]; + let calibration = walk(noisy_rz, PRO).result().unwrap().unwrap(); + assert!(calibration.axes.iter().enumerate().all(|(c, axis)| axis.source == c && !axis.reversed), "{calibration:?}"); + } + + #[test] + fn a_step_that_caught_a_resting_hand_instead_of_a_push_is_named() { + // A quiet device (nothing at rest), and slide right recorded only a hand resting on the + // cap: scaled up, a few units would be full speed. + let mut steps = PRO; + steps[0] = [6, 4, 0, 0, 3, 0]; + assert_eq!(record(steps, [[0; 6]; 2]).solve(), Err(Problem::NoResponse(0))); + } + + #[test] + fn a_hand_edited_calibration_that_could_spin_the_view_isnt_usable() { + let solved = record(PRO, STILL).solve().unwrap(); + assert!(solved.is_usable()); + let mut bad = solved; + bad.axes[2].source = 6; + assert!(!bad.is_usable(), "a source the device doesn't have"); + let mut bad = solved; + bad.axes[2].full[0] = bad.axes[2].dead_zone; + assert!(!bad.is_usable(), "any touch past the dead zone would be full speed"); + let mut bad = solved; + bad.axes[2].source = bad.axes[3].source; + assert!(!bad.is_usable(), "two canonical axes from one raw axis"); + } + + #[test] + fn readings_for_a_step_that_doesnt_exist_are_ignored() { + let mut recording = record(PRO, STILL); + recording.step(12, [i16::MAX; 6]); + assert_eq!(recording.solve(), record(PRO, STILL).solve()); + } +} diff --git a/crates/space-mouse/src/lib.rs b/crates/space-mouse/src/lib.rs index 6ab8099db..6a2af5f2e 100644 --- a/crates/space-mouse/src/lib.rs +++ b/crates/space-mouse/src/lib.rs @@ -10,6 +10,10 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +mod calibration; mod descriptor; +pub use calibration::{ + AxisCalibration, Calibration, HOLD_SECONDS, MAX_DEAD_ZONE_SHARE, MIN_SHARE, Problem, REST_SECONDS, Recording, STEPS, Stage, Step, Wizard, +}; pub use descriptor::{Descriptor, FULL_SCALE, Field, Layout, MAX_BUTTONS, Report}; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 70e1c9749..d1bf0fc4b 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -13,6 +13,7 @@ solidcraft-engine = { workspace = true } egui = { workspace = true } egui-wgpu = { workspace = true } solidcraft-gpu = { workspace = true } +solidcraft-space-mouse = { workspace = true, features = ["serde"] } serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b5d2d4f00..89483780d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -178,6 +178,7 @@ pub mod smart_extrude; #[cfg(test)] mod smart_extrude_ui_tests; pub mod space_mouse; +pub mod space_mouse_calibration; pub mod stand_up; #[cfg(test)] mod sweep_dialog_tests; @@ -415,6 +416,8 @@ pub struct SolveApp { pub flat_view: dialogs_sheet::FlatView, /// The start page. pub home: home::HomeState, + /// The 3D mouse: which device, its reading, and the calibration window. + pub space_mouse: space_mouse::Input, pub file_load: file_load::FileLoad, /// The other open designs (tabs). pub docs: documents::Documents, @@ -507,6 +510,7 @@ impl SolveApp { pending_fit: None, flat_view: Default::default(), home: home::HomeState::default(), + space_mouse: Default::default(), file_load: file_load::FileLoad::default(), docs: documents::Documents::default(), applied_fonts_language: "en".into(), diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 47963d692..661fd5ebd 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -284,6 +284,10 @@ pub struct Prefs { pub space_mouse_reverse: [bool; 6], /// Per physical axis of the cap, a multiplier on top of `space_mouse_speed`; 0 switches it off. pub space_mouse_axis_speed: [f32; 6], + /// Per 3D mouse (`space_mouse::Input::device`), the calibration that puts its axes on + /// 3Dconnexion's. A device without one is read as it reports. + #[serde(deserialize_with = "calibrations_that_read")] + pub space_mouse_calibrations: std::collections::BTreeMap, /// Anti-aliasing samples (applies on restart). pub msaa: u32, /// Soft contact shading in the GPU viewport; optional and applied immediately. @@ -446,6 +450,7 @@ impl Default for Prefs { space_mouse_speed: 1.0, space_mouse_reverse: [false; 6], space_mouse_axis_speed: [1.0; 6], + space_mouse_calibrations: Default::default(), msaa: 4, ambient_occlusion: false, grid_follows_view: false, @@ -763,6 +768,7 @@ fn defaults(app: &mut SolveApp, page: usize) { p.space_mouse_speed = d.space_mouse_speed; p.space_mouse_reverse = d.space_mouse_reverse; p.space_mouse_axis_speed = d.space_mouse_axis_speed; + // The 3D mice the user calibrated stay: a calibration describes the device. p.look_at_anim = d.look_at_anim; p.look_at_speed = d.look_at_speed; p.middle_double_click = d.middle_double_click; @@ -1079,6 +1085,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } if !app.prefs_window.open { app.prefs_window.snapshot = None; + // Calibration opens from here and ends with it, so the cap moves the view again. + app.space_mouse.calibrating = None; return; } if app.prefs_window.snapshot.is_none() { @@ -1147,6 +1155,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { if let Some(w) = &shown { crate::scenario::publish_rect("prefs:window", w.response.rect); } + crate::space_mouse_calibration::show(app, ctx); if app.preferences.msaa != before.msaa { save_graphics(app); } @@ -1395,6 +1404,42 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { }); ui.end_row(); } + ui.label(app.tr("ui.space_mouse_calibration")); + ui.horizontal(|ui| { + let device = app.space_mouse.device.clone(); + let saved = device.as_ref().is_some_and(|device| app.preferences.space_mouse_calibrations.contains_key(device)); + ui.add_enabled_ui(app.preferences.space_mouse_enabled && device.is_some(), |ui| { + if ui.button(app.tr("ui.space_mouse_calibrate")).on_hover_text(app.tr("ui.space_mouse_calibrate_tip")).clicked() { + crate::space_mouse_calibration::start(app); + } + if saved && ui.button(app.tr("ui.space_mouse_forget")).clicked() + && let Some(device) = &device + { + app.preferences.space_mouse_calibrations.remove(device); + } + }); + // With the device it's about, so it's clear which calibration is in use. + ui.label(match (&device, saved) { + (None, _) => app.tr("ui.space_mouse_none").to_owned(), + (Some(device), true) => format!("{} ({device})", app.tr("ui.space_mouse_calibrated")), + (Some(device), false) => format!("{} ({device})", app.tr("ui.space_mouse_not_calibrated")), + }); + }); + ui.end_row(); + // The calibrated device's dead zone, adjustable after calibrating. + let enabled = app.preferences.space_mouse_enabled; + let (label, tip) = (app.tr("ui.space_mouse_dead_zone").to_owned(), app.tr("ui.space_mouse_dead_zone_tip").to_owned()); + let (device, raw) = (app.space_mouse.device.clone(), app.space_mouse.raw.into()); + if let Some(calibration) = device.and_then(|device| app.preferences.space_mouse_calibrations.get_mut(&device)) { + ui.label(label); + ui.add_enabled_ui(enabled, |ui| { + crate::space_mouse_calibration::dead_zone_slider(ui, &mut calibration.dead_zone_share).on_hover_text(tip); + }); + ui.end_row(); + ui.label(""); + crate::space_mouse_calibration::dead_zone_pads(ui, calibration, raw); + ui.end_row(); + } note(ui, crate::i18n::tr_label("Move and rotate the view together; sketches use pan and zoom only.")); } PAGE_DESIGN => { @@ -1704,6 +1749,24 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result>( + saved: D, +) -> Result, D::Error> { + let saved = std::collections::BTreeMap::::deserialize(saved)?; + Ok(saved + .into_iter() + .filter_map(|(device, calibration)| match serde_json::from_value(calibration) { + Ok(calibration) => Some((device, calibration)), + Err(error) => { + log::warn!("preferences: the 3D mouse calibration for `{device}` can't be read ({error}); reading the device as it reports"); + None + } + }) + .collect()) +} + /// Every theme the Theme list offers, as (id, name): the modes, the built-in theme files, then /// the imported ones. fn theme_choices(app: &SolveApp) -> Vec<(String, String)> { @@ -1756,16 +1819,26 @@ fn current_theme_file(app: &SolveApp) -> serde_json::Value { } } -/// Fold a setting an older release kept in its own field into the one this version reads. -/// `orbit_cursor` (`true` = the point under the cursor) became `orbit_around`. /// The cap's physical axes, in the order of `Prefs::space_mouse_reverse`. -const SPACE_MOUSE_AXES: [&str; 6] = ["Push left / right", "Push forward / back", "Lift / press", "Tilt forward / back", "Tilt left / right", "Twist"]; +pub(crate) const SPACE_MOUSE_AXES: [&str; 6] = + ["Push left / right", "Push forward / back", "Lift / press", "Tilt forward / back", "Tilt left / right", "Twist"]; +/// Fold a setting an older release kept in its own field into the one this version reads. +/// `orbit_cursor` (`true` = the point under the cursor) became `orbit_around`. A 3D mouse +/// calibration that can't be used as it is (a hand edit) is dropped, so the device is read as it +/// reports rather than spinning the view. pub fn migrate(mut p: Prefs) -> Prefs { if p.orbit_cursor { p.orbit_around = OrbitAround::Cursor; p.orbit_cursor = false; } + p.space_mouse_calibrations.retain(|device, calibration| { + let usable = calibration.is_usable(); + if !usable { + log::warn!("preferences: the 3D mouse calibration for `{device}` can't be used as it is; reading the device as it reports"); + } + usable + }); p } diff --git a/crates/ui-egui/src/space_mouse.rs b/crates/ui-egui/src/space_mouse.rs index f6663b369..fbd61fc48 100644 --- a/crates/ui-egui/src/space_mouse.rs +++ b/crates/ui-egui/src/space_mouse.rs @@ -8,6 +8,8 @@ use std::time::Duration; use crate::SolveApp; +pub use solidcraft_space_mouse::{AxisCalibration, Calibration}; + /// What a 3Dconnexion device reports at full deflection, in raw units, on every axis. pub const FULL_SCALE: i16 = 350; @@ -26,6 +28,31 @@ impl Axes { } } +impl From for [i16; 6] { + fn from(axes: Axes) -> Self { + let ([x, y, z], [rx, ry, rz]) = (axes.translation, axes.rotation); + [x, y, z, rx, ry, rz] + } +} + +impl From<[i16; 6]> for Axes { + fn from([x, y, z, rx, ry, rz]: [i16; 6]) -> Self { + Self { translation: [x, y, z], rotation: [rx, ry, rz] } + } +} + +/// The 3D mouse as of this frame. +#[derive(Debug, Default)] +pub struct Input { + /// The device being read: where from and its vendor and product ids (`hid 256f:c63a`, + /// `web 256f:c63a`), or where from alone (`spacenavd`). Its calibration is saved under it. + pub device: Option, + /// This frame's reading, before calibration. + pub raw: Axes, + /// The guided calibration while its window is open, and the device it is for. + pub calibrating: Option<(String, solidcraft_space_mouse::Wizard)>, +} + /// Seconds after the cap last moved that wheel events are still taken for 3DxWare's: one can be /// queued just before the cap stops and only reach the next frame. pub const WHEEL_QUIET_S: f64 = 0.15; @@ -134,13 +161,39 @@ pub struct DeviceMotion { pub seconds: f64, } +/// The saved calibration of the device being read, when it has one. +pub fn calibration(app: &SolveApp) -> Option { + app.space_mouse.device.as_ref().and_then(|device| app.preferences.space_mouse_calibrations.get(device)).copied() +} + +/// A reading on 3Dconnexion's axes: through `calibration` when there is one. Whether the cap is +/// moving is asked of this, never of the raw reading, so a device resting off zero isn't "moving" +/// and a short-range one moves as soon as it does. +pub fn calibrated(axes: Axes, calibration: Option) -> Axes { + calibration.map_or(axes, |calibration| calibration.apply(axes.into()).into()) +} + /// Hands one frame of 3D mouse input, `seconds` after the previous frame, to the page showing /// the camera. Nothing happens with navigation switched off, on the start page or while a file -/// picker is open. Returns whether there was motion to hand over; it then asks for the next frame -/// itself. +/// picker is open, or while the reading is inside the dead zone (after calibration, which takes +/// off the device's own rest offset), so a cap resting just off zero doesn't keep redrawing. +/// Returns whether there was motion to hand over; it then asks for the next frame itself. The +/// reading goes through the device's saved calibration first, when it has one; while the +/// calibration window is open, the reading goes to it instead and the view stays put. pub fn navigate_frame(app: &mut SolveApp, ctx: &egui::Context, mapping: DriverMapping, axes: Axes, seconds: f64) -> bool { + app.space_mouse.raw = axes; + if let Some((device, wizard)) = &mut app.space_mouse.calibrating { + if app.space_mouse.device.as_ref() == Some(device) { + wizard.feed(axes.into(), seconds); + ctx.request_repaint_after(Duration::from_millis(16)); + return false; + } + // Another device is being read now, or none: what was recorded isn't its. + app.space_mouse.calibrating = None; + } + let axes = calibrated(axes, calibration(app)); // Only the window with focus: with two windows open, the cap moves the one being used, not both. - if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || axes == Axes::default() || !ctx.input(|i| i.focused) { + if !app.preferences.space_mouse_enabled || app.home.open || app.file_picker_busy() || !axes.moving() || !ctx.input(|i| i.focused) { return false; } let speed = f64::from(app.preferences.space_mouse_speed); @@ -467,4 +520,112 @@ mod tests { guard.filter(false, f64::NAN, &mut events); assert_eq!(events.len(), 1); } + + /// A homemade device that sends push forward/back as its fifth axis, the other way round, at + /// ten times 3Dconnexion's range. + fn homemade() -> solidcraft_space_mouse::Calibration { + let axis = |source, reversed| solidcraft_space_mouse::AxisCalibration { source, reversed, rest: 0, dead_zone: 0, full: [3500; 2] }; + solidcraft_space_mouse::Calibration { + dead_zone_share: 0.0, + axes: [axis(0, false), axis(4, true), axis(2, false), axis(3, false), axis(1, false), axis(5, false)], + } + } + + #[test] + fn a_devices_saved_calibration_puts_its_axes_on_3dconnexions() { + let ctx = window(true); + let mut reference = app(); + frame(&mut reference, &ctx, DriverMapping::default(), PUSH, 0.02); + let sent = Axes { translation: [0; 3], rotation: [0, -3500, 0] }; + let mut calibrated = app(); + calibrated.space_mouse.device = Some("hid 1234:5678".into()); + calibrated.preferences.space_mouse_calibrations.insert("hid 1234:5678".into(), homemade()); + assert!(frame(&mut calibrated, &ctx, DriverMapping::default(), sent, 0.02)); + assert_eq!(calibrated.cam, reference.cam); + // Another device's calibration isn't applied: the reading turns the view as it comes. + let mut other = app(); + other.space_mouse.device = Some("hid 256f:c63a".into()); + other.preferences.space_mouse_calibrations.insert("hid 1234:5678".into(), homemade()); + frame(&mut other, &ctx, DriverMapping::default(), sent, 0.02); + assert_ne!(other.cam, reference.cam); + } + + #[test] + fn while_calibrating_the_cap_feeds_the_calibration_and_the_view_stays() { + let ctx = window(true); + let mut app = app(); + crate::space_mouse_calibration::start(&mut app); + assert!(app.space_mouse.calibrating.is_none(), "nothing to calibrate without a device"); + app.space_mouse.device = Some("hid 256f:c63a".into()); + crate::space_mouse_calibration::start(&mut app); + let before = app.cam; + assert!(!frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02)); + assert_eq!(app.cam, before); + assert_eq!(app.space_mouse.raw, PUSH); + assert!(app.space_mouse.calibrating.as_ref().is_some_and(|(_, wizard)| wizard.progress() > 0.0)); + // Closing Preferences ends it, so the cap moves the view again. + app.prefs_window.open = false; + crate::prefs::show(&mut app, &ctx); + assert!(app.space_mouse.calibrating.is_none()); + assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02)); + } + + #[test] + fn a_reading_resting_off_zero_is_kept_for_calibration_and_doesnt_move_the_view() { + let ctx = window(true); + // Inside the dead zone and not calibrated: no motion, so no redraw either. + let mut app = app(); + let resting = Axes { translation: [0, 15, 0], rotation: [0; 3] }; + let before = app.cam; + assert!(!frame(&mut app, &ctx, DriverMapping::default(), resting, 0.02)); + assert_eq!(app.cam, before); + // The calibration window gets it as it is, to measure where the cap rests. + app.space_mouse.device = Some("web 1234:5678".into()); + crate::space_mouse_calibration::start(&mut app); + frame(&mut app, &ctx, DriverMapping::default(), resting, 0.02); + assert_eq!(app.space_mouse.raw, resting); + app.space_mouse.calibrating = None; + // A device resting far off zero, calibrated: still at rest, moving when pushed. + let mut offset = homemade(); + for axis in &mut offset.axes { + axis.rest = 1000; + } + app.preferences.space_mouse_calibrations.insert("web 1234:5678".into(), offset); + let at_rest = Axes { translation: [1000; 3], rotation: [1000; 3] }; + assert!(!frame(&mut app, &ctx, DriverMapping::default(), at_rest, 0.02)); + assert_eq!(app.cam, before); + assert!(frame(&mut app, &ctx, DriverMapping::default(), Axes { rotation: [1000, 1000 - 3500, 1000], ..at_rest }, 0.02)); + } + + #[test] + fn another_device_turning_up_mid_calibration_ends_it() { + let ctx = window(true); + let mut app = app(); + app.space_mouse.device = Some("hid 256f:c63a".into()); + crate::space_mouse_calibration::start(&mut app); + frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02); + app.space_mouse.device = Some("spacenavd".into()); + assert!(frame(&mut app, &ctx, DriverMapping::default(), PUSH, 0.02), "the new device moves the view"); + assert!(app.space_mouse.calibrating.is_none()); + assert!(app.preferences.space_mouse_calibrations.is_empty()); + } + + #[test] + fn calibrations_are_saved_with_the_preferences() { + let mut prefs = crate::prefs::Prefs::default(); + prefs.space_mouse_calibrations.insert("hid 1234:5678".into(), homemade()); + let mut saved = serde_json::to_value(&prefs).unwrap(); + assert_eq!(crate::prefs::lenient(&saved), prefs); + // One that can't be read, or that could spin the view, is dropped on its own. + let mut spinning = homemade(); + spinning.axes[0].full = [0; 2]; + saved["space_mouse_calibrations"]["spacenavd"] = serde_json::to_value(spinning).unwrap(); + saved["space_mouse_calibrations"]["web 046d:c62b"] = serde_json::json!({ "axes": "garbled" }); + assert_eq!(crate::prefs::lenient(&saved), prefs); + // One saved before the dead zone setting existed reads with none. + let mut older = serde_json::to_value(homemade()).unwrap(); + older.as_object_mut().unwrap().remove("dead_zone_share"); + saved["space_mouse_calibrations"]["hid 1234:5678"] = older; + assert_eq!(crate::prefs::lenient(&saved), prefs); + } } diff --git a/crates/ui-egui/src/space_mouse_calibration.rs b/crates/ui-egui/src/space_mouse_calibration.rs new file mode 100644 index 000000000..078b0621e --- /dev/null +++ b/crates/ui-egui/src/space_mouse_calibration.rs @@ -0,0 +1,157 @@ +//! The 3D mouse calibration window, opened from Preferences › Navigation. It asks the user to +//! leave the cap still, then to move it along each axis both ways, moving on by itself after each +//! (`solidcraft_space_mouse::Wizard`), and saves what it found for the device it started with. +//! The window closes with Preferences, and when another device (or none) is read instead. + +use solidcraft_space_mouse::{Calibration, Problem, Stage, Wizard}; + +use crate::SolveApp; + +/// What each of `solidcraft_space_mouse::STEPS` asks for, in order. +const STEP_PROMPTS: [&str; 12] = [ + "ui.space_mouse_step_slide_right", + "ui.space_mouse_step_slide_left", + "ui.space_mouse_step_pull", + "ui.space_mouse_step_push", + "ui.space_mouse_step_press", + "ui.space_mouse_step_lift", + "ui.space_mouse_step_tilt_back", + "ui.space_mouse_step_tilt_forward", + "ui.space_mouse_step_tilt_left", + "ui.space_mouse_step_tilt_right", + "ui.space_mouse_step_twist_clockwise", + "ui.space_mouse_step_twist_counterclockwise", +]; + +/// The dead zone, as a share of full travel, shown as a percentage. +pub(crate) fn dead_zone_slider(ui: &mut egui::Ui, share: &mut f32) -> egui::Response { + ui.add( + egui::Slider::new(share, 0.0..=solidcraft_space_mouse::MAX_DEAD_ZONE_SHARE) + .step_by(0.01) + .custom_formatter(|v, _| format!("{:.0} %", v * 100.0)), + ) +} + +/// The calibration's dead zones the way a game controller tester shows a stick: per pair of axes, +/// a circle for the full travel, the dead zone shaded inside it (each direction its own size), and +/// a dot where the cap is now, before the dead zone, so it's plain when the view starts to move. +pub(crate) fn dead_zone_pads(ui: &mut egui::Ui, calibration: &Calibration, raw: [i16; 6]) { + const NAMES: [&str; 6] = ["X", "Y", "Z", "Rx", "Ry", "Rz"]; + // (horizontal axis, its positive way on screen, vertical axis, its positive way down), so the + // dot moves as the cap does: slid right and pulled toward you, twisted and pressed, tilted. + const PADS: [(usize, f32, usize, f32); 3] = [(0, 1.0, 1, 1.0), (5, 1.0, 2, 1.0), (4, -1.0, 3, -1.0)]; + const SIZE: f32 = 76.0; + let (shares, travel, moving) = (calibration.dead_zone_shares(), calibration.travel(raw), calibration.apply(raw)); + let visuals = ui.visuals().clone(); + ui.horizontal(|ui| { + for (h, h_way, v, v_way) in PADS { + ui.vertical(|ui| { + let (rect, response) = ui.allocate_exact_size(egui::vec2(SIZE, SIZE), egui::Sense::hover()); + let painter = ui.painter_at(rect); + let (centre, radius) = (rect.center(), SIZE / 2.0 - 2.0); + let faint = visuals.weak_text_color(); + // Which side of an axis's dead zone lies along a way on screen. + let side = |axis: usize, way: f32, screen: f32| shares[axis][usize::from(way * screen > 0.0)]; + let zone: Vec = (0..64) + .map(|i| { + let (sin, cos) = (i as f32 / 64.0 * std::f32::consts::TAU).sin_cos(); + let (x, y) = (side(h, h_way, cos) * cos, side(v, v_way, sin) * sin); + centre + egui::vec2(x, y) * radius + }) + .collect(); + painter.add(egui::Shape::convex_polygon(zone, visuals.selection.bg_fill.gamma_multiply(0.35), egui::Stroke::NONE)); + painter.line_segment( + [centre - egui::vec2(radius, 0.0), centre + egui::vec2(radius, 0.0)], + egui::Stroke::new(1.0, faint.gamma_multiply(0.4)), + ); + painter.line_segment( + [centre - egui::vec2(0.0, radius), centre + egui::vec2(0.0, radius)], + egui::Stroke::new(1.0, faint.gamma_multiply(0.4)), + ); + painter.circle_stroke(centre, radius, egui::Stroke::new(1.0, faint)); + let dot = egui::vec2(h_way * travel[h], v_way * travel[v]); + let dot = if dot.length() > 1.0 { dot.normalized() } else { dot }; + let live = moving[h] != 0 || moving[v] != 0; + painter.circle_filled(centre + dot * radius, 3.5, if live { visuals.selection.stroke.color } else { faint }); + let percent = |axis: usize| format!("{} −{:.0} % +{:.0} %", NAMES[axis], shares[axis][0] * 100.0, shares[axis][1] * 100.0); + response.on_hover_text(format!("{}\n{}", percent(h), percent(v))); + ui.label(egui::RichText::new(format!("{} · {}", NAMES[h], NAMES[v])).small().color(faint)); + }); + } + }); +} + +/// Starts calibrating the device being read, if there is one. +pub fn start(app: &mut SolveApp) { + app.space_mouse.calibrating = app.space_mouse.device.clone().map(|device| (device, Wizard::default())); +} + +pub fn show(app: &mut SolveApp, ctx: &egui::Context) { + let Some((_, wizard)) = &app.space_mouse.calibrating else { return }; + let (stage, progress, result) = (wizard.stage(), wizard.progress(), wizard.result()); + let mut dead_zone = wizard.dead_zone_share(); + let raw: [i16; 6] = app.space_mouse.raw.into(); + let prompt = match (stage, result) { + (Stage::Rest, _) => "ui.space_mouse_step_rest", + (Stage::Step(index), _) => STEP_PROMPTS.get(index).copied().unwrap_or_default(), + (Stage::Done, Some(Ok(_))) => "ui.space_mouse_calibration_done", + (Stage::Done, _) => "ui.space_mouse_calibration_no_response", + }; + // The axis that barely moved, as Preferences names it. + let weak = match result { + Some(Err(Problem::NoResponse(axis))) => crate::prefs::SPACE_MOUSE_AXES.get(axis).copied(), + _ => None, + }; + let counter = match stage { + Stage::Rest => String::new(), + Stage::Step(index) => format!("{} / {}", index + 1, STEP_PROMPTS.len()), + Stage::Done => format!("{0} / {0}", STEP_PROMPTS.len()), + }; + let (mut back, mut over, mut cancel, mut save) = (false, false, false, false); + crate::frame::window(ctx, app.tr("ui.space_mouse_calibrate_title"), crate::frame::Width::Normal) + .id(egui::Id::new("sc_space_mouse_calibration")) + .collapsible(false) + .resizable(false) + .show(ctx, |ui| { + ui.label(app.tr(prompt)); + if let Some(axis) = weak { + ui.label(egui::RichText::new(app.tr_label(axis)).strong()); + } + ui.add_space(6.0); + ui.add(egui::ProgressBar::new(progress as f32).text(counter)); + if let Some(Ok(calibration)) = result { + ui.add_space(6.0); + dead_zone_pads(ui, &Calibration { dead_zone_share: dead_zone, ..calibration }, raw); + } + // The device's six raw axes as they come, so the jitter at rest is there to see. + let reading = raw.map(|value| format!("{value:>6}")).join(" "); + ui.label(egui::RichText::new(format!("{}: {reading}", app.tr("ui.space_mouse_reading"))).monospace()); + ui.horizontal(|ui| { + ui.label(app.tr("ui.space_mouse_dead_zone")); + dead_zone_slider(ui, &mut dead_zone).on_hover_text(app.tr("ui.space_mouse_dead_zone_tip")); + }); + ui.add_space(6.0); + ui.horizontal(|ui| { + back = ui.add_enabled(stage != Stage::Rest, egui::Button::new(app.tr("ui.back"))).clicked(); + over = matches!(result, Some(Err(_))) && ui.button(app.tr("ui.start_over")).clicked(); + cancel = ui.button(app.tr("ui.cancel")).clicked(); + save = matches!(result, Some(Ok(_))) && ui.button(app.tr("ui.save")).clicked(); + }); + }); + if cancel { + app.space_mouse.calibrating = None; + } else if let Some((device, wizard)) = &mut app.space_mouse.calibrating { + wizard.set_dead_zone_share(dead_zone); + let result = wizard.result(); + if save && let Some(Ok(calibration)) = result { + app.preferences.space_mouse_calibrations.insert(std::mem::take(device), calibration); + app.space_mouse.calibrating = None; + } else if over { + // A new recording; the dead zone set so far stays. + *wizard = Wizard::default(); + wizard.set_dead_zone_share(dead_zone); + } else if back { + wizard.back(); + } + } +}