1use crate::arena::SmallVec;
4use crate::element::TransitionSpec;
5use crate::solver::Region;
6use crate::style::{Color, Easing, LoopMode};
7
8#[derive(Copy, Clone, PartialEq, Eq, Debug)]
10pub struct MotionState {
11 pub bounds: Region,
13 pub bg: Color,
15 pub border: Color,
17 pub opacity: u8,
19}
20
21impl MotionState {
22 #[inline(always)]
24 pub const fn new(bounds: Region, bg: Color, border: Color) -> Self {
25 Self {
26 bounds,
27 bg,
28 border,
29 opacity: 255,
30 }
31 }
32
33 #[inline(always)]
35 pub const fn with_opacity(mut self, opacity: u8) -> Self {
36 self.opacity = opacity;
37 self
38 }
39
40 #[inline]
41 fn lerp(self, to: Self, t_256: i32) -> Self {
42 let t_clamped = t_256.clamp(0, 256) as u16;
43 let op = self.opacity as i32 + (((to.opacity as i32 - self.opacity as i32) * t_256) >> 8);
44 Self {
45 bounds: lerp_region_signed(self.bounds, to.bounds, t_256),
46 bg: self.bg.lerp(to.bg, t_clamped),
47 border: self.border.lerp(to.border, t_clamped),
48 opacity: op.clamp(0, 255) as u8,
49 }
50 }
51}
52
53#[derive(Copy, Clone, Debug)]
58struct ActiveTransition {
59 id: u32,
60 path_hash: u32,
61 start_bounds: Region,
62 target_bounds: Region,
63 start_bg: Color,
64 target_bg: Color,
65 start_border: Color,
66 target_border: Color,
67 parent_x: i16,
69 parent_y: i16,
70 elapsed_ms: i16,
72 duration_ms: u16,
74 mode_flags: u8,
76 start_opacity: u8,
77 target_opacity: u8,
78}
79
80const FLAG_REVERSE: u8 = 0x20;
81const FLAG_SEEN: u8 = 0x40;
82
83impl ActiveTransition {
84 #[inline(always)]
85 const fn easing(&self) -> Easing {
86 Easing::from_bits(self.mode_flags)
87 }
88
89 #[inline(always)]
90 const fn loop_mode(&self) -> LoopMode {
91 match (self.mode_flags >> 3) & 0x03 {
92 1 => LoopMode::Infinite,
93 2 => LoopMode::PingPong,
94 _ => LoopMode::Once,
95 }
96 }
97
98 #[inline(always)]
99 const fn is_reverse(&self) -> bool {
100 (self.mode_flags & FLAG_REVERSE) != 0
101 }
102
103 #[inline(always)]
104 const fn seen(&self) -> bool {
105 (self.mode_flags & FLAG_SEEN) != 0
106 }
107
108 #[inline(always)]
109 fn set_seen(&mut self, seen: bool) {
110 if seen {
111 self.mode_flags |= FLAG_SEEN;
112 } else {
113 self.mode_flags &= !FLAG_SEEN;
114 }
115 }
116
117 #[inline(always)]
119 fn set_mode(&mut self, easing: Easing, loop_mode: LoopMode) {
120 self.mode_flags = (easing as u8 & 0x07)
121 | ((loop_mode as u8 & 0x03) << 3)
122 | (self.mode_flags & (FLAG_REVERSE | FLAG_SEEN));
123 }
124
125 #[inline(always)]
126 const fn clamp_duration(ms: u16) -> u16 {
127 if ms > i16::MAX as u16 { i16::MAX as u16 } else { ms }
128 }
129
130 #[inline(always)]
131 const fn delay_to_elapsed(delay_ms: u16) -> i16 {
132 if delay_ms > i16::MAX as u16 {
133 i16::MIN + 1
134 } else {
135 -(delay_ms as i16)
136 }
137 }
138
139 #[inline(always)]
140 const fn is_active(&self) -> bool {
141 if self.duration_ms == 0 {
142 return false;
143 }
144 !matches!(self.loop_mode(), LoopMode::Once) || (self.elapsed_ms as i32) < self.duration_ms as i32
145 }
146
147 #[inline(always)]
148 fn start_state(&self) -> MotionState {
149 MotionState {
150 bounds: self.start_bounds,
151 bg: self.start_bg,
152 border: self.start_border,
153 opacity: self.start_opacity,
154 }
155 }
156
157 #[inline(always)]
158 fn target_state(&self) -> MotionState {
159 MotionState {
160 bounds: self.target_bounds,
161 bg: self.target_bg,
162 border: self.target_border,
163 opacity: self.target_opacity,
164 }
165 }
166
167 #[inline(always)]
168 fn set_start(&mut self, s: MotionState) {
169 self.start_bounds = s.bounds;
170 self.start_bg = s.bg;
171 self.start_border = s.border;
172 self.start_opacity = s.opacity;
173 }
174
175 #[inline(always)]
176 fn set_target(&mut self, s: MotionState) {
177 self.target_bounds = s.bounds;
178 self.target_bg = s.bg;
179 self.target_border = s.border;
180 self.target_opacity = s.opacity;
181 }
182
183 #[inline]
185 fn settle(&mut self, target: MotionState) {
186 self.set_start(target);
187 self.set_target(target);
188 self.elapsed_ms = self.duration_ms as i16;
189 self.mode_flags &= 0x07 | FLAG_SEEN;
190 }
191
192 #[inline]
193 fn current_state(&self) -> MotionState {
194 if self.duration_ms == 0
195 || (matches!(self.loop_mode(), LoopMode::Once)
196 && (self.elapsed_ms as i32) >= self.duration_ms as i32)
197 {
198 return self.target_state();
199 }
200 let phase = self.elapsed_ms.max(0) as u32;
201 let dur = self.duration_ms as u32;
202 let eff = if self.is_reverse() {
203 dur.saturating_sub(phase)
204 } else {
205 phase
206 };
207 let t_256 = self.easing().sample_256(eff, dur);
208 self.start_state().lerp(self.target_state(), t_256)
209 }
210}
211
212#[derive(Copy, Clone, Debug)]
214struct ScrollEntry {
215 id: u32,
216 offset_y: i16,
217 velocity_y: i16,
218 max_scroll: i16,
219}
220
221#[derive(Debug)]
226pub struct MotionCache {
227 transitions: SmallVec<ActiveTransition, 16>,
228 scroll_offsets: SmallVec<ScrollEntry, 16>,
229 scroll_stale_bits: u32,
231}
232
233impl Default for MotionCache {
234 fn default() -> Self {
235 Self::new()
236 }
237}
238
239impl MotionCache {
240 pub const fn new() -> Self {
242 Self {
243 transitions: SmallVec::new(),
244 scroll_offsets: SmallVec::new(),
245 scroll_stale_bits: 0,
246 }
247 }
248
249 #[inline(always)]
250 fn stale_at(&self, idx: usize) -> u8 {
251 if idx < 16 {
252 ((self.scroll_stale_bits >> (idx * 2)) & 0x03) as u8
253 } else {
254 0
255 }
256 }
257
258 #[inline(always)]
259 fn set_stale_at(&mut self, idx: usize, val: u8) {
260 if idx < 16 {
261 let shift = idx * 2;
262 self.scroll_stale_bits = (self.scroll_stale_bits & !(0x03u32 << shift))
263 | (((val.min(3)) as u32) << shift);
264 }
265 }
266
267 pub fn tick(&mut self, dt_ms: u16) -> bool {
270 let mut any_stepped = false;
271 for tr in self.transitions.iter_mut() {
272 if tr.is_active() {
273 any_stepped = true;
274 let dur = tr.duration_ms as i32;
275 let next = tr.elapsed_ms as i32 + dt_ms as i32;
276 if next >= dur {
277 match tr.loop_mode() {
278 LoopMode::Once => {
279 tr.elapsed_ms = dur as i16;
280 }
281 LoopMode::Infinite => {
282 tr.elapsed_ms = (next % dur.max(1)) as i16;
283 }
284 LoopMode::PingPong => {
285 tr.elapsed_ms = (next % dur.max(1)) as i16;
286 tr.mode_flags ^= FLAG_REVERSE;
287 }
288 }
289 } else {
290 tr.elapsed_ms = next as i16;
291 }
292 }
293 }
294
295 for sc in self.scroll_offsets.iter_mut() {
297 if sc.velocity_y != 0 {
298 any_stepped = true;
299 let max_s = if sc.max_scroll >= 0 {
300 sc.max_scroll
301 } else {
302 i16::MAX
303 };
304 let step = (((sc.velocity_y as i32) * (dt_ms.max(1) as i32)) / 16)
305 .clamp(i16::MIN as i32, i16::MAX as i32) as i16;
306 let delta = if step != 0 {
307 step
308 } else if sc.velocity_y > 0 {
309 1
310 } else {
311 -1
312 };
313 let next_off = sc.offset_y.saturating_add(delta).clamp(0, max_s);
314 if next_off == sc.offset_y {
315 sc.velocity_y = 0;
316 } else {
317 sc.offset_y = next_off;
318 sc.velocity_y = (((sc.velocity_y as i32) * 7) / 8) as i16;
319 if sc.velocity_y.abs() <= 1 {
320 sc.velocity_y = 0;
321 }
322 }
323 }
324 }
325 any_stepped
326 }
327
328 #[inline]
330 pub fn has_active_animations(&self) -> bool {
331 self.transitions.iter().any(|t| t.is_active())
332 || self.scroll_offsets.iter().any(|s| s.velocity_y != 0)
333 }
334
335 #[inline]
337 pub fn transition_count(&self) -> usize {
338 self.transitions.len()
339 }
340
341 pub fn begin_frame(&mut self) {
343 for tr in self.transitions.iter_mut() {
344 tr.set_seen(false);
345 }
346 let n = self.scroll_offsets.len().min(16);
347 for idx in 0..n {
348 let next = self.stale_at(idx).saturating_add(1);
349 self.set_stale_at(idx, next);
350 }
351 }
352
353 pub fn end_frame(&mut self) {
355 let mut i = 0;
356 while i < self.transitions.len() {
357 if self.transitions[i].seen() {
358 i += 1;
359 } else {
360 self.transitions.swap_remove(i);
361 }
362 }
363 let mut s_idx = 0;
364 while s_idx < self.scroll_offsets.len() {
365 let stale = self.stale_at(s_idx);
366 let sc = &self.scroll_offsets[s_idx];
367 let evict = sc.velocity_y == 0
368 && (stale >= 3
369 || (stale >= 2 && (sc.offset_y == 0 || self.scroll_offsets.len() > 12)));
370 if evict {
371 let last_idx = self.scroll_offsets.len() - 1;
372 let last_stale = self.stale_at(last_idx);
373 self.scroll_offsets.swap_remove(s_idx);
374 self.set_stale_at(s_idx, last_stale);
375 self.set_stale_at(last_idx, 0);
376 } else {
377 s_idx += 1;
378 }
379 }
380 }
381
382 #[inline]
384 pub(crate) fn sync_scroll_bounds(&mut self, id: u32, max_scroll: i16) {
385 let clamped_max = max_scroll.max(0);
386 if let Some((idx, entry)) = self
387 .scroll_offsets
388 .iter_mut()
389 .enumerate()
390 .find(|(_, e)| e.id == id)
391 {
392 entry.max_scroll = clamped_max;
393 entry.offset_y = entry.offset_y.clamp(0, clamped_max);
394 self.set_stale_at(idx, 0);
395 }
396 }
397
398 pub fn finish_all(&mut self) {
400 for tr in self.transitions.iter_mut() {
401 if !matches!(tr.loop_mode(), LoopMode::Once) {
402 continue;
403 }
404 let target = tr.target_state();
405 tr.settle(target);
406 }
407 }
408
409 pub fn current_state(&self, id: u32) -> Option<MotionState> {
411 self.transitions
412 .iter()
413 .find(|t| t.id == id)
414 .map(|t| t.current_state())
415 }
416
417 pub(crate) fn peek_offset_opacity_scoped(
419 &self,
420 id: u32,
421 path_hash: u32,
422 ) -> Option<(i16, i16, u8)> {
423 self.transitions
424 .iter()
425 .find(|t| t.id == id && t.path_hash == path_hash)
426 .or_else(|| self.transitions.iter().find(|t| t.id == id))
427 .map(|t| {
428 let cur = t.current_state();
429 (
430 cur.bounds.x.saturating_sub(t.target_bounds.x),
431 cur.bounds.y.saturating_sub(t.target_bounds.y),
432 cur.opacity,
433 )
434 })
435 }
436
437 pub fn resolve(
439 &mut self,
440 id: u32,
441 target: MotionState,
442 spec: Option<TransitionSpec>,
443 ) -> MotionState {
444 self.resolve_inner(id, id, (0, 0), target, spec, false)
445 }
446
447 pub(crate) fn resolve_scoped(
454 &mut self,
455 id: u32,
456 path_hash: u32,
457 parent_origin: (i16, i16),
458 target: MotionState,
459 spec: Option<TransitionSpec>,
460 ) -> MotionState {
461 self.resolve_inner(id, path_hash, parent_origin, target, spec, true)
462 }
463
464 fn resolve_inner(
465 &mut self,
466 id: u32,
467 path_hash: u32,
468 parent_origin: (i16, i16),
469 target: MotionState,
470 spec: Option<TransitionSpec>,
471 guard_same_frame_dup: bool,
472 ) -> MotionState {
473 let matched_idx = self
474 .transitions
475 .iter()
476 .position(|t| t.id == id && t.path_hash == path_hash)
477 .or_else(|| {
478 if spec.is_some() {
479 self.transitions
480 .iter()
481 .position(|t| t.id == id && (!guard_same_frame_dup || !t.seen()))
482 } else {
483 None
484 }
485 });
486
487 if let Some(idx) = matched_idx {
488 let tr = &mut self.transitions[idx];
489 if guard_same_frame_dup && tr.seen() {
490 return target;
492 }
493 let same_parent = tr.path_hash == path_hash;
494 if same_parent {
495 let pdx = parent_origin.0.saturating_sub(tr.parent_x);
496 let pdy = parent_origin.1.saturating_sub(tr.parent_y);
497 if pdx != 0 || pdy != 0 {
498 tr.start_bounds.x = tr.start_bounds.x.saturating_add(pdx);
499 tr.start_bounds.y = tr.start_bounds.y.saturating_add(pdy);
500 tr.target_bounds.x = tr.target_bounds.x.saturating_add(pdx);
501 tr.target_bounds.y = tr.target_bounds.y.saturating_add(pdy);
502 }
503 }
504 tr.parent_x = parent_origin.0;
505 tr.parent_y = parent_origin.1;
506 tr.path_hash = path_hash;
507 tr.set_seen(true);
508 let Some(s) = spec else {
509 tr.settle(target);
510 return target;
511 };
512 tr.set_mode(s.easing, s.loop_mode);
513
514 if let Some(pulse_from) = s.pulse_from_bg {
515 tr.set_start(MotionState {
516 bg: pulse_from,
517 ..target
518 });
519 tr.set_target(target);
520 tr.duration_ms = ActiveTransition::clamp_duration(s.duration_ms.max(1));
521 return tr.current_state();
522 }
523
524 let color_changed = s.animate_color
525 && (tr.target_bg != target.bg || tr.target_border != target.border);
526 let bounds_changed = s.animate_bounds && tr.target_bounds != target.bounds;
527 let opacity_changed = s.animate_opacity && tr.target_opacity != target.opacity;
528
529 if color_changed || bounds_changed || opacity_changed {
530 let in_flight = tr.is_active();
532 let cur = tr.current_state();
533 tr.set_start(MotionState {
534 bounds: if s.animate_bounds || in_flight {
535 cur.bounds
536 } else {
537 target.bounds
538 },
539 bg: if s.animate_color || in_flight {
540 cur.bg
541 } else {
542 target.bg
543 },
544 border: if s.animate_color || in_flight {
545 cur.border
546 } else {
547 target.border
548 },
549 opacity: if s.animate_opacity || in_flight {
550 cur.opacity
551 } else {
552 target.opacity
553 },
554 });
555 tr.set_target(target);
556 tr.duration_ms = ActiveTransition::clamp_duration(s.duration_ms.max(1));
557 tr.elapsed_ms = ActiveTransition::delay_to_elapsed(s.delay_ms);
558 } else if !tr.is_active() {
559 tr.set_start(target);
560 tr.set_target(target);
561 } else {
562 if tr.target_bounds != target.bounds {
564 let dx = target.bounds.x.saturating_sub(tr.target_bounds.x);
565 let dy = target.bounds.y.saturating_sub(tr.target_bounds.y);
566 tr.start_bounds = Region::new(
567 tr.start_bounds.x.saturating_add(dx),
568 tr.start_bounds.y.saturating_add(dy),
569 target.bounds.w,
570 target.bounds.h,
571 );
572 tr.target_bounds = target.bounds;
573 }
574 if tr.target_bg != target.bg || tr.target_border != target.border {
575 tr.start_bg = target.bg;
576 tr.start_border = target.border;
577 tr.target_bg = target.bg;
578 tr.target_border = target.border;
579 }
580 tr.target_opacity = target.opacity;
581 }
582 return tr.current_state();
583 }
584
585 let Some(s) = spec else {
587 return target;
588 };
589 let mut start = target;
590 if let Some(pulse_from) = s.pulse_from_bg {
591 start.bg = pulse_from;
592 }
593 if let Some(enter) = s.enter {
594 start.opacity = enter.opacity;
595 start.bounds = Region::new(
596 target.bounds.x.saturating_add(enter.dx),
597 target.bounds.y.saturating_add(enter.dy),
598 target.bounds.w,
599 target.bounds.h,
600 );
601 }
602 let animating = s.enter.is_some() || !matches!(s.loop_mode, LoopMode::Once);
603 let duration_ms = ActiveTransition::clamp_duration(s.duration_ms);
604 let mut entry = ActiveTransition {
605 id,
606 path_hash,
607 start_bounds: start.bounds,
608 target_bounds: target.bounds,
609 start_bg: start.bg,
610 target_bg: target.bg,
611 start_border: start.border,
612 target_border: target.border,
613 parent_x: parent_origin.0,
614 parent_y: parent_origin.1,
615 elapsed_ms: if animating {
616 ActiveTransition::delay_to_elapsed(s.delay_ms)
617 } else {
618 duration_ms as i16
619 },
620 duration_ms,
621 mode_flags: FLAG_SEEN,
622 start_opacity: start.opacity,
623 target_opacity: target.opacity,
624 };
625 entry.set_mode(s.easing, s.loop_mode);
626 let state = entry.current_state();
627 if !self.transitions.push(entry) {
628 if let Some(slot) = self.transitions.iter_mut().find(|t| !t.is_active()) {
630 *slot = entry;
631 } else {
632 return target;
633 }
634 }
635 state
636 }
637
638 pub fn resolve_div(
640 &mut self,
641 id: u32,
642 target_bounds: Region,
643 target_bg: Color,
644 target_border: Color,
645 spec: Option<TransitionSpec>,
646 ) -> (Region, Color, Color) {
647 let st = self.resolve(
648 id,
649 MotionState::new(target_bounds, target_bg, target_border),
650 spec,
651 );
652 (st.bounds, st.bg, st.border)
653 }
654
655 pub fn resolve_text_color(&mut self, id: u32, target_color: Color, duration_ms: u16) -> Color {
657 self.resolve_text_color_with(
658 id,
659 target_color,
660 TransitionSpec {
661 duration_ms,
662 ..TransitionSpec::default()
663 },
664 )
665 }
666
667 pub fn resolve_text_color_with(
669 &mut self,
670 id: u32,
671 target_color: Color,
672 parent: TransitionSpec,
673 ) -> Color {
674 let spec = TransitionSpec {
675 duration_ms: parent.duration_ms,
676 delay_ms: parent.delay_ms,
677 easing: parent.easing,
678 animate_color: true,
679 ..TransitionSpec::default()
680 };
681 self.resolve(
682 id,
683 MotionState::new(Region::EMPTY, target_color, Color::TRANSPARENT),
684 Some(spec),
685 )
686 .bg
687 }
688
689 pub fn scroll_offset(&self, id: u32) -> i16 {
691 self.scroll_offsets
692 .iter()
693 .find(|e| e.id == id)
694 .map(|e| e.offset_y)
695 .unwrap_or(0)
696 }
697
698 fn insert_scroll_entry(&mut self, entry: ScrollEntry) {
699 if self.scroll_offsets.len() >= 64 {
700 if let Some((idx, _)) = (0..self.scroll_offsets.len())
701 .filter(|&i| self.scroll_offsets[i].velocity_y == 0)
702 .map(|i| (i, self.stale_at(i)))
703 .max_by_key(|&(_, st)| st)
704 {
705 self.scroll_offsets[idx] = entry;
706 self.set_stale_at(idx, 0);
707 return;
708 }
709 self.scroll_offsets[0] = entry;
710 self.set_stale_at(0, 0);
711 return;
712 }
713 let new_idx = self.scroll_offsets.len();
714 if self.scroll_offsets.push(entry) {
715 self.set_stale_at(new_idx, 0);
716 } else if let Some((idx, _)) = (0..self.scroll_offsets.len())
717 .map(|i| (i, (self.scroll_offsets[i].velocity_y == 0, self.stale_at(i))))
718 .max_by_key(|&(_, k)| k)
719 {
720 self.scroll_offsets[idx] = entry;
721 self.set_stale_at(idx, 0);
722 }
723 }
724
725 pub fn set_scroll_offset(&mut self, id: u32, offset_y: i16) {
727 if let Some((idx, entry)) = self
728 .scroll_offsets
729 .iter_mut()
730 .enumerate()
731 .find(|(_, e)| e.id == id)
732 {
733 let max_s = if entry.max_scroll >= 0 {
734 entry.max_scroll
735 } else {
736 i16::MAX
737 };
738 entry.offset_y = offset_y.clamp(0, max_s);
739 self.set_stale_at(idx, 0);
740 } else {
741 self.insert_scroll_entry(ScrollEntry {
742 id,
743 offset_y: offset_y.max(0),
744 velocity_y: 0,
745 max_scroll: -1,
746 });
747 }
748 }
749
750 pub fn set_scroll_inertia(&mut self, id: u32, velocity_y: i16, max_scroll: i16) {
752 if let Some((idx, entry)) = self
753 .scroll_offsets
754 .iter_mut()
755 .enumerate()
756 .find(|(_, e)| e.id == id)
757 {
758 entry.velocity_y = velocity_y;
759 if max_scroll >= 0 {
760 entry.max_scroll = max_scroll;
761 entry.offset_y = entry.offset_y.clamp(0, max_scroll);
762 }
763 self.set_stale_at(idx, 0);
764 } else {
765 let eff_max = if max_scroll >= 0 { max_scroll } else { -1 };
766 self.insert_scroll_entry(ScrollEntry {
767 id,
768 offset_y: 0,
769 velocity_y,
770 max_scroll: eff_max,
771 });
772 }
773 }
774}
775
776#[inline]
777fn lerp_i16_signed(a: i16, b: i16, t_256: i32) -> i16 {
778 let diff = (b as i32) - (a as i32);
779 let val = (a as i32) + ((diff * t_256) >> 8);
780 val.clamp(i16::MIN as i32, i16::MAX as i32) as i16
781}
782
783#[inline]
784fn lerp_region_signed(a: Region, b: Region, t_256: i32) -> Region {
785 Region {
786 x: lerp_i16_signed(a.x, b.x, t_256),
787 y: lerp_i16_signed(a.y, b.y, t_256),
788 w: lerp_i16_signed(a.w, b.w, t_256).max(0),
789 h: lerp_i16_signed(a.h, b.h, t_256).max(0),
790 }
791}
792