1use std::collections::VecDeque;
6
7use arc_tokens::SpringSpec;
8
9use crate::spring::SpringSolver;
10
11pub fn rubber_band(distance: f32, limit: f32) -> f32 {
15 if limit <= 0.0 || distance <= 0.0 {
16 return 0.0;
17 }
18 (1.0 - 1.0 / (distance * 0.55 / limit + 1.0)) * limit
19}
20
21pub fn rubber_band_signed(distance: f32, limit: f32) -> f32 {
23 if distance == 0.0 {
24 return 0.0;
25 }
26 distance.signum() * rubber_band(distance.abs(), limit)
27}
28
29pub fn project_deceleration(velocity_px_per_sec: f32) -> f32 {
32 (velocity_px_per_sec / 1000.0) * 0.99 / (1.0 - 0.99)
33}
34
35#[derive(Clone, Copy, Debug, Default, PartialEq)]
37pub struct DragConstraints {
38 pub min: Option<f32>,
39 pub max: Option<f32>,
40 pub elastic_limit: f32,
42}
43
44impl DragConstraints {
45 pub fn apply(self, raw: f32) -> (f32, f32) {
46 let mut clamped = raw;
47 if let Some(min) = self.min {
48 clamped = clamped.max(min);
49 }
50 if let Some(max) = self.max {
51 clamped = clamped.min(max);
52 }
53 let excess = raw - clamped;
54 let elastic = if self.elastic_limit > 0.0 {
55 rubber_band_signed(excess, self.elastic_limit)
56 } else {
57 0.0
58 };
59 (clamped, elastic)
60 }
61}
62
63#[derive(Clone, Copy, Debug, PartialEq)]
65pub struct DragSample {
66 pub time_secs: f64,
67 pub position: f32,
68}
69
70#[derive(Clone, Debug)]
72pub struct DragTracker {
73 pub slop_px: f32,
74 pub active: bool,
75 start_x: f32,
76 start_y: f32,
77 origin_value: f32,
78 samples: VecDeque<DragSample>,
79}
80
81impl DragTracker {
82 pub fn new(slop_px: f32) -> Self {
83 Self {
84 slop_px: slop_px.max(0.0),
85 active: false,
86 start_x: 0.0,
87 start_y: 0.0,
88 origin_value: 0.0,
89 samples: VecDeque::with_capacity(8),
90 }
91 }
92
93 pub fn begin(&mut self, pointer_x: f32, pointer_y: f32, origin_value: f32, time_secs: f64) {
94 self.active = self.slop_px == 0.0;
95 self.start_x = pointer_x;
96 self.start_y = pointer_y;
97 self.origin_value = origin_value;
98 self.samples.clear();
99 if self.active {
100 self.samples.push_back(DragSample {
101 time_secs,
102 position: origin_value,
103 });
104 }
105 }
106
107 pub fn update_x(
110 &mut self,
111 pointer_x: f32,
112 pointer_y: f32,
113 time_secs: f64,
114 lock_horizontal: bool,
115 ) -> Option<f32> {
116 if !self.active {
117 let dx = pointer_x - self.start_x;
118 let dy = pointer_y - self.start_y;
119 if dx.hypot(dy) < self.slop_px {
120 return None;
121 }
122 if lock_horizontal && dy.abs() > dx.abs() {
123 return None;
124 }
125 self.active = true;
126 self.start_x = pointer_x;
128 self.samples.clear();
129 }
130 let raw = self.origin_value + (pointer_x - self.start_x);
131 self.samples.push_back(DragSample {
132 time_secs,
133 position: raw,
134 });
135 while self.samples.len() > 2 {
136 if let Some(front) = self.samples.front()
137 && time_secs - front.time_secs > 0.1
138 {
139 self.samples.pop_front();
140 continue;
141 }
142 break;
143 }
144 Some(raw)
145 }
146
147 pub fn release_velocity(&self, release_time_secs: f64) -> f32 {
149 let (Some(first), Some(last)) = (self.samples.front(), self.samples.back()) else {
150 return 0.0;
151 };
152 let dt = last.time_secs - first.time_secs;
153 if dt <= 0.008 || (release_time_secs - last.time_secs) > 0.060 {
154 return 0.0;
155 }
156 ((last.position - first.position) as f64 / dt) as f32
157 }
158}
159
160#[derive(Clone, Copy, Debug)]
162pub struct InertiaConfig {
163 pub power: f64,
164 pub time_constant_ms: f64,
166 pub bounce_stiffness: f64,
167 pub bounce_damping: f64,
168 pub min: Option<f64>,
169 pub max: Option<f64>,
170 pub rest_delta: f64,
171}
172
173impl Default for InertiaConfig {
174 fn default() -> Self {
175 Self {
176 power: 0.8,
177 time_constant_ms: 325.0,
178 bounce_stiffness: 500.0,
179 bounce_damping: 10.0,
180 min: None,
181 max: None,
182 rest_delta: 0.5,
183 }
184 }
185}
186
187#[derive(Clone, Copy, Debug, PartialEq)]
189pub struct InertiaSample {
190 pub value: f32,
191 pub done: bool,
192}
193
194#[derive(Clone, Debug)]
196pub struct InertiaSolver {
197 target: f64,
198 amplitude: f64,
199 config: InertiaConfig,
200 boundary_time_ms: Option<f64>,
201 boundary_spring: Option<SpringSolver>,
202}
203
204impl InertiaSolver {
205 pub fn new(origin: f64, velocity_per_sec: f64, config: InertiaConfig) -> Self {
206 let amplitude = config.power * velocity_per_sec;
207 let target = origin + amplitude;
208 let mut solver = Self {
209 target,
210 amplitude,
211 config,
212 boundary_time_ms: None,
213 boundary_spring: None,
214 };
215 solver.check_boundary(0.0, origin);
216 if solver.boundary_spring.is_none()
217 && solver.is_out_of_bounds(target)
218 && amplitude.abs() > 1e-9
219 && config.time_constant_ms > 0.0
220 {
221 let boundary = solver.nearest_boundary(target);
222 if (target - boundary).abs() > config.rest_delta {
223 let ratio = ((target - boundary) / amplitude).clamp(1e-9, 1.0);
224 let bt = (-config.time_constant_ms * ratio.ln()).max(0.0);
225 solver.check_boundary(bt, boundary);
226 }
227 }
228 solver
229 }
230
231 fn is_out_of_bounds(&self, v: f64) -> bool {
232 self.config.min.is_some_and(|min| v < min) || self.config.max.is_some_and(|max| v > max)
233 }
234
235 fn nearest_boundary(&self, v: f64) -> f64 {
236 match (self.config.min, self.config.max) {
237 (Some(min), Some(max)) => {
238 if (min - v).abs() < (max - v).abs() {
239 min
240 } else {
241 max
242 }
243 }
244 (Some(min), None) => min,
245 (None, Some(max)) => max,
246 (None, None) => v,
247 }
248 }
249
250 fn calc_delta(&self, t_ms: f64) -> f64 {
251 -self.amplitude * (-t_ms / self.config.time_constant_ms).exp()
252 }
253
254 fn check_boundary(&mut self, t_ms: f64, value: f64) {
255 if self.boundary_spring.is_some() || !self.is_out_of_bounds(value) {
256 return;
257 }
258 self.boundary_time_ms = Some(t_ms);
259 let boundary = self.nearest_boundary(value);
260 let velocity_per_sec = (-self.calc_delta(t_ms) / self.config.time_constant_ms) * 1000.0;
263 let spec = SpringSpec::physics(
264 self.config.bounce_stiffness as f32,
265 self.config.bounce_damping as f32,
266 );
267 self.boundary_spring = Some(
268 SpringSolver::new(spec, value, boundary, velocity_per_sec)
269 .with_rest_thresholds(self.config.rest_delta, 2.0),
270 );
271 }
272
273 pub fn sample_ms(&mut self, t_ms: f64) -> InertiaSample {
275 let t_ms = t_ms.max(0.0);
276 if self.boundary_spring.is_none() {
277 let delta = self.calc_delta(t_ms);
278 let done = delta.abs() <= self.config.rest_delta;
279 let value = if done {
280 self.target
281 } else {
282 self.target + delta
283 };
284 self.check_boundary(t_ms, value);
285 if self.boundary_spring.is_none() {
286 return InertiaSample {
287 value: value as f32,
288 done,
289 };
290 }
291 }
292
293 if let (Some(bt), Some(spring)) = (self.boundary_time_ms, &self.boundary_spring)
294 && t_ms >= bt
295 {
296 let s = spring.sample((t_ms - bt) / 1000.0);
297 return InertiaSample {
298 value: s.value,
299 done: s.settled,
300 };
301 }
302
303 let delta = self.calc_delta(t_ms);
304 let done = delta.abs() <= self.config.rest_delta;
305 let value = if done {
306 self.target
307 } else {
308 self.target + delta
309 };
310 InertiaSample {
311 value: value as f32,
312 done,
313 }
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 #[test]
322 fn rubber_band_is_monotonic_and_bounded_by_limit() {
323 let limit = 26.0;
324 assert_eq!(rubber_band_signed(0.0, limit), 0.0);
325 let small = rubber_band_signed(10.0, limit);
326 let large = rubber_band_signed(1000.0, limit);
327 assert!(small > 0.0 && small < large && large < limit);
328 assert!((rubber_band_signed(-10.0, limit) + small).abs() < 1e-5);
329 }
330
331 #[test]
332 fn drag_tracker_handles_slop_and_velocity() {
333 let mut tracker = DragTracker::new(6.0);
334 tracker.begin(100.0, 50.0, 0.0, 0.0);
335 assert_eq!(tracker.update_x(103.0, 50.0, 0.016, true), None);
336 assert!(!tracker.active);
337
338 assert_eq!(tracker.update_x(110.0, 50.0, 0.032, true), Some(0.0));
340 assert!(tracker.active);
341 assert_eq!(tracker.update_x(160.0, 50.0, 0.082, true), Some(50.0));
342 let vel = tracker.release_velocity(0.090);
343 assert!((vel - 1000.0).abs() < 1.0, "expected ~1000px/s, got {vel}");
344 }
345
346 #[test]
347 fn inertia_matches_motion_decay_and_bounces_at_boundary() {
348 let mut free = InertiaSolver::new(0.0, 500.0, InertiaConfig::default());
350 let s100 = free.sample_ms(100.0);
351 let expected = 400.0 - 400.0 * (-100.0_f64 / 325.0).exp();
352 assert!((f64::from(s100.value) - expected).abs() < 1e-3);
353
354 let cfg = InertiaConfig {
356 min: Some(0.0),
357 max: Some(100.0),
358 ..Default::default()
359 };
360 let mut bounded = InertiaSolver::new(0.0, 800.0, cfg);
361 let mut settled_value = 0.0;
362 let mut reached_done = false;
363 for step in 1..=200 {
364 let s = bounded.sample_ms(step as f64 * 16.0);
365 settled_value = s.value;
366 if s.done {
367 reached_done = true;
368 break;
369 }
370 }
371 assert!(reached_done);
372 assert!((settled_value - 100.0).abs() <= 0.5);
373 }
374}