forge
Explore
Log in

Don't you dare go Hollow

Implement spring animations

Browse files at this commit

ae89b2e514fd4c22a38c2dce258707c369ca944aIvan MolodetskikhParent: 732f7f6
niri-config/src/lib.rsmodified+310 -21
@@ -527,50 +527,95 @@ impl Default for Animations {
527527 }
528528 }
529529
530-#[derive(knuffel::Decode, Debug, Clone, Copy, PartialEq)]
530+#[derive(Debug, Clone, Copy, PartialEq)]
531531 pub struct Animation {
532- #[knuffel(child)]
533532 pub off: bool,
534- #[knuffel(child, unwrap(argument))]
535- pub duration_ms: Option<u32>,
536- #[knuffel(child, unwrap(argument))]
537- pub curve: Option<AnimationCurve>,
533+ pub kind: AnimationKind,
538534 }
539535
540536 impl Animation {
541537 pub const fn unfilled() -> Self {
542538 Self {
543539 off: false,
544- duration_ms: None,
545- curve: None,
540+ kind: AnimationKind::Easing(EasingParams::unfilled()),
546541 }
547542 }
548543
549544 pub const fn default() -> Self {
550545 Self {
551546 off: false,
552- duration_ms: Some(250),
553- curve: Some(AnimationCurve::EaseOutCubic),
547+ kind: AnimationKind::Easing(EasingParams::default()),
554548 }
555549 }
556550
557551 pub const fn default_workspace_switch() -> Self {
558- Self::default()
552+ Self {
553+ off: false,
554+ kind: AnimationKind::Spring(SpringParams {
555+ damping_ratio: 1.,
556+ stiffness: 1000,
557+ epsilon: 0.0001,
558+ }),
559+ }
559560 }
560561
561562 pub const fn default_horizontal_view_movement() -> Self {
562- Self::default()
563+ Self {
564+ off: false,
565+ kind: AnimationKind::Spring(SpringParams {
566+ damping_ratio: 1.,
567+ stiffness: 800,
568+ epsilon: 0.0001,
569+ }),
570+ }
563571 }
564572
565573 pub const fn default_config_notification_open_close() -> Self {
566- Self::default()
574+ Self {
575+ off: false,
576+ kind: AnimationKind::Spring(SpringParams {
577+ damping_ratio: 0.6,
578+ stiffness: 1000,
579+ epsilon: 0.001,
580+ }),
581+ }
567582 }
568583
569584 pub const fn default_window_open() -> Self {
570585 Self {
571- duration_ms: Some(150),
572- curve: Some(AnimationCurve::EaseOutExpo),
573- ..Self::default()
586+ off: false,
587+ kind: AnimationKind::Easing(EasingParams {
588+ duration_ms: Some(150),
589+ curve: Some(AnimationCurve::EaseOutExpo),
590+ }),
591+ }
592+ }
593+}
594+
595+#[derive(Debug, Clone, Copy, PartialEq)]
596+pub enum AnimationKind {
597+ Easing(EasingParams),
598+ Spring(SpringParams),
599+}
600+
601+#[derive(Debug, Clone, Copy, PartialEq)]
602+pub struct EasingParams {
603+ pub duration_ms: Option<u32>,
604+ pub curve: Option<AnimationCurve>,
605+}
606+
607+impl EasingParams {
608+ pub const fn unfilled() -> Self {
609+ Self {
610+ duration_ms: None,
611+ curve: None,
612+ }
613+ }
614+
615+ pub const fn default() -> Self {
616+ Self {
617+ duration_ms: Some(250),
618+ curve: Some(AnimationCurve::EaseOutCubic),
574619 }
575620 }
576621 }
@@ -581,6 +626,13 @@ pub enum AnimationCurve {
581626 EaseOutExpo,
582627 }
583628
629+#[derive(Debug, Clone, Copy, PartialEq)]
630+pub struct SpringParams {
631+ pub damping_ratio: f64,
632+ pub stiffness: u32,
633+ pub epsilon: f64,
634+}
635+
584636 #[derive(knuffel::Decode, Debug, Default, Clone, PartialEq, Eq)]
585637 pub struct Environment(#[knuffel(children)] pub Vec<EnvironmentVariable>);
586638
@@ -1012,6 +1064,229 @@ where
10121064 }
10131065 }
10141066
1067+fn parse_arg_node<S: knuffel::traits::ErrorSpan, T: knuffel::traits::DecodeScalar<S>>(
1068+ name: &str,
1069+ node: &knuffel::ast::SpannedNode<S>,
1070+ ctx: &mut knuffel::decode::Context<S>,
1071+) -> Result<T, DecodeError<S>> {
1072+ let mut iter_args = node.arguments.iter();
1073+ let val = iter_args.next().ok_or_else(|| {
1074+ DecodeError::missing(node, format!("additional argument `{name}` is required"))
1075+ })?;
1076+
1077+ let value = knuffel::traits::DecodeScalar::decode(val, ctx)?;
1078+
1079+ if let Some(val) = iter_args.next() {
1080+ ctx.emit_error(DecodeError::unexpected(
1081+ &val.literal,
1082+ "argument",
1083+ "unexpected argument",
1084+ ));
1085+ }
1086+ for name in node.properties.keys() {
1087+ ctx.emit_error(DecodeError::unexpected(
1088+ name,
1089+ "property",
1090+ format!("unexpected property `{}`", name.escape_default()),
1091+ ));
1092+ }
1093+ for child in node.children() {
1094+ ctx.emit_error(DecodeError::unexpected(
1095+ child,
1096+ "node",
1097+ format!("unexpected node `{}`", child.node_name.escape_default()),
1098+ ));
1099+ }
1100+
1101+ Ok(value)
1102+}
1103+
1104+impl<S> knuffel::Decode<S> for Animation
1105+where
1106+ S: knuffel::traits::ErrorSpan,
1107+{
1108+ fn decode_node(
1109+ node: &knuffel::ast::SpannedNode<S>,
1110+ ctx: &mut knuffel::decode::Context<S>,
1111+ ) -> Result<Self, DecodeError<S>> {
1112+ expect_only_children(node, ctx);
1113+
1114+ let mut off = false;
1115+ let mut easing_params = EasingParams::unfilled();
1116+ let mut spring_params = None;
1117+
1118+ for child in node.children() {
1119+ match &**child.node_name {
1120+ "off" => {
1121+ knuffel::decode::check_flag_node(child, ctx);
1122+ if off {
1123+ ctx.emit_error(DecodeError::unexpected(
1124+ &child.node_name,
1125+ "node",
1126+ "duplicate node `off`, single node expected",
1127+ ));
1128+ } else {
1129+ off = true;
1130+ }
1131+ }
1132+ "spring" => {
1133+ if easing_params != EasingParams::unfilled() {
1134+ ctx.emit_error(DecodeError::unexpected(
1135+ child,
1136+ "node",
1137+ "cannot set both spring and easing parameters at once",
1138+ ));
1139+ }
1140+ if spring_params.is_some() {
1141+ ctx.emit_error(DecodeError::unexpected(
1142+ &child.node_name,
1143+ "node",
1144+ "duplicate node `spring`, single node expected",
1145+ ));
1146+ }
1147+
1148+ spring_params = Some(SpringParams::decode_node(child, ctx)?);
1149+ }
1150+ "duration-ms" => {
1151+ if spring_params.is_some() {
1152+ ctx.emit_error(DecodeError::unexpected(
1153+ child,
1154+ "node",
1155+ "cannot set both spring and easing parameters at once",
1156+ ));
1157+ }
1158+ if easing_params.duration_ms.is_some() {
1159+ ctx.emit_error(DecodeError::unexpected(
1160+ &child.node_name,
1161+ "node",
1162+ "duplicate node `duration-ms`, single node expected",
1163+ ));
1164+ }
1165+
1166+ easing_params.duration_ms = Some(parse_arg_node("duration-ms", child, ctx)?);
1167+ }
1168+ "curve" => {
1169+ if spring_params.is_some() {
1170+ ctx.emit_error(DecodeError::unexpected(
1171+ child,
1172+ "node",
1173+ "cannot set both spring and easing parameters at once",
1174+ ));
1175+ }
1176+ if easing_params.curve.is_some() {
1177+ ctx.emit_error(DecodeError::unexpected(
1178+ &child.node_name,
1179+ "node",
1180+ "duplicate node `curve`, single node expected",
1181+ ));
1182+ }
1183+
1184+ easing_params.curve = Some(parse_arg_node("curve", child, ctx)?);
1185+ }
1186+ name_str => {
1187+ ctx.emit_error(DecodeError::unexpected(
1188+ child,
1189+ "node",
1190+ format!("unexpected node `{}`", name_str.escape_default()),
1191+ ));
1192+ }
1193+ }
1194+ }
1195+
1196+ let kind = if let Some(spring_params) = spring_params {
1197+ AnimationKind::Spring(spring_params)
1198+ } else {
1199+ AnimationKind::Easing(easing_params)
1200+ };
1201+
1202+ Ok(Self { off, kind })
1203+ }
1204+}
1205+
1206+impl<S> knuffel::Decode<S> for SpringParams
1207+where
1208+ S: knuffel::traits::ErrorSpan,
1209+{
1210+ fn decode_node(
1211+ node: &knuffel::ast::SpannedNode<S>,
1212+ ctx: &mut knuffel::decode::Context<S>,
1213+ ) -> Result<Self, DecodeError<S>> {
1214+ if let Some(type_name) = &node.type_name {
1215+ ctx.emit_error(DecodeError::unexpected(
1216+ type_name,
1217+ "type name",
1218+ "no type name expected for this node",
1219+ ));
1220+ }
1221+ if let Some(val) = node.arguments.first() {
1222+ ctx.emit_error(DecodeError::unexpected(
1223+ &val.literal,
1224+ "argument",
1225+ "unexpected argument",
1226+ ));
1227+ }
1228+ for child in node.children() {
1229+ ctx.emit_error(DecodeError::unexpected(
1230+ child,
1231+ "node",
1232+ format!("unexpected node `{}`", child.node_name.escape_default()),
1233+ ));
1234+ }
1235+
1236+ let mut damping_ratio = None;
1237+ let mut stiffness = None;
1238+ let mut epsilon = None;
1239+ for (name, val) in &node.properties {
1240+ match &***name {
1241+ "damping-ratio" => {
1242+ damping_ratio = Some(knuffel::traits::DecodeScalar::decode(val, ctx)?);
1243+ }
1244+ "stiffness" => {
1245+ stiffness = Some(knuffel::traits::DecodeScalar::decode(val, ctx)?);
1246+ }
1247+ "epsilon" => {
1248+ epsilon = Some(knuffel::traits::DecodeScalar::decode(val, ctx)?);
1249+ }
1250+ name_str => {
1251+ ctx.emit_error(DecodeError::unexpected(
1252+ name,
1253+ "property",
1254+ format!("unexpected property `{}`", name_str.escape_default()),
1255+ ));
1256+ }
1257+ }
1258+ }
1259+ let damping_ratio = damping_ratio
1260+ .ok_or_else(|| DecodeError::missing(node, "property `damping-ratio` is required"))?;
1261+ let stiffness = stiffness
1262+ .ok_or_else(|| DecodeError::missing(node, "property `stiffness` is required"))?;
1263+ let epsilon =
1264+ epsilon.ok_or_else(|| DecodeError::missing(node, "property `epsilon` is required"))?;
1265+
1266+ if !(0.1..=10.).contains(&damping_ratio) {
1267+ ctx.emit_error(DecodeError::conversion(
1268+ node,
1269+ "damping-ratio must be between 0.1 and 10.0",
1270+ ));
1271+ }
1272+ if stiffness < 1 {
1273+ ctx.emit_error(DecodeError::conversion(node, "stiffness must be >= 1"));
1274+ }
1275+ if !(0.00001..=0.1).contains(&epsilon) {
1276+ ctx.emit_error(DecodeError::conversion(
1277+ node,
1278+ "epsilon must be between 0.00001 and 0.1",
1279+ ));
1280+ }
1281+
1282+ Ok(SpringParams {
1283+ damping_ratio,
1284+ stiffness,
1285+ epsilon,
1286+ })
1287+ }
1288+}
1289+
10151290 impl<S> knuffel::Decode<S> for Binds
10161291 where
10171292 S: knuffel::traits::ErrorSpan,
@@ -1345,12 +1620,16 @@ mod tests {
13451620 animations {
13461621 slowdown 2.0
13471622
1348- workspace-switch { off; }
1623+ workspace-switch {
1624+ spring damping-ratio=1.0 stiffness=1000 epsilon=0.0001
1625+ }
13491626
13501627 horizontal-view-movement {
13511628 duration-ms 100
13521629 curve "ease-out-expo"
13531630 }
1631+
1632+ window-open { off; }
13541633 }
13551634
13561635 environment {
@@ -1507,12 +1786,22 @@ mod tests {
15071786 animations: Animations {
15081787 slowdown: 2.,
15091788 workspace_switch: Animation {
1510- off: true,
1511- ..Animation::unfilled()
1789+ off: false,
1790+ kind: AnimationKind::Spring(SpringParams {
1791+ damping_ratio: 1.,
1792+ stiffness: 1000,
1793+ epsilon: 0.0001,
1794+ }),
15121795 },
15131796 horizontal_view_movement: Animation {
1514- duration_ms: Some(100),
1515- curve: Some(AnimationCurve::EaseOutExpo),
1797+ off: false,
1798+ kind: AnimationKind::Easing(EasingParams {
1799+ duration_ms: Some(100),
1800+ curve: Some(AnimationCurve::EaseOutExpo),
1801+ }),
1802+ },
1803+ window_open: Animation {
1804+ off: true,
15161805 ..Animation::unfilled()
15171806 },
15181807 ..Default::default()
resources/default-config.kdlmodified+35 -7
@@ -254,18 +254,48 @@ animations {
254254 // slowdown 3.0
255255
256256 // You can configure all individual animations.
257- // Available settings are the same for all of them:
257+ // Available settings are the same for all of them.
258258 // - off disables the animation.
259+ //
260+ // Niri supports two animation types: easing and spring.
261+ //
262+ // Easing has the following settings:
259263 // - duration-ms sets the duration of the animation in milliseconds.
260264 // - curve sets the easing curve. Currently, available curves
261265 // are "ease-out-cubic" and "ease-out-expo".
266+ //
267+ // Spring animations work better with touchpad gestures, because they
268+ // take into account the velocity of your fingers as you release the swipe.
269+ // The parameters are less obvious and generally should be tuned
270+ // with trial and error. Notably, you cannot directly set the duration.
271+ // You can use this app to help visualize how the spring parameters
272+ // change the animation: https://flathub.org/apps/app.drey.Elastic
273+ //
274+ // A spring animation is configured like this:
275+ // - spring damping-ratio=1.0 stiffness=1000 epsilon=0.0001
276+ //
277+ // The damping ratio goes from 0.1 to 10.0 and has the following properties:
278+ // - below 1.0: underdamped spring, will oscillate in the end.
279+ // - above 1.0: overdamped spring, won't oscillate.
280+ // - 1.0: critically damped spring, comes to rest in minimum possible time
281+ // without oscillations.
282+ //
283+ // However, even with damping ratio = 1.0 the spring animation may oscillate
284+ // if "launched" with enough velocity from a touchpad swipe.
285+ //
286+ // Lower stiffness will result in a slower animation more prone to oscillation.
287+ //
288+ // Set epsilon to a lower value if the animation "jumps" in the end.
289+ //
290+ // The spring mass is hardcoded to 1.0 and cannot be changed. Instead, change
291+ // stiffness proportionally. E.g. increasing mass by 2x is the same as
292+ // decreasing stiffness by 2x.
262293
263294 // Animation when switching workspaces up and down,
264295 // including after the touchpad gesture.
265296 workspace-switch {
266297 // off
267- // duration-ms 250
268- // curve "ease-out-cubic"
298+ // spring damping-ratio=1.0 stiffness=1000 epsilon=0.0001
269299 }
270300
271301 // All horizontal camera view movement:
@@ -275,8 +305,7 @@ animations {
275305 // - And so on.
276306 horizontal-view-movement {
277307 // off
278- // duration-ms 250
279- // curve "ease-out-cubic"
308+ // spring damping-ratio=1.0 stiffness=800 epsilon=0.0001
280309 }
281310
282311 // Window opening animation. Note that this one has different defaults.
@@ -290,8 +319,7 @@ animations {
290319 // open/close animation.
291320 config-notification-open-close {
292321 // off
293- // duration-ms 250
294- // curve "ease-out-cubic"
322+ // spring damping-ratio=0.6 stiffness=1000 epsilon=0.001
295323 }
296324 }
297325
src/animation/mod.rsmodified+140 -11
@@ -6,6 +6,9 @@ use portable_atomic::{AtomicF64, Ordering};
66
77 use crate::utils::get_monotonic_time;
88
9+mod spring;
10+pub use spring::{Spring, SpringParams};
11+
912 pub static ANIMATION_SLOWDOWN: AtomicF64 = AtomicF64::new(1.);
1013
1114 #[derive(Debug)]
@@ -15,7 +18,19 @@ pub struct Animation {
1518 duration: Duration,
1619 start_time: Duration,
1720 current_time: Duration,
18- curve: Curve,
21+ kind: Kind,
22+}
23+
24+#[derive(Debug, Clone, Copy)]
25+enum Kind {
26+ Easing {
27+ curve: Curve,
28+ },
29+ Spring(Spring),
30+ Deceleration {
31+ initial_velocity: f64,
32+ deceleration_rate: f64,
33+ },
1934 }
2035
2136 #[derive(Debug, Clone, Copy)]
@@ -28,21 +43,116 @@ impl Animation {
2843 pub fn new(
2944 from: f64,
3045 to: f64,
46+ initial_velocity: f64,
3147 config: niri_config::Animation,
3248 default: niri_config::Animation,
49+ ) -> Self {
50+ if config.off {
51+ return Self::ease(from, to, 0, Curve::EaseOutCubic);
52+ }
53+
54+ // Resolve defaults.
55+ let (kind, easing_defaults) = match (config.kind, default.kind) {
56+ // Configured spring.
57+ (configured @ niri_config::AnimationKind::Spring(_), _) => (configured, None),
58+ // Configured nothing, defaults spring.
59+ (
60+ niri_config::AnimationKind::Easing(easing),
61+ defaults @ niri_config::AnimationKind::Spring(_),
62+ ) if easing == niri_config::EasingParams::unfilled() => (defaults, None),
63+ // Configured easing or nothing, defaults easing.
64+ (
65+ configured @ niri_config::AnimationKind::Easing(_),
66+ niri_config::AnimationKind::Easing(defaults),
67+ ) => (configured, Some(defaults)),
68+ // Configured easing, defaults spring.
69+ (
70+ configured @ niri_config::AnimationKind::Easing(_),
71+ niri_config::AnimationKind::Spring(_),
72+ ) => (configured, None),
73+ };
74+
75+ match kind {
76+ niri_config::AnimationKind::Spring(p) => {
77+ let params = SpringParams::new(p.damping_ratio, f64::from(p.stiffness), p.epsilon);
78+
79+ let spring = Spring {
80+ from,
81+ to,
82+ initial_velocity,
83+ params,
84+ };
85+ Self::spring(spring)
86+ }
87+ niri_config::AnimationKind::Easing(p) => {
88+ let defaults = easing_defaults.unwrap_or(niri_config::EasingParams::default());
89+ let duration_ms = p.duration_ms.or(defaults.duration_ms).unwrap();
90+ let curve = Curve::from(p.curve.or(defaults.curve).unwrap());
91+ Self::ease(from, to, u64::from(duration_ms), curve)
92+ }
93+ }
94+ }
95+
96+ pub fn ease(from: f64, to: f64, duration_ms: u64, curve: Curve) -> Self {
97+ // FIXME: ideally we shouldn't use current time here because animations started within the
98+ // same frame cycle should have the same start time to be synchronized.
99+ let now = get_monotonic_time();
100+
101+ let duration = Duration::from_millis(duration_ms);
102+ let kind = Kind::Easing { curve };
103+
104+ Self {
105+ from,
106+ to,
107+ duration,
108+ start_time: now,
109+ current_time: now,
110+ kind,
111+ }
112+ }
113+
114+ pub fn spring(spring: Spring) -> Self {
115+ // FIXME: ideally we shouldn't use current time here because animations started within the
116+ // same frame cycle should have the same start time to be synchronized.
117+ let now = get_monotonic_time();
118+
119+ let duration = spring.duration();
120+ let kind = Kind::Spring(spring);
121+
122+ Self {
123+ from: spring.from,
124+ to: spring.to,
125+ duration,
126+ start_time: now,
127+ current_time: now,
128+ kind,
129+ }
130+ }
131+
132+ pub fn decelerate(
133+ from: f64,
134+ initial_velocity: f64,
135+ deceleration_rate: f64,
136+ threshold: f64,
33137 ) -> Self {
34138 // FIXME: ideally we shouldn't use current time here because animations started within the
35139 // same frame cycle should have the same start time to be synchronized.
36140 let now = get_monotonic_time();
37141
38- let duration_ms = if config.off {
39- 0
142+ let duration_s = if initial_velocity == 0. {
143+ 0.
40144 } else {
41- config.duration_ms.unwrap_or(default.duration_ms.unwrap())
145+ let coeff = 1000. * deceleration_rate.ln();
146+ (-coeff * threshold / initial_velocity.abs()).ln() / coeff
42147 };
43- let duration = Duration::from_millis(u64::from(duration_ms));
148+ let duration = Duration::from_secs_f64(duration_s);
149+
150+ let to = from - initial_velocity / (1000. * deceleration_rate.ln());
44151
45- let curve = Curve::from(config.curve.unwrap_or(default.curve.unwrap()));
152+ let kind = Kind::Deceleration {
153+ initial_velocity,
154+ deceleration_rate,
155+ };
46156
47157 Self {
48158 from,
@@ -50,7 +160,7 @@ impl Animation {
50160 duration,
51161 start_time: now,
52162 current_time: now,
53- curve,
163+ kind,
54164 }
55165 }
56166
@@ -118,10 +228,29 @@ impl Animation {
118228 }
119229
120230 pub fn value(&self) -> f64 {
121- let passed = (self.current_time - self.start_time).as_secs_f64();
122- let total = self.duration.as_secs_f64();
123- let x = (passed / total).clamp(0., 1.);
124- self.curve.y(x) * (self.to - self.from) + self.from
231+ if self.is_done() {
232+ return self.to;
233+ }
234+
235+ let passed = self.current_time - self.start_time;
236+
237+ match self.kind {
238+ Kind::Easing { curve } => {
239+ let passed = passed.as_secs_f64();
240+ let total = self.duration.as_secs_f64();
241+ let x = (passed / total).clamp(0., 1.);
242+ curve.y(x) * (self.to - self.from) + self.from
243+ }
244+ Kind::Spring(spring) => spring.value_at(passed),
245+ Kind::Deceleration {
246+ initial_velocity,
247+ deceleration_rate,
248+ } => {
249+ let passed = passed.as_secs_f64();
250+ let coeff = 1000. * deceleration_rate.ln();
251+ self.from + (deceleration_rate.powf(1000. * passed) - 1.) / coeff * initial_velocity
252+ }
253+ }
125254 }
126255
127256 pub fn to(&self) -> f64 {
src/animation/spring.rsadded+137 -0
@@ -0,0 +1,137 @@
1+use std::time::Duration;
2+
3+#[derive(Debug, Clone, Copy)]
4+pub struct SpringParams {
5+ pub damping: f64,
6+ pub mass: f64,
7+ pub stiffness: f64,
8+ pub epsilon: f64,
9+}
10+
11+#[derive(Debug, Clone, Copy)]
12+pub struct Spring {
13+ pub from: f64,
14+ pub to: f64,
15+ pub initial_velocity: f64,
16+ pub params: SpringParams,
17+}
18+
19+impl SpringParams {
20+ pub fn new(damping_ratio: f64, stiffness: f64, epsilon: f64) -> Self {
21+ let damping_ratio = damping_ratio.max(0.);
22+ let stiffness = stiffness.max(0.);
23+ let epsilon = epsilon.max(0.);
24+
25+ let mass = 1.;
26+ let critical_damping = 2. * (mass * stiffness).sqrt();
27+ let damping = damping_ratio * critical_damping;
28+
29+ Self {
30+ damping,
31+ mass,
32+ stiffness,
33+ epsilon,
34+ }
35+ }
36+}
37+
38+impl Spring {
39+ pub fn value_at(&self, t: Duration) -> f64 {
40+ self.oscillate(t.as_secs_f64())
41+ }
42+
43+ // Based on libadwaita (LGPL-2.1-or-later):
44+ // https://gitlab.gnome.org/GNOME/libadwaita/-/blob/1.4.4/src/adw-spring-animation.c,
45+ // which itself is based on (MIT):
46+ // https://github.com/robb/RBBAnimation/blob/master/RBBAnimation/RBBSpringAnimation.m
47+ /// Computes and returns the duration until the spring is at rest.
48+ pub fn duration(&self) -> Duration {
49+ const DELTA: f64 = 0.001;
50+
51+ let beta = self.params.damping / (2. * self.params.mass);
52+
53+ if beta.abs() <= f64::EPSILON || beta < 0. {
54+ return Duration::MAX;
55+ }
56+
57+ let omega0 = (self.params.stiffness / self.params.mass).sqrt();
58+
59+ // As first ansatz for the overdamped solution,
60+ // and general estimation for the oscillating ones
61+ // we take the value of the envelope when it's < epsilon.
62+ let mut x0 = -self.params.epsilon.ln() / beta;
63+
64+ // f64::EPSILON is too small for this specific comparison, so we use
65+ // f32::EPSILON even though it's doubles.
66+ if (beta - omega0).abs() <= f64::from(f32::EPSILON) || beta < omega0 {
67+ return Duration::from_secs_f64(x0);
68+ }
69+
70+ // Since the overdamped solution decays way slower than the envelope
71+ // we need to use the value of the oscillation itself.
72+ // Newton's root finding method is a good candidate in this particular case:
73+ // https://en.wikipedia.org/wiki/Newton%27s_method
74+ let mut y0 = self.oscillate(x0);
75+ let m = (self.oscillate(x0 + DELTA) - y0) / DELTA;
76+
77+ let mut x1 = (self.to - y0 + m * x0) / m;
78+ let mut y1 = self.oscillate(x1);
79+
80+ let mut i = 0;
81+ while (self.to - y1).abs() > self.params.epsilon {
82+ if i > 1000 {
83+ return Duration::ZERO;
84+ }
85+
86+ x0 = x1;
87+ y0 = y1;
88+
89+ let m = (self.oscillate(x0 + DELTA) - y0) / DELTA;
90+
91+ x1 = (self.to - y0 + m * x0) / m;
92+ y1 = self.oscillate(x1);
93+ i += 1;
94+ }
95+
96+ Duration::from_secs_f64(x1)
97+ }
98+
99+ /// Returns the spring position at a given time in seconds.
100+ fn oscillate(&self, t: f64) -> f64 {
101+ let b = self.params.damping;
102+ let m = self.params.mass;
103+ let k = self.params.stiffness;
104+ let v0 = self.initial_velocity;
105+
106+ let beta = b / (2. * m);
107+ let omega0 = (k / m).sqrt();
108+
109+ let x0 = self.from - self.to;
110+
111+ let envelope = (-beta * t).exp();
112+
113+ // Solutions of the form C1*e^(lambda1*x) + C2*e^(lambda2*x)
114+ // for the differential equation m*ẍ+b*ẋ+kx = 0
115+
116+ // f64::EPSILON is too small for this specific comparison, so we use
117+ // f32::EPSILON even though it's doubles.
118+ if (beta - omega0).abs() <= f64::from(f32::EPSILON) {
119+ // Critically damped.
120+ self.to + envelope * (x0 + (beta * x0 + v0) * t)
121+ } else if beta < omega0 {
122+ // Underdamped.
123+ let omega1 = ((omega0 * omega0) - (beta * beta)).sqrt();
124+
125+ self.to
126+ + envelope
127+ * (x0 * (omega1 * t).cos() + ((beta * x0 + v0) / omega1) * (omega1 * t).sin())
128+ } else {
129+ // Overdamped.
130+ let omega2 = ((beta * beta) - (omega0 * omega0)).sqrt();
131+
132+ self.to
133+ + envelope
134+ * (x0 * (omega2 * t).cosh() + ((beta * x0 + v0) / omega2) * (omega2 * t).sinh())
135+ }
136+ }
137+}
src/layout/monitor.rsmodified+4 -0
@@ -94,6 +94,7 @@ impl<W: LayoutElement> Monitor<W> {
9494 return;
9595 }
9696
97+ // FIXME: also compute and use current velocity.
9798 let current_idx = self
9899 .workspace_switch
99100 .as_ref()
@@ -105,6 +106,7 @@ impl<W: LayoutElement> Monitor<W> {
105106 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
106107 current_idx,
107108 idx as f64,
109+ 0.,
108110 self.options.animations.workspace_switch,
109111 niri_config::Animation::default_workspace_switch(),
110112 )));
@@ -781,6 +783,7 @@ impl<W: LayoutElement> Monitor<W> {
781783 return true;
782784 }
783785
786+ let velocity = gesture.tracker.velocity() / WORKSPACE_GESTURE_MOVEMENT;
784787 let pos = gesture.tracker.projected_end_pos() / WORKSPACE_GESTURE_MOVEMENT;
785788
786789 let min = gesture.center_idx.saturating_sub(1) as f64;
@@ -792,6 +795,7 @@ impl<W: LayoutElement> Monitor<W> {
792795 self.workspace_switch = Some(WorkspaceSwitch::Animation(Animation::new(
793796 gesture.current_idx,
794797 new_idx as f64,
798+ velocity,
795799 self.options.animations.workspace_switch,
796800 niri_config::Animation::default_workspace_switch(),
797801 )));
src/layout/tile.rsmodified+1 -0
@@ -111,6 +111,7 @@ impl<W: LayoutElement> Tile<W> {
111111 self.open_animation = Some(Animation::new(
112112 0.,
113113 1.,
114+ 0.,
114115 self.options.animations.window_open,
115116 niri_config::Animation::default_window_open(),
116117 ));
src/layout/workspace.rsmodified+4 -0
@@ -436,9 +436,11 @@ impl<W: LayoutElement> Workspace<W> {
436436 return;
437437 }
438438
439+ // FIXME: also compute and use current velocity.
439440 self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(
440441 self.view_offset as f64,
441442 new_view_offset as f64,
443+ 0.,
442444 self.options.animations.horizontal_view_movement,
443445 niri_config::Animation::default_horizontal_view_movement(),
444446 )));
@@ -1272,6 +1274,7 @@ impl<W: LayoutElement> Workspace<W> {
12721274 // effort and bug potential.
12731275
12741276 let norm_factor = self.working_area.size.w as f64 / VIEW_GESTURE_WORKING_AREA_MOVEMENT;
1277+ let velocity = gesture.tracker.velocity() * norm_factor;
12751278 let pos = gesture.tracker.pos() * norm_factor;
12761279 let current_view_offset = pos + gesture.delta_from_tracker;
12771280
@@ -1420,6 +1423,7 @@ impl<W: LayoutElement> Workspace<W> {
14201423 self.view_offset_adj = Some(ViewOffsetAdjustment::Animation(Animation::new(
14211424 current_view_offset + delta,
14221425 target_view_offset as f64,
1426+ velocity,
14231427 self.options.animations.horizontal_view_movement,
14241428 niri_config::Animation::default_horizontal_view_movement(),
14251429 )));
src/ui/config_error_notification.rsmodified+4 -1
@@ -62,6 +62,7 @@ impl ConfigErrorNotification {
6262 Animation::new(
6363 from,
6464 to,
65+ 0.,
6566 c.animations.config_notification_open_close,
6667 niri_config::Animation::default_config_notification_open_close(),
6768 )
@@ -118,7 +119,9 @@ impl ConfigErrorNotification {
118119 }
119120 State::Hiding(anim) => {
120121 anim.set_current_time(target_presentation_time);
121- if anim.is_done() {
122+ // HACK: prevent bounciness on hiding. This is better done with a clamp property on
123+ // the spring animation.
124+ if anim.is_done() || anim.value() <= 0. {
122125 self.state = State::Hidden;
123126 }
124127 }