diff --git a/README.md b/README.md index b09eccb..e4c7d47 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Features: - Touch input (multi-touch gestures, tapping and moving) - Configurable palm rejection (disables touch input for a configurable grace period if any pen input is detected, default 500ms) - Screen orientation support (portrait, landscape-right, landscape-left, inverted) +- Optional tilt correction: cancels the small offset between the hover cursor and where the pen actually draws, caused by holding the pen at an angle - Input grab (enabled by default): A small helper binary is uploaded to `/tmp` on the tablet and uses `EVIOCGRAB` to exclusively grab the input devices. The tablet UI (xochitl) keeps running but receives no pen/touch events. The grab is automatically released when rm-pad exits or the SSH connection drops — no reboot or manual cleanup needed. Use `--no-grab-input` to disable. - Works over both wifi and USB - Very low latency (as long as your connection to the tablet is fast) @@ -124,6 +125,8 @@ You can also use environment variables: - **no_palm_rejection**: Disable palm rejection - **palm_grace_ms**: Palm rejection grace period in milliseconds (default: 500) - **orientation**: Screen orientation - `portrait`, `landscape-right` (default), `landscape-left`, or `inverted` +- **tilt_correction**: Cancel the tilt-induced hover-vs-contact pen offset - `off` (default), `tilt`, or `tilt-distance` (ramps the correction off as the pen lifts away) +- **tilt_correction_gain**: Correction strength, i.e. the effective coil-to-nib lever length in pen digitizer units (default: `1.0`, off). Tune empirically; use a negative value to flip direction All options can also be set via command-line flags. Run `rm-pad --help` for details. diff --git a/rm-pad.toml.example b/rm-pad.toml.example index 4dd0c1d..f20659a 100644 --- a/rm-pad.toml.example +++ b/rm-pad.toml.example @@ -10,3 +10,5 @@ host = "10.11.99.1" # no_palm_rejection = false # palm_grace_ms = 500 # orientation = "landscape-right" +# tilt_correction = "off" # "off", "tilt", or "tilt-distance" +# tilt_correction_gain = 1.0 # effective lever length in pen digitizer units (negative flips direction) diff --git a/src/config/cli.rs b/src/config/cli.rs index 2ba4bea..3b53655 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -2,6 +2,7 @@ use clap::{Parser, Subcommand}; use std::path::PathBuf; use crate::orientation::Orientation; +use crate::tilt::TiltCorrectionMode; #[derive(Parser)] #[command(name = "rm-pad")] @@ -59,6 +60,14 @@ pub struct Cli { #[arg(long, value_parser = clap::value_parser!(Orientation))] pub orientation: Option, + /// Pen tilt-offset correction (off, tilt, tilt-distance) + #[arg(long, value_parser = clap::value_parser!(TiltCorrectionMode))] + pub tilt_correction: Option, + + /// Tilt-correction strength: effective lever length in pen digitizer units + #[arg(long)] + pub tilt_correction_gain: Option, + /// Path to config file #[arg(long, env = "RMPAD_CONFIG")] pub config: Option, diff --git a/src/config/file.rs b/src/config/file.rs index af6f6f0..92c8af0 100644 --- a/src/config/file.rs +++ b/src/config/file.rs @@ -2,6 +2,7 @@ use serde::Deserialize; use std::path::{Path, PathBuf}; use crate::orientation::Orientation; +use crate::tilt::TiltCorrectionMode; const DEFAULT_HOST: &str = "10.11.99.1"; @@ -25,6 +26,9 @@ pub struct FileConfig { pub palm_grace_ms: Option, #[serde(default)] pub orientation: Orientation, + #[serde(default)] + pub tilt_correction: TiltCorrectionMode, + pub tilt_correction_gain: Option, } impl Default for FileConfig { @@ -41,6 +45,8 @@ impl Default for FileConfig { no_palm_rejection: false, palm_grace_ms: None, orientation: Orientation::default(), + tilt_correction: TiltCorrectionMode::default(), + tilt_correction_gain: None, } } } diff --git a/src/config/mod.rs b/src/config/mod.rs index 158b314..239dfe4 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -7,6 +7,7 @@ use std::path::PathBuf; use crate::device::DeviceProfile; use crate::orientation::Orientation; +use crate::tilt::TiltCorrectionMode; /// Authentication method for SSH connection. #[derive(Clone)] @@ -29,6 +30,8 @@ pub struct Config { pub no_palm_rejection: bool, pub palm_grace_ms: u64, pub orientation: Orientation, + pub tilt_correction: TiltCorrectionMode, + pub tilt_correction_gain: f64, } impl Config { @@ -66,6 +69,11 @@ impl Config { .or(file_config.palm_grace_ms) .unwrap_or(500), orientation: cli.orientation.unwrap_or(file_config.orientation), + tilt_correction: cli.tilt_correction.unwrap_or(file_config.tilt_correction), + tilt_correction_gain: cli + .tilt_correction_gain + .or(file_config.tilt_correction_gain) + .unwrap_or(1.0), } } diff --git a/src/input/pen.rs b/src/input/pen.rs index f38a86d..1b6a957 100644 --- a/src/input/pen.rs +++ b/src/input/pen.rs @@ -10,11 +10,13 @@ use crate::device::DeviceProfile; use crate::orientation::Orientation; use crate::palm::SharedPalmState; use crate::ssh; +use crate::tilt; use super::event::{key_event, parse_input_event, ABS_PRESSURE, EV_ABS, EV_SYN, SYN_REPORT}; const ABS_X: u16 = 0x00; const ABS_Y: u16 = 0x01; +const ABS_DISTANCE: u16 = 0x19; const ABS_TILT_X: u16 = 0x1a; const ABS_TILT_Y: u16 = 0x1b; @@ -70,6 +72,17 @@ pub fn run_pen( let mut pending_tilt_y: Option = None; let orientation = config.orientation; + // Tilt-offset correction. `None` when disabled: the position path is then a + // plain pass-through, identical to the uncorrected behaviour. + let correction = tilt::resolve(config.tilt_correction, config.tilt_correction_gain); + if let Some(c) = &correction { + log::info!("Pen tilt correction: {} (gain {})", c.mode, c.gain); + } + // Last-known tilt/distance, since they are not reported on every frame. + let mut last_tilt_x = 0; + let mut last_tilt_y = 0; + let mut last_distance = 0; + loop { channel.read_exact(&mut buf)?; @@ -94,12 +107,19 @@ pub fn run_pen( } ABS_TILT_X => { pending_tilt_x = Some(value); + last_tilt_x = value; continue; } ABS_TILT_Y => { pending_tilt_y = Some(value); + last_tilt_y = value; continue; } + // Hover distance is forwarded verbatim; we only record it to + // ramp the tilt correction, so it falls through to the batch. + ABS_DISTANCE => { + last_distance = value; + } _ => {} } } @@ -112,6 +132,25 @@ pub fn run_pen( // Transform and emit position events if let (Some(x), Some(y)) = (pending_x.take(), pending_y.take()) { + // Correct the tilt-induced coil-vs-nib offset in raw device space, + // before orientation (and any downstream aspect-ratio warp), where + // position and raw tilt share axes. + let (x, y) = match &correction { + Some(c) => { + let (dx, dy) = c.offset( + last_tilt_x, + last_tilt_y, + device_profile.pen_tilt_range, + last_distance, + device_profile.pen_distance_max, + ); + ( + (x - dx).clamp(0, device_profile.pen_x_max), + (y - dy).clamp(0, device_profile.pen_y_max), + ) + } + None => (x, y), + }; let (out_x, out_y) = orientation.transform_pen( x, y, device_profile.pen_x_max, diff --git a/src/main.rs b/src/main.rs index f56c87f..a49442a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod input; mod orientation; mod palm; mod ssh; +mod tilt; use std::sync::atomic::Ordering; use std::sync::Arc; diff --git a/src/tilt.rs b/src/tilt.rs new file mode 100644 index 0000000..7225dde --- /dev/null +++ b/src/tilt.rs @@ -0,0 +1,176 @@ +//! Tilt-based correction for the pen's hover-vs-contact offset. +//! +//! The reMarkable's EMR digitizer reports the position of the pen's internal +//! resonant coil, which sits a short distance up the barrel from the physical +//! nib. When the pen is tilted, the coil's projection onto the sensor plane +//! lands *ahead* of the nib by roughly `L * sin(tilt)` along the direction of +//! lean, where `L` is the effective coil-to-nib lever length. This is what +//! produces the small gap between the hover cursor (the coil projection) and +//! the pen-down ink (the nib). +//! +//! [`TiltCorrection`] subtracts that offset so the emitted coordinate tracks the +//! nib. The offset is driven by tilt and is essentially independent of hover +//! height; [`TiltCorrectionMode::TiltDistance`] additionally ramps the +//! correction by proximity so it eases off as the pen lifts away from the +//! surface. It is applied in raw device space, before orientation and any +//! downstream aspect-ratio warp, so the correction is a true device-space +//! displacement rather than something distorted by a later non-linear map. + +use std::f64::consts::FRAC_PI_2; +use std::fmt; +use std::str::FromStr; + +use serde::Deserialize; + +/// Which tilt-correction model to apply. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum TiltCorrectionMode { + /// No correction (default; preserves original behaviour). + #[default] + Off, + /// Correct by `gain * sin(tilt)` whenever the pen is in range. + Tilt, + /// Like [`Self::Tilt`], but ramped by proximity: full strength at contact, + /// easing to zero as the pen lifts to maximum hover distance. + TiltDistance, +} + +/// A resolved tilt correction: the model plus its tuned strength. +#[derive(Debug, Clone, Copy)] +pub struct TiltCorrection { + pub mode: TiltCorrectionMode, + /// Effective lever length in pen digitizer units (the offset at 90° tilt). + pub gain: f64, +} + +impl TiltCorrection { + /// The `(dx, dy)` offset to subtract from raw device coordinates. + /// + /// Full tilt range maps to 90°, so `sin` covers the physical lean. The + /// caller is responsible for clamping the corrected point into range. + pub fn offset( + &self, + tilt_x: i32, + tilt_y: i32, + tilt_range: i32, + distance: i32, + distance_max: i32, + ) -> (i32, i32) { + if self.mode == TiltCorrectionMode::Off || self.gain == 0.0 || tilt_range == 0 { + return (0, 0); + } + + let ramp = match self.mode { + TiltCorrectionMode::Off => 0.0, + TiltCorrectionMode::Tilt => 1.0, + TiltCorrectionMode::TiltDistance => { + if distance_max <= 0 { + 1.0 + } else { + (1.0 - distance as f64 / distance_max as f64).clamp(0.0, 1.0) + } + } + }; + + ( + self.axis_offset(tilt_x, tilt_range, ramp), + self.axis_offset(tilt_y, tilt_range, ramp), + ) + } + + fn axis_offset(&self, tilt: i32, tilt_range: i32, ramp: f64) -> i32 { + let t = tilt as f64 / tilt_range as f64; + (self.gain * (t * FRAC_PI_2).sin() * ramp).round() as i32 + } +} + +/// Resolve a mode + gain into an active correction, or `None` when disabled. +/// +/// Mirrors `fit::resolve`: the default/disabled case returns `None` so the pen +/// loop can skip the stage entirely. +pub fn resolve(mode: TiltCorrectionMode, gain: f64) -> Option { + if mode == TiltCorrectionMode::Off || gain == 0.0 { + return None; + } + Some(TiltCorrection { mode, gain }) +} + +impl fmt::Display for TiltCorrectionMode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + TiltCorrectionMode::Off => write!(f, "off"), + TiltCorrectionMode::Tilt => write!(f, "tilt"), + TiltCorrectionMode::TiltDistance => write!(f, "tilt-distance"), + } + } +} + +impl FromStr for TiltCorrectionMode { + type Err = String; + + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "off" | "none" => Ok(TiltCorrectionMode::Off), + "tilt" => Ok(TiltCorrectionMode::Tilt), + "tilt-distance" | "tilt_distance" | "distance" => Ok(TiltCorrectionMode::TiltDistance), + _ => Err(format!( + "Invalid tilt correction '{}'. Valid values: off, tilt, tilt-distance", + s + )), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const RANGE: i32 = 9000; // RMPP: full range = 90.00° + const DIST_MAX: i32 = 65535; + + #[test] + fn disabled_when_off_or_zero_gain() { + assert!(resolve(TiltCorrectionMode::Off, 300.0).is_none()); + assert!(resolve(TiltCorrectionMode::Tilt, 0.0).is_none()); + assert!(resolve(TiltCorrectionMode::Tilt, 300.0).is_some()); + } + + #[test] + fn off_mode_offset_is_zero() { + let c = TiltCorrection { mode: TiltCorrectionMode::Off, gain: 300.0 }; + assert_eq!(c.offset(RANGE, RANGE, RANGE, 0, DIST_MAX), (0, 0)); + } + + #[test] + fn full_tilt_offset_equals_gain() { + // At full range (90°), sin(90°) = 1, so the offset equals the gain. + let c = TiltCorrection { mode: TiltCorrectionMode::Tilt, gain: 300.0 }; + assert_eq!(c.offset(RANGE, 0, RANGE, 0, DIST_MAX), (300, 0)); + assert_eq!(c.offset(0, RANGE, RANGE, 0, DIST_MAX), (0, 300)); + } + + #[test] + fn negated_tilt_negates_offset() { + let c = TiltCorrection { mode: TiltCorrectionMode::Tilt, gain: 300.0 }; + assert_eq!(c.offset(-RANGE, 0, RANGE, 0, DIST_MAX), (-300, 0)); + } + + #[test] + fn axes_are_independent() { + let c = TiltCorrection { mode: TiltCorrectionMode::Tilt, gain: 1000.0 }; + // 45° on x only: sin(45°) ~= 0.7071 -> 707; y untouched. + assert_eq!(c.offset(RANGE / 2, 0, RANGE, 0, DIST_MAX), (707, 0)); + } + + #[test] + fn distance_ramp_full_at_contact_zero_at_max_hover() { + let c = TiltCorrection { mode: TiltCorrectionMode::TiltDistance, gain: 300.0 }; + // distance 0 (touching) -> full offset. + assert_eq!(c.offset(RANGE, 0, RANGE, 0, DIST_MAX), (300, 0)); + // distance at max (far hover) -> no offset. + assert_eq!(c.offset(RANGE, 0, RANGE, DIST_MAX, DIST_MAX), (0, 0)); + // halfway -> half offset. + assert_eq!(c.offset(RANGE, 0, RANGE, DIST_MAX / 2, DIST_MAX), (150, 0)); + } +}